lib.rs 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960
  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, Clone, Default, PartialEq)]
  575. pub struct PluginRegistry {
  576. plugins: Vec<RegisteredPlugin>,
  577. }
  578. impl PluginRegistry {
  579. #[must_use]
  580. pub fn new(mut plugins: Vec<RegisteredPlugin>) -> Self {
  581. plugins.sort_by(|left, right| left.metadata().id.cmp(&right.metadata().id));
  582. Self { plugins }
  583. }
  584. #[must_use]
  585. pub fn plugins(&self) -> &[RegisteredPlugin] {
  586. &self.plugins
  587. }
  588. #[must_use]
  589. pub fn get(&self, plugin_id: &str) -> Option<&RegisteredPlugin> {
  590. self.plugins
  591. .iter()
  592. .find(|plugin| plugin.metadata().id == plugin_id)
  593. }
  594. #[must_use]
  595. pub fn contains(&self, plugin_id: &str) -> bool {
  596. self.get(plugin_id).is_some()
  597. }
  598. #[must_use]
  599. pub fn summaries(&self) -> Vec<PluginSummary> {
  600. self.plugins.iter().map(RegisteredPlugin::summary).collect()
  601. }
  602. pub fn aggregated_hooks(&self) -> Result<PluginHooks, PluginError> {
  603. self.plugins
  604. .iter()
  605. .filter(|plugin| plugin.is_enabled())
  606. .try_fold(PluginHooks::default(), |acc, plugin| {
  607. plugin.validate()?;
  608. Ok(acc.merged_with(plugin.hooks()))
  609. })
  610. }
  611. pub fn aggregated_tools(&self) -> Result<Vec<PluginTool>, PluginError> {
  612. let mut tools = Vec::new();
  613. let mut seen_names = BTreeMap::new();
  614. for plugin in self.plugins.iter().filter(|plugin| plugin.is_enabled()) {
  615. plugin.validate()?;
  616. for tool in plugin.tools() {
  617. if let Some(existing_plugin) =
  618. seen_names.insert(tool.definition().name.clone(), tool.plugin_id().to_string())
  619. {
  620. return Err(PluginError::InvalidManifest(format!(
  621. "plugin tool `{}` is defined by both `{existing_plugin}` and `{}`",
  622. tool.definition().name,
  623. tool.plugin_id()
  624. )));
  625. }
  626. tools.push(tool.clone());
  627. }
  628. }
  629. Ok(tools)
  630. }
  631. pub fn initialize(&self) -> Result<(), PluginError> {
  632. for plugin in self.plugins.iter().filter(|plugin| plugin.is_enabled()) {
  633. plugin.validate()?;
  634. plugin.initialize()?;
  635. }
  636. Ok(())
  637. }
  638. pub fn shutdown(&self) -> Result<(), PluginError> {
  639. for plugin in self
  640. .plugins
  641. .iter()
  642. .rev()
  643. .filter(|plugin| plugin.is_enabled())
  644. {
  645. plugin.shutdown()?;
  646. }
  647. Ok(())
  648. }
  649. }
  650. #[derive(Debug, Clone, PartialEq, Eq)]
  651. pub struct PluginManagerConfig {
  652. pub config_home: PathBuf,
  653. pub enabled_plugins: BTreeMap<String, bool>,
  654. pub external_dirs: Vec<PathBuf>,
  655. pub install_root: Option<PathBuf>,
  656. pub registry_path: Option<PathBuf>,
  657. pub bundled_root: Option<PathBuf>,
  658. }
  659. impl PluginManagerConfig {
  660. #[must_use]
  661. pub fn new(config_home: impl Into<PathBuf>) -> Self {
  662. Self {
  663. config_home: config_home.into(),
  664. enabled_plugins: BTreeMap::new(),
  665. external_dirs: Vec::new(),
  666. install_root: None,
  667. registry_path: None,
  668. bundled_root: None,
  669. }
  670. }
  671. }
  672. #[derive(Debug, Clone, PartialEq, Eq)]
  673. pub struct PluginManager {
  674. config: PluginManagerConfig,
  675. }
  676. #[derive(Debug, Clone, PartialEq, Eq)]
  677. pub struct InstallOutcome {
  678. pub plugin_id: String,
  679. pub version: String,
  680. pub install_path: PathBuf,
  681. }
  682. #[derive(Debug, Clone, PartialEq, Eq)]
  683. pub struct UpdateOutcome {
  684. pub plugin_id: String,
  685. pub old_version: String,
  686. pub new_version: String,
  687. pub install_path: PathBuf,
  688. }
  689. #[derive(Debug, Clone, PartialEq, Eq)]
  690. pub enum PluginManifestValidationError {
  691. EmptyField {
  692. field: &'static str,
  693. },
  694. EmptyEntryField {
  695. kind: &'static str,
  696. field: &'static str,
  697. name: Option<String>,
  698. },
  699. InvalidPermission {
  700. permission: String,
  701. },
  702. DuplicatePermission {
  703. permission: String,
  704. },
  705. DuplicateEntry {
  706. kind: &'static str,
  707. name: String,
  708. },
  709. MissingPath {
  710. kind: &'static str,
  711. path: PathBuf,
  712. },
  713. InvalidToolInputSchema {
  714. tool_name: String,
  715. },
  716. InvalidToolRequiredPermission {
  717. tool_name: String,
  718. permission: String,
  719. },
  720. }
  721. impl Display for PluginManifestValidationError {
  722. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  723. match self {
  724. Self::EmptyField { field } => {
  725. write!(f, "plugin manifest {field} cannot be empty")
  726. }
  727. Self::EmptyEntryField { kind, field, name } => match name {
  728. Some(name) if !name.is_empty() => {
  729. write!(f, "plugin {kind} `{name}` {field} cannot be empty")
  730. }
  731. _ => write!(f, "plugin {kind} {field} cannot be empty"),
  732. },
  733. Self::InvalidPermission { permission } => {
  734. write!(
  735. f,
  736. "plugin manifest permission `{permission}` must be one of read, write, or execute"
  737. )
  738. }
  739. Self::DuplicatePermission { permission } => {
  740. write!(f, "plugin manifest permission `{permission}` is duplicated")
  741. }
  742. Self::DuplicateEntry { kind, name } => {
  743. write!(f, "plugin {kind} `{name}` is duplicated")
  744. }
  745. Self::MissingPath { kind, path } => {
  746. write!(f, "{kind} path `{}` does not exist", path.display())
  747. }
  748. Self::InvalidToolInputSchema { tool_name } => {
  749. write!(
  750. f,
  751. "plugin tool `{tool_name}` inputSchema must be a JSON object"
  752. )
  753. }
  754. Self::InvalidToolRequiredPermission {
  755. tool_name,
  756. permission,
  757. } => write!(
  758. f,
  759. "plugin tool `{tool_name}` requiredPermission `{permission}` must be read-only, workspace-write, or danger-full-access"
  760. ),
  761. }
  762. }
  763. }
  764. #[derive(Debug)]
  765. pub enum PluginError {
  766. Io(std::io::Error),
  767. Json(serde_json::Error),
  768. ManifestValidation(Vec<PluginManifestValidationError>),
  769. InvalidManifest(String),
  770. NotFound(String),
  771. CommandFailed(String),
  772. }
  773. impl Display for PluginError {
  774. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  775. match self {
  776. Self::Io(error) => write!(f, "{error}"),
  777. Self::Json(error) => write!(f, "{error}"),
  778. Self::ManifestValidation(errors) => {
  779. for (index, error) in errors.iter().enumerate() {
  780. if index > 0 {
  781. write!(f, "; ")?;
  782. }
  783. write!(f, "{error}")?;
  784. }
  785. Ok(())
  786. }
  787. Self::InvalidManifest(message)
  788. | Self::NotFound(message)
  789. | Self::CommandFailed(message) => write!(f, "{message}"),
  790. }
  791. }
  792. }
  793. impl std::error::Error for PluginError {}
  794. impl From<std::io::Error> for PluginError {
  795. fn from(value: std::io::Error) -> Self {
  796. Self::Io(value)
  797. }
  798. }
  799. impl From<serde_json::Error> for PluginError {
  800. fn from(value: serde_json::Error) -> Self {
  801. Self::Json(value)
  802. }
  803. }
  804. impl PluginManager {
  805. #[must_use]
  806. pub fn new(config: PluginManagerConfig) -> Self {
  807. Self { config }
  808. }
  809. #[must_use]
  810. pub fn bundled_root() -> PathBuf {
  811. PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("bundled")
  812. }
  813. #[must_use]
  814. pub fn install_root(&self) -> PathBuf {
  815. self.config
  816. .install_root
  817. .clone()
  818. .unwrap_or_else(|| self.config.config_home.join("plugins").join("installed"))
  819. }
  820. #[must_use]
  821. pub fn registry_path(&self) -> PathBuf {
  822. self.config.registry_path.clone().unwrap_or_else(|| {
  823. self.config
  824. .config_home
  825. .join("plugins")
  826. .join(REGISTRY_FILE_NAME)
  827. })
  828. }
  829. #[must_use]
  830. pub fn settings_path(&self) -> PathBuf {
  831. self.config.config_home.join(SETTINGS_FILE_NAME)
  832. }
  833. pub fn plugin_registry(&self) -> Result<PluginRegistry, PluginError> {
  834. Ok(PluginRegistry::new(
  835. self.discover_plugins()?
  836. .into_iter()
  837. .map(|plugin| {
  838. let enabled = self.is_enabled(plugin.metadata());
  839. RegisteredPlugin::new(plugin, enabled)
  840. })
  841. .collect(),
  842. ))
  843. }
  844. pub fn list_plugins(&self) -> Result<Vec<PluginSummary>, PluginError> {
  845. Ok(self.plugin_registry()?.summaries())
  846. }
  847. pub fn list_installed_plugins(&self) -> Result<Vec<PluginSummary>, PluginError> {
  848. Ok(self.installed_plugin_registry()?.summaries())
  849. }
  850. pub fn discover_plugins(&self) -> Result<Vec<PluginDefinition>, PluginError> {
  851. self.sync_bundled_plugins()?;
  852. let mut plugins = builtin_plugins();
  853. plugins.extend(self.discover_installed_plugins()?);
  854. plugins.extend(self.discover_external_directory_plugins(&plugins)?);
  855. Ok(plugins)
  856. }
  857. pub fn aggregated_hooks(&self) -> Result<PluginHooks, PluginError> {
  858. self.plugin_registry()?.aggregated_hooks()
  859. }
  860. pub fn aggregated_tools(&self) -> Result<Vec<PluginTool>, PluginError> {
  861. self.plugin_registry()?.aggregated_tools()
  862. }
  863. pub fn validate_plugin_source(&self, source: &str) -> Result<PluginManifest, PluginError> {
  864. let path = resolve_local_source(source)?;
  865. load_plugin_from_directory(&path)
  866. }
  867. pub fn install(&mut self, source: &str) -> Result<InstallOutcome, PluginError> {
  868. let install_source = parse_install_source(source)?;
  869. let temp_root = self.install_root().join(".tmp");
  870. let staged_source = materialize_source(&install_source, &temp_root)?;
  871. let cleanup_source = matches!(install_source, PluginInstallSource::GitUrl { .. });
  872. let manifest = load_plugin_from_directory(&staged_source)?;
  873. let plugin_id = plugin_id(&manifest.name, EXTERNAL_MARKETPLACE);
  874. let install_path = self.install_root().join(sanitize_plugin_id(&plugin_id));
  875. if install_path.exists() {
  876. fs::remove_dir_all(&install_path)?;
  877. }
  878. copy_dir_all(&staged_source, &install_path)?;
  879. if cleanup_source {
  880. let _ = fs::remove_dir_all(&staged_source);
  881. }
  882. let now = unix_time_ms();
  883. let record = InstalledPluginRecord {
  884. kind: PluginKind::External,
  885. id: plugin_id.clone(),
  886. name: manifest.name,
  887. version: manifest.version.clone(),
  888. description: manifest.description,
  889. install_path: install_path.clone(),
  890. source: install_source,
  891. installed_at_unix_ms: now,
  892. updated_at_unix_ms: now,
  893. };
  894. let mut registry = self.load_registry()?;
  895. registry.plugins.insert(plugin_id.clone(), record);
  896. self.store_registry(&registry)?;
  897. self.write_enabled_state(&plugin_id, Some(true))?;
  898. self.config.enabled_plugins.insert(plugin_id.clone(), true);
  899. Ok(InstallOutcome {
  900. plugin_id,
  901. version: manifest.version,
  902. install_path,
  903. })
  904. }
  905. pub fn enable(&mut self, plugin_id: &str) -> Result<(), PluginError> {
  906. self.ensure_known_plugin(plugin_id)?;
  907. self.write_enabled_state(plugin_id, Some(true))?;
  908. self.config
  909. .enabled_plugins
  910. .insert(plugin_id.to_string(), true);
  911. Ok(())
  912. }
  913. pub fn disable(&mut self, plugin_id: &str) -> Result<(), PluginError> {
  914. self.ensure_known_plugin(plugin_id)?;
  915. self.write_enabled_state(plugin_id, Some(false))?;
  916. self.config
  917. .enabled_plugins
  918. .insert(plugin_id.to_string(), false);
  919. Ok(())
  920. }
  921. pub fn uninstall(&mut self, plugin_id: &str) -> Result<(), PluginError> {
  922. let mut registry = self.load_registry()?;
  923. let record = registry.plugins.remove(plugin_id).ok_or_else(|| {
  924. PluginError::NotFound(format!("plugin `{plugin_id}` is not installed"))
  925. })?;
  926. if record.kind == PluginKind::Bundled {
  927. registry.plugins.insert(plugin_id.to_string(), record);
  928. return Err(PluginError::CommandFailed(format!(
  929. "plugin `{plugin_id}` is bundled and managed automatically; disable it instead"
  930. )));
  931. }
  932. if record.install_path.exists() {
  933. fs::remove_dir_all(&record.install_path)?;
  934. }
  935. self.store_registry(&registry)?;
  936. self.write_enabled_state(plugin_id, None)?;
  937. self.config.enabled_plugins.remove(plugin_id);
  938. Ok(())
  939. }
  940. pub fn update(&mut self, plugin_id: &str) -> Result<UpdateOutcome, PluginError> {
  941. let mut registry = self.load_registry()?;
  942. let record = registry.plugins.get(plugin_id).cloned().ok_or_else(|| {
  943. PluginError::NotFound(format!("plugin `{plugin_id}` is not installed"))
  944. })?;
  945. let temp_root = self.install_root().join(".tmp");
  946. let staged_source = materialize_source(&record.source, &temp_root)?;
  947. let cleanup_source = matches!(record.source, PluginInstallSource::GitUrl { .. });
  948. let manifest = load_plugin_from_directory(&staged_source)?;
  949. if record.install_path.exists() {
  950. fs::remove_dir_all(&record.install_path)?;
  951. }
  952. copy_dir_all(&staged_source, &record.install_path)?;
  953. if cleanup_source {
  954. let _ = fs::remove_dir_all(&staged_source);
  955. }
  956. let updated_record = InstalledPluginRecord {
  957. version: manifest.version.clone(),
  958. description: manifest.description,
  959. updated_at_unix_ms: unix_time_ms(),
  960. ..record.clone()
  961. };
  962. registry
  963. .plugins
  964. .insert(plugin_id.to_string(), updated_record);
  965. self.store_registry(&registry)?;
  966. Ok(UpdateOutcome {
  967. plugin_id: plugin_id.to_string(),
  968. old_version: record.version,
  969. new_version: manifest.version,
  970. install_path: record.install_path,
  971. })
  972. }
  973. fn discover_installed_plugins(&self) -> Result<Vec<PluginDefinition>, PluginError> {
  974. let mut registry = self.load_registry()?;
  975. let mut plugins = Vec::new();
  976. let mut seen_ids = BTreeSet::<String>::new();
  977. let mut seen_paths = BTreeSet::<PathBuf>::new();
  978. let mut stale_registry_ids = Vec::new();
  979. for install_path in discover_plugin_dirs(&self.install_root())? {
  980. let matched_record = registry
  981. .plugins
  982. .values()
  983. .find(|record| record.install_path == install_path);
  984. let kind = matched_record.map_or(PluginKind::External, |record| record.kind);
  985. let source = matched_record.map_or_else(
  986. || install_path.display().to_string(),
  987. |record| describe_install_source(&record.source),
  988. );
  989. let plugin = load_plugin_definition(&install_path, kind, source, kind.marketplace())?;
  990. if seen_ids.insert(plugin.metadata().id.clone()) {
  991. seen_paths.insert(install_path);
  992. plugins.push(plugin);
  993. }
  994. }
  995. for record in registry.plugins.values() {
  996. if seen_paths.contains(&record.install_path) {
  997. continue;
  998. }
  999. if !record.install_path.exists() || plugin_manifest_path(&record.install_path).is_err()
  1000. {
  1001. stale_registry_ids.push(record.id.clone());
  1002. continue;
  1003. }
  1004. let plugin = load_plugin_definition(
  1005. &record.install_path,
  1006. record.kind,
  1007. describe_install_source(&record.source),
  1008. record.kind.marketplace(),
  1009. )?;
  1010. if seen_ids.insert(plugin.metadata().id.clone()) {
  1011. seen_paths.insert(record.install_path.clone());
  1012. plugins.push(plugin);
  1013. }
  1014. }
  1015. if !stale_registry_ids.is_empty() {
  1016. for plugin_id in stale_registry_ids {
  1017. registry.plugins.remove(&plugin_id);
  1018. }
  1019. self.store_registry(&registry)?;
  1020. }
  1021. Ok(plugins)
  1022. }
  1023. fn discover_external_directory_plugins(
  1024. &self,
  1025. existing_plugins: &[PluginDefinition],
  1026. ) -> Result<Vec<PluginDefinition>, PluginError> {
  1027. let mut plugins = Vec::new();
  1028. for directory in &self.config.external_dirs {
  1029. for root in discover_plugin_dirs(directory)? {
  1030. let plugin = load_plugin_definition(
  1031. &root,
  1032. PluginKind::External,
  1033. root.display().to_string(),
  1034. EXTERNAL_MARKETPLACE,
  1035. )?;
  1036. if existing_plugins
  1037. .iter()
  1038. .chain(plugins.iter())
  1039. .all(|existing| existing.metadata().id != plugin.metadata().id)
  1040. {
  1041. plugins.push(plugin);
  1042. }
  1043. }
  1044. }
  1045. Ok(plugins)
  1046. }
  1047. fn installed_plugin_registry(&self) -> Result<PluginRegistry, PluginError> {
  1048. self.sync_bundled_plugins()?;
  1049. Ok(PluginRegistry::new(
  1050. self.discover_installed_plugins()?
  1051. .into_iter()
  1052. .map(|plugin| {
  1053. let enabled = self.is_enabled(plugin.metadata());
  1054. RegisteredPlugin::new(plugin, enabled)
  1055. })
  1056. .collect(),
  1057. ))
  1058. }
  1059. fn sync_bundled_plugins(&self) -> Result<(), PluginError> {
  1060. let bundled_root = self
  1061. .config
  1062. .bundled_root
  1063. .clone()
  1064. .unwrap_or_else(Self::bundled_root);
  1065. let bundled_plugins = discover_plugin_dirs(&bundled_root)?;
  1066. let mut registry = self.load_registry()?;
  1067. let mut changed = false;
  1068. let install_root = self.install_root();
  1069. let mut active_bundled_ids = BTreeSet::new();
  1070. for source_root in bundled_plugins {
  1071. let manifest = load_plugin_from_directory(&source_root)?;
  1072. let plugin_id = plugin_id(&manifest.name, BUNDLED_MARKETPLACE);
  1073. active_bundled_ids.insert(plugin_id.clone());
  1074. let install_path = install_root.join(sanitize_plugin_id(&plugin_id));
  1075. let now = unix_time_ms();
  1076. let existing_record = registry.plugins.get(&plugin_id);
  1077. let installed_copy_is_valid =
  1078. install_path.exists() && load_plugin_from_directory(&install_path).is_ok();
  1079. let needs_sync = existing_record.is_none_or(|record| {
  1080. record.kind != PluginKind::Bundled
  1081. || record.version != manifest.version
  1082. || record.name != manifest.name
  1083. || record.description != manifest.description
  1084. || record.install_path != install_path
  1085. || !record.install_path.exists()
  1086. || !installed_copy_is_valid
  1087. });
  1088. if !needs_sync {
  1089. continue;
  1090. }
  1091. if install_path.exists() {
  1092. fs::remove_dir_all(&install_path)?;
  1093. }
  1094. copy_dir_all(&source_root, &install_path)?;
  1095. let installed_at_unix_ms =
  1096. existing_record.map_or(now, |record| record.installed_at_unix_ms);
  1097. registry.plugins.insert(
  1098. plugin_id.clone(),
  1099. InstalledPluginRecord {
  1100. kind: PluginKind::Bundled,
  1101. id: plugin_id,
  1102. name: manifest.name,
  1103. version: manifest.version,
  1104. description: manifest.description,
  1105. install_path,
  1106. source: PluginInstallSource::LocalPath { path: source_root },
  1107. installed_at_unix_ms,
  1108. updated_at_unix_ms: now,
  1109. },
  1110. );
  1111. changed = true;
  1112. }
  1113. let stale_bundled_ids = registry
  1114. .plugins
  1115. .iter()
  1116. .filter_map(|(plugin_id, record)| {
  1117. (record.kind == PluginKind::Bundled && !active_bundled_ids.contains(plugin_id))
  1118. .then_some(plugin_id.clone())
  1119. })
  1120. .collect::<Vec<_>>();
  1121. for plugin_id in stale_bundled_ids {
  1122. if let Some(record) = registry.plugins.remove(&plugin_id) {
  1123. if record.install_path.exists() {
  1124. fs::remove_dir_all(&record.install_path)?;
  1125. }
  1126. changed = true;
  1127. }
  1128. }
  1129. if changed {
  1130. self.store_registry(&registry)?;
  1131. }
  1132. Ok(())
  1133. }
  1134. fn is_enabled(&self, metadata: &PluginMetadata) -> bool {
  1135. self.config
  1136. .enabled_plugins
  1137. .get(&metadata.id)
  1138. .copied()
  1139. .unwrap_or(match metadata.kind {
  1140. PluginKind::External => false,
  1141. PluginKind::Builtin | PluginKind::Bundled => metadata.default_enabled,
  1142. })
  1143. }
  1144. fn ensure_known_plugin(&self, plugin_id: &str) -> Result<(), PluginError> {
  1145. if self.plugin_registry()?.contains(plugin_id) {
  1146. Ok(())
  1147. } else {
  1148. Err(PluginError::NotFound(format!(
  1149. "plugin `{plugin_id}` is not installed or discoverable"
  1150. )))
  1151. }
  1152. }
  1153. fn load_registry(&self) -> Result<InstalledPluginRegistry, PluginError> {
  1154. let path = self.registry_path();
  1155. match fs::read_to_string(&path) {
  1156. Ok(contents) if contents.trim().is_empty() => Ok(InstalledPluginRegistry::default()),
  1157. Ok(contents) => Ok(serde_json::from_str(&contents)?),
  1158. Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
  1159. Ok(InstalledPluginRegistry::default())
  1160. }
  1161. Err(error) => Err(PluginError::Io(error)),
  1162. }
  1163. }
  1164. fn store_registry(&self, registry: &InstalledPluginRegistry) -> Result<(), PluginError> {
  1165. let path = self.registry_path();
  1166. if let Some(parent) = path.parent() {
  1167. fs::create_dir_all(parent)?;
  1168. }
  1169. fs::write(path, serde_json::to_string_pretty(registry)?)?;
  1170. Ok(())
  1171. }
  1172. fn write_enabled_state(
  1173. &self,
  1174. plugin_id: &str,
  1175. enabled: Option<bool>,
  1176. ) -> Result<(), PluginError> {
  1177. update_settings_json(&self.settings_path(), |root| {
  1178. let enabled_plugins = ensure_object(root, "enabledPlugins");
  1179. match enabled {
  1180. Some(value) => {
  1181. enabled_plugins.insert(plugin_id.to_string(), Value::Bool(value));
  1182. }
  1183. None => {
  1184. enabled_plugins.remove(plugin_id);
  1185. }
  1186. }
  1187. })
  1188. }
  1189. }
  1190. #[must_use]
  1191. pub fn builtin_plugins() -> Vec<PluginDefinition> {
  1192. vec![PluginDefinition::Builtin(BuiltinPlugin {
  1193. metadata: PluginMetadata {
  1194. id: plugin_id("example-builtin", BUILTIN_MARKETPLACE),
  1195. name: "example-builtin".to_string(),
  1196. version: "0.1.0".to_string(),
  1197. description: "Example built-in plugin scaffold for the Rust plugin system".to_string(),
  1198. kind: PluginKind::Builtin,
  1199. source: BUILTIN_MARKETPLACE.to_string(),
  1200. default_enabled: false,
  1201. root: None,
  1202. },
  1203. hooks: PluginHooks::default(),
  1204. lifecycle: PluginLifecycle::default(),
  1205. tools: Vec::new(),
  1206. })]
  1207. }
  1208. fn load_plugin_definition(
  1209. root: &Path,
  1210. kind: PluginKind,
  1211. source: String,
  1212. marketplace: &str,
  1213. ) -> Result<PluginDefinition, PluginError> {
  1214. let manifest = load_plugin_from_directory(root)?;
  1215. let metadata = PluginMetadata {
  1216. id: plugin_id(&manifest.name, marketplace),
  1217. name: manifest.name,
  1218. version: manifest.version,
  1219. description: manifest.description,
  1220. kind,
  1221. source,
  1222. default_enabled: manifest.default_enabled,
  1223. root: Some(root.to_path_buf()),
  1224. };
  1225. let hooks = resolve_hooks(root, &manifest.hooks);
  1226. let lifecycle = resolve_lifecycle(root, &manifest.lifecycle);
  1227. let tools = resolve_tools(root, &metadata.id, &metadata.name, &manifest.tools);
  1228. Ok(match kind {
  1229. PluginKind::Builtin => PluginDefinition::Builtin(BuiltinPlugin {
  1230. metadata,
  1231. hooks,
  1232. lifecycle,
  1233. tools,
  1234. }),
  1235. PluginKind::Bundled => PluginDefinition::Bundled(BundledPlugin {
  1236. metadata,
  1237. hooks,
  1238. lifecycle,
  1239. tools,
  1240. }),
  1241. PluginKind::External => PluginDefinition::External(ExternalPlugin {
  1242. metadata,
  1243. hooks,
  1244. lifecycle,
  1245. tools,
  1246. }),
  1247. })
  1248. }
  1249. pub fn load_plugin_from_directory(root: &Path) -> Result<PluginManifest, PluginError> {
  1250. load_manifest_from_directory(root)
  1251. }
  1252. fn load_manifest_from_directory(root: &Path) -> Result<PluginManifest, PluginError> {
  1253. let manifest_path = plugin_manifest_path(root)?;
  1254. load_manifest_from_path(root, &manifest_path)
  1255. }
  1256. fn load_manifest_from_path(
  1257. root: &Path,
  1258. manifest_path: &Path,
  1259. ) -> Result<PluginManifest, PluginError> {
  1260. let contents = fs::read_to_string(manifest_path).map_err(|error| {
  1261. PluginError::NotFound(format!(
  1262. "plugin manifest not found at {}: {error}",
  1263. manifest_path.display()
  1264. ))
  1265. })?;
  1266. let raw_manifest: RawPluginManifest = serde_json::from_str(&contents)?;
  1267. build_plugin_manifest(root, raw_manifest)
  1268. }
  1269. fn plugin_manifest_path(root: &Path) -> Result<PathBuf, PluginError> {
  1270. let direct_path = root.join(MANIFEST_FILE_NAME);
  1271. if direct_path.exists() {
  1272. return Ok(direct_path);
  1273. }
  1274. let packaged_path = root.join(MANIFEST_RELATIVE_PATH);
  1275. if packaged_path.exists() {
  1276. return Ok(packaged_path);
  1277. }
  1278. Err(PluginError::NotFound(format!(
  1279. "plugin manifest not found at {} or {}",
  1280. direct_path.display(),
  1281. packaged_path.display()
  1282. )))
  1283. }
  1284. fn build_plugin_manifest(
  1285. root: &Path,
  1286. raw: RawPluginManifest,
  1287. ) -> Result<PluginManifest, PluginError> {
  1288. let mut errors = Vec::new();
  1289. validate_required_manifest_field("name", &raw.name, &mut errors);
  1290. validate_required_manifest_field("version", &raw.version, &mut errors);
  1291. validate_required_manifest_field("description", &raw.description, &mut errors);
  1292. let permissions = build_manifest_permissions(&raw.permissions, &mut errors);
  1293. validate_command_entries(root, raw.hooks.pre_tool_use.iter(), "hook", &mut errors);
  1294. validate_command_entries(root, raw.hooks.post_tool_use.iter(), "hook", &mut errors);
  1295. validate_command_entries(
  1296. root,
  1297. raw.lifecycle.init.iter(),
  1298. "lifecycle command",
  1299. &mut errors,
  1300. );
  1301. validate_command_entries(
  1302. root,
  1303. raw.lifecycle.shutdown.iter(),
  1304. "lifecycle command",
  1305. &mut errors,
  1306. );
  1307. let tools = build_manifest_tools(root, raw.tools, &mut errors);
  1308. let commands = build_manifest_commands(root, raw.commands, &mut errors);
  1309. if !errors.is_empty() {
  1310. return Err(PluginError::ManifestValidation(errors));
  1311. }
  1312. Ok(PluginManifest {
  1313. name: raw.name,
  1314. version: raw.version,
  1315. description: raw.description,
  1316. permissions,
  1317. default_enabled: raw.default_enabled,
  1318. hooks: raw.hooks,
  1319. lifecycle: raw.lifecycle,
  1320. tools,
  1321. commands,
  1322. })
  1323. }
  1324. fn validate_required_manifest_field(
  1325. field: &'static str,
  1326. value: &str,
  1327. errors: &mut Vec<PluginManifestValidationError>,
  1328. ) {
  1329. if value.trim().is_empty() {
  1330. errors.push(PluginManifestValidationError::EmptyField { field });
  1331. }
  1332. }
  1333. fn build_manifest_permissions(
  1334. permissions: &[String],
  1335. errors: &mut Vec<PluginManifestValidationError>,
  1336. ) -> Vec<PluginPermission> {
  1337. let mut seen = BTreeSet::new();
  1338. let mut validated = Vec::new();
  1339. for permission in permissions {
  1340. let permission = permission.trim();
  1341. if permission.is_empty() {
  1342. errors.push(PluginManifestValidationError::EmptyEntryField {
  1343. kind: "permission",
  1344. field: "value",
  1345. name: None,
  1346. });
  1347. continue;
  1348. }
  1349. if !seen.insert(permission.to_string()) {
  1350. errors.push(PluginManifestValidationError::DuplicatePermission {
  1351. permission: permission.to_string(),
  1352. });
  1353. continue;
  1354. }
  1355. match PluginPermission::parse(permission) {
  1356. Some(permission) => validated.push(permission),
  1357. None => errors.push(PluginManifestValidationError::InvalidPermission {
  1358. permission: permission.to_string(),
  1359. }),
  1360. }
  1361. }
  1362. validated
  1363. }
  1364. fn build_manifest_tools(
  1365. root: &Path,
  1366. tools: Vec<RawPluginToolManifest>,
  1367. errors: &mut Vec<PluginManifestValidationError>,
  1368. ) -> Vec<PluginToolManifest> {
  1369. let mut seen = BTreeSet::new();
  1370. let mut validated = Vec::new();
  1371. for tool in tools {
  1372. let name = tool.name.trim().to_string();
  1373. if name.is_empty() {
  1374. errors.push(PluginManifestValidationError::EmptyEntryField {
  1375. kind: "tool",
  1376. field: "name",
  1377. name: None,
  1378. });
  1379. continue;
  1380. }
  1381. if !seen.insert(name.clone()) {
  1382. errors.push(PluginManifestValidationError::DuplicateEntry { kind: "tool", name });
  1383. continue;
  1384. }
  1385. if tool.description.trim().is_empty() {
  1386. errors.push(PluginManifestValidationError::EmptyEntryField {
  1387. kind: "tool",
  1388. field: "description",
  1389. name: Some(name.clone()),
  1390. });
  1391. }
  1392. if tool.command.trim().is_empty() {
  1393. errors.push(PluginManifestValidationError::EmptyEntryField {
  1394. kind: "tool",
  1395. field: "command",
  1396. name: Some(name.clone()),
  1397. });
  1398. } else {
  1399. validate_command_entry(root, &tool.command, "tool", errors);
  1400. }
  1401. if !tool.input_schema.is_object() {
  1402. errors.push(PluginManifestValidationError::InvalidToolInputSchema {
  1403. tool_name: name.clone(),
  1404. });
  1405. }
  1406. let Some(required_permission) =
  1407. PluginToolPermission::parse(tool.required_permission.trim())
  1408. else {
  1409. errors.push(
  1410. PluginManifestValidationError::InvalidToolRequiredPermission {
  1411. tool_name: name.clone(),
  1412. permission: tool.required_permission.trim().to_string(),
  1413. },
  1414. );
  1415. continue;
  1416. };
  1417. validated.push(PluginToolManifest {
  1418. name,
  1419. description: tool.description,
  1420. input_schema: tool.input_schema,
  1421. command: tool.command,
  1422. args: tool.args,
  1423. required_permission,
  1424. });
  1425. }
  1426. validated
  1427. }
  1428. fn build_manifest_commands(
  1429. root: &Path,
  1430. commands: Vec<PluginCommandManifest>,
  1431. errors: &mut Vec<PluginManifestValidationError>,
  1432. ) -> Vec<PluginCommandManifest> {
  1433. let mut seen = BTreeSet::new();
  1434. let mut validated = Vec::new();
  1435. for command in commands {
  1436. let name = command.name.trim().to_string();
  1437. if name.is_empty() {
  1438. errors.push(PluginManifestValidationError::EmptyEntryField {
  1439. kind: "command",
  1440. field: "name",
  1441. name: None,
  1442. });
  1443. continue;
  1444. }
  1445. if !seen.insert(name.clone()) {
  1446. errors.push(PluginManifestValidationError::DuplicateEntry {
  1447. kind: "command",
  1448. name,
  1449. });
  1450. continue;
  1451. }
  1452. if command.description.trim().is_empty() {
  1453. errors.push(PluginManifestValidationError::EmptyEntryField {
  1454. kind: "command",
  1455. field: "description",
  1456. name: Some(name.clone()),
  1457. });
  1458. }
  1459. if command.command.trim().is_empty() {
  1460. errors.push(PluginManifestValidationError::EmptyEntryField {
  1461. kind: "command",
  1462. field: "command",
  1463. name: Some(name.clone()),
  1464. });
  1465. } else {
  1466. validate_command_entry(root, &command.command, "command", errors);
  1467. }
  1468. validated.push(command);
  1469. }
  1470. validated
  1471. }
  1472. fn validate_command_entries<'a>(
  1473. root: &Path,
  1474. entries: impl Iterator<Item = &'a String>,
  1475. kind: &'static str,
  1476. errors: &mut Vec<PluginManifestValidationError>,
  1477. ) {
  1478. for entry in entries {
  1479. validate_command_entry(root, entry, kind, errors);
  1480. }
  1481. }
  1482. fn validate_command_entry(
  1483. root: &Path,
  1484. entry: &str,
  1485. kind: &'static str,
  1486. errors: &mut Vec<PluginManifestValidationError>,
  1487. ) {
  1488. if entry.trim().is_empty() {
  1489. errors.push(PluginManifestValidationError::EmptyEntryField {
  1490. kind,
  1491. field: "command",
  1492. name: None,
  1493. });
  1494. return;
  1495. }
  1496. if is_literal_command(entry) {
  1497. return;
  1498. }
  1499. let path = if Path::new(entry).is_absolute() {
  1500. PathBuf::from(entry)
  1501. } else {
  1502. root.join(entry)
  1503. };
  1504. if !path.exists() {
  1505. errors.push(PluginManifestValidationError::MissingPath { kind, path });
  1506. }
  1507. }
  1508. fn resolve_hooks(root: &Path, hooks: &PluginHooks) -> PluginHooks {
  1509. PluginHooks {
  1510. pre_tool_use: hooks
  1511. .pre_tool_use
  1512. .iter()
  1513. .map(|entry| resolve_hook_entry(root, entry))
  1514. .collect(),
  1515. post_tool_use: hooks
  1516. .post_tool_use
  1517. .iter()
  1518. .map(|entry| resolve_hook_entry(root, entry))
  1519. .collect(),
  1520. post_tool_use_failure: hooks
  1521. .post_tool_use_failure
  1522. .iter()
  1523. .map(|entry| resolve_hook_entry(root, entry))
  1524. .collect(),
  1525. }
  1526. }
  1527. fn resolve_lifecycle(root: &Path, lifecycle: &PluginLifecycle) -> PluginLifecycle {
  1528. PluginLifecycle {
  1529. init: lifecycle
  1530. .init
  1531. .iter()
  1532. .map(|entry| resolve_hook_entry(root, entry))
  1533. .collect(),
  1534. shutdown: lifecycle
  1535. .shutdown
  1536. .iter()
  1537. .map(|entry| resolve_hook_entry(root, entry))
  1538. .collect(),
  1539. }
  1540. }
  1541. fn resolve_tools(
  1542. root: &Path,
  1543. plugin_id: &str,
  1544. plugin_name: &str,
  1545. tools: &[PluginToolManifest],
  1546. ) -> Vec<PluginTool> {
  1547. tools
  1548. .iter()
  1549. .map(|tool| {
  1550. PluginTool::new(
  1551. plugin_id,
  1552. plugin_name,
  1553. PluginToolDefinition {
  1554. name: tool.name.clone(),
  1555. description: Some(tool.description.clone()),
  1556. input_schema: tool.input_schema.clone(),
  1557. },
  1558. resolve_hook_entry(root, &tool.command),
  1559. tool.args.clone(),
  1560. tool.required_permission,
  1561. Some(root.to_path_buf()),
  1562. )
  1563. })
  1564. .collect()
  1565. }
  1566. fn validate_hook_paths(root: Option<&Path>, hooks: &PluginHooks) -> Result<(), PluginError> {
  1567. let Some(root) = root else {
  1568. return Ok(());
  1569. };
  1570. for entry in hooks
  1571. .pre_tool_use
  1572. .iter()
  1573. .chain(hooks.post_tool_use.iter())
  1574. .chain(hooks.post_tool_use_failure.iter())
  1575. {
  1576. validate_command_path(root, entry, "hook")?;
  1577. }
  1578. Ok(())
  1579. }
  1580. fn validate_lifecycle_paths(
  1581. root: Option<&Path>,
  1582. lifecycle: &PluginLifecycle,
  1583. ) -> Result<(), PluginError> {
  1584. let Some(root) = root else {
  1585. return Ok(());
  1586. };
  1587. for entry in lifecycle.init.iter().chain(lifecycle.shutdown.iter()) {
  1588. validate_command_path(root, entry, "lifecycle command")?;
  1589. }
  1590. Ok(())
  1591. }
  1592. fn validate_tool_paths(root: Option<&Path>, tools: &[PluginTool]) -> Result<(), PluginError> {
  1593. let Some(root) = root else {
  1594. return Ok(());
  1595. };
  1596. for tool in tools {
  1597. validate_command_path(root, &tool.command, "tool")?;
  1598. }
  1599. Ok(())
  1600. }
  1601. fn validate_command_path(root: &Path, entry: &str, kind: &str) -> Result<(), PluginError> {
  1602. if is_literal_command(entry) {
  1603. return Ok(());
  1604. }
  1605. let path = if Path::new(entry).is_absolute() {
  1606. PathBuf::from(entry)
  1607. } else {
  1608. root.join(entry)
  1609. };
  1610. if !path.exists() {
  1611. return Err(PluginError::InvalidManifest(format!(
  1612. "{kind} path `{}` does not exist",
  1613. path.display()
  1614. )));
  1615. }
  1616. Ok(())
  1617. }
  1618. fn resolve_hook_entry(root: &Path, entry: &str) -> String {
  1619. if is_literal_command(entry) {
  1620. entry.to_string()
  1621. } else {
  1622. root.join(entry).display().to_string()
  1623. }
  1624. }
  1625. fn is_literal_command(entry: &str) -> bool {
  1626. !entry.starts_with("./") && !entry.starts_with("../") && !Path::new(entry).is_absolute()
  1627. }
  1628. fn run_lifecycle_commands(
  1629. metadata: &PluginMetadata,
  1630. lifecycle: &PluginLifecycle,
  1631. phase: &str,
  1632. commands: &[String],
  1633. ) -> Result<(), PluginError> {
  1634. if lifecycle.is_empty() || commands.is_empty() {
  1635. return Ok(());
  1636. }
  1637. for command in commands {
  1638. let mut process = if Path::new(command).exists() {
  1639. if cfg!(windows) {
  1640. let mut process = Command::new("cmd");
  1641. process.arg("/C").arg(command);
  1642. process
  1643. } else {
  1644. let mut process = Command::new("sh");
  1645. process.arg(command);
  1646. process
  1647. }
  1648. } else if cfg!(windows) {
  1649. let mut process = Command::new("cmd");
  1650. process.arg("/C").arg(command);
  1651. process
  1652. } else {
  1653. let mut process = Command::new("sh");
  1654. process.arg("-lc").arg(command);
  1655. process
  1656. };
  1657. if let Some(root) = &metadata.root {
  1658. process.current_dir(root);
  1659. }
  1660. let output = process.output()?;
  1661. if !output.status.success() {
  1662. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  1663. return Err(PluginError::CommandFailed(format!(
  1664. "plugin `{}` {} failed for `{}`: {}",
  1665. metadata.id,
  1666. phase,
  1667. command,
  1668. if stderr.is_empty() {
  1669. format!("exit status {}", output.status)
  1670. } else {
  1671. stderr
  1672. }
  1673. )));
  1674. }
  1675. }
  1676. Ok(())
  1677. }
  1678. fn resolve_local_source(source: &str) -> Result<PathBuf, PluginError> {
  1679. let path = PathBuf::from(source);
  1680. if path.exists() {
  1681. Ok(path)
  1682. } else {
  1683. Err(PluginError::NotFound(format!(
  1684. "plugin source `{source}` was not found"
  1685. )))
  1686. }
  1687. }
  1688. fn parse_install_source(source: &str) -> Result<PluginInstallSource, PluginError> {
  1689. if source.starts_with("http://")
  1690. || source.starts_with("https://")
  1691. || source.starts_with("git@")
  1692. || Path::new(source)
  1693. .extension()
  1694. .is_some_and(|extension| extension.eq_ignore_ascii_case("git"))
  1695. {
  1696. Ok(PluginInstallSource::GitUrl {
  1697. url: source.to_string(),
  1698. })
  1699. } else {
  1700. Ok(PluginInstallSource::LocalPath {
  1701. path: resolve_local_source(source)?,
  1702. })
  1703. }
  1704. }
  1705. fn materialize_source(
  1706. source: &PluginInstallSource,
  1707. temp_root: &Path,
  1708. ) -> Result<PathBuf, PluginError> {
  1709. fs::create_dir_all(temp_root)?;
  1710. match source {
  1711. PluginInstallSource::LocalPath { path } => Ok(path.clone()),
  1712. PluginInstallSource::GitUrl { url } => {
  1713. let destination = temp_root.join(format!("plugin-{}", unix_time_ms()));
  1714. let output = Command::new("git")
  1715. .arg("clone")
  1716. .arg("--depth")
  1717. .arg("1")
  1718. .arg(url)
  1719. .arg(&destination)
  1720. .output()?;
  1721. if !output.status.success() {
  1722. return Err(PluginError::CommandFailed(format!(
  1723. "git clone failed for `{url}`: {}",
  1724. String::from_utf8_lossy(&output.stderr).trim()
  1725. )));
  1726. }
  1727. Ok(destination)
  1728. }
  1729. }
  1730. }
  1731. fn discover_plugin_dirs(root: &Path) -> Result<Vec<PathBuf>, PluginError> {
  1732. match fs::read_dir(root) {
  1733. Ok(entries) => {
  1734. let mut paths = Vec::new();
  1735. for entry in entries {
  1736. let path = entry?.path();
  1737. if path.is_dir() && plugin_manifest_path(&path).is_ok() {
  1738. paths.push(path);
  1739. }
  1740. }
  1741. paths.sort();
  1742. Ok(paths)
  1743. }
  1744. Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
  1745. Err(error) => Err(PluginError::Io(error)),
  1746. }
  1747. }
  1748. fn plugin_id(name: &str, marketplace: &str) -> String {
  1749. format!("{name}@{marketplace}")
  1750. }
  1751. fn sanitize_plugin_id(plugin_id: &str) -> String {
  1752. plugin_id
  1753. .chars()
  1754. .map(|ch| match ch {
  1755. '/' | '\\' | '@' | ':' => '-',
  1756. other => other,
  1757. })
  1758. .collect()
  1759. }
  1760. fn describe_install_source(source: &PluginInstallSource) -> String {
  1761. match source {
  1762. PluginInstallSource::LocalPath { path } => path.display().to_string(),
  1763. PluginInstallSource::GitUrl { url } => url.clone(),
  1764. }
  1765. }
  1766. fn unix_time_ms() -> u128 {
  1767. SystemTime::now()
  1768. .duration_since(UNIX_EPOCH)
  1769. .expect("time should be after epoch")
  1770. .as_millis()
  1771. }
  1772. fn copy_dir_all(source: &Path, destination: &Path) -> Result<(), PluginError> {
  1773. fs::create_dir_all(destination)?;
  1774. for entry in fs::read_dir(source)? {
  1775. let entry = entry?;
  1776. let target = destination.join(entry.file_name());
  1777. if entry.file_type()?.is_dir() {
  1778. copy_dir_all(&entry.path(), &target)?;
  1779. } else {
  1780. fs::copy(entry.path(), target)?;
  1781. }
  1782. }
  1783. Ok(())
  1784. }
  1785. fn update_settings_json(
  1786. path: &Path,
  1787. mut update: impl FnMut(&mut Map<String, Value>),
  1788. ) -> Result<(), PluginError> {
  1789. if let Some(parent) = path.parent() {
  1790. fs::create_dir_all(parent)?;
  1791. }
  1792. let mut root = match fs::read_to_string(path) {
  1793. Ok(contents) if !contents.trim().is_empty() => serde_json::from_str::<Value>(&contents)?,
  1794. Ok(_) => Value::Object(Map::new()),
  1795. Err(error) if error.kind() == std::io::ErrorKind::NotFound => Value::Object(Map::new()),
  1796. Err(error) => return Err(PluginError::Io(error)),
  1797. };
  1798. let object = root.as_object_mut().ok_or_else(|| {
  1799. PluginError::InvalidManifest(format!(
  1800. "settings file {} must contain a JSON object",
  1801. path.display()
  1802. ))
  1803. })?;
  1804. update(object);
  1805. fs::write(path, serde_json::to_string_pretty(&root)?)?;
  1806. Ok(())
  1807. }
  1808. fn ensure_object<'a>(root: &'a mut Map<String, Value>, key: &str) -> &'a mut Map<String, Value> {
  1809. if !root.get(key).is_some_and(Value::is_object) {
  1810. root.insert(key.to_string(), Value::Object(Map::new()));
  1811. }
  1812. root.get_mut(key)
  1813. .and_then(Value::as_object_mut)
  1814. .expect("object should exist")
  1815. }
  1816. #[cfg(test)]
  1817. mod tests {
  1818. use super::*;
  1819. fn temp_dir(label: &str) -> PathBuf {
  1820. let nanos = std::time::SystemTime::now()
  1821. .duration_since(std::time::UNIX_EPOCH)
  1822. .expect("time should be after epoch")
  1823. .as_nanos();
  1824. std::env::temp_dir().join(format!("plugins-{label}-{nanos}"))
  1825. }
  1826. fn write_file(path: &Path, contents: &str) {
  1827. if let Some(parent) = path.parent() {
  1828. fs::create_dir_all(parent).expect("parent dir");
  1829. }
  1830. fs::write(path, contents).expect("write file");
  1831. }
  1832. fn write_loader_plugin(root: &Path) {
  1833. write_file(
  1834. root.join("hooks").join("pre.sh").as_path(),
  1835. "#!/bin/sh\nprintf 'pre'\n",
  1836. );
  1837. write_file(
  1838. root.join("tools").join("echo-tool.sh").as_path(),
  1839. "#!/bin/sh\ncat\n",
  1840. );
  1841. write_file(
  1842. root.join("commands").join("sync.sh").as_path(),
  1843. "#!/bin/sh\nprintf 'sync'\n",
  1844. );
  1845. write_file(
  1846. root.join(MANIFEST_FILE_NAME).as_path(),
  1847. r#"{
  1848. "name": "loader-demo",
  1849. "version": "1.2.3",
  1850. "description": "Manifest loader test plugin",
  1851. "permissions": ["read", "write"],
  1852. "hooks": {
  1853. "PreToolUse": ["./hooks/pre.sh"]
  1854. },
  1855. "tools": [
  1856. {
  1857. "name": "echo_tool",
  1858. "description": "Echoes JSON input",
  1859. "inputSchema": {
  1860. "type": "object"
  1861. },
  1862. "command": "./tools/echo-tool.sh",
  1863. "requiredPermission": "workspace-write"
  1864. }
  1865. ],
  1866. "commands": [
  1867. {
  1868. "name": "sync",
  1869. "description": "Sync command",
  1870. "command": "./commands/sync.sh"
  1871. }
  1872. ]
  1873. }"#,
  1874. );
  1875. }
  1876. fn write_external_plugin(root: &Path, name: &str, version: &str) {
  1877. write_file(
  1878. root.join("hooks").join("pre.sh").as_path(),
  1879. "#!/bin/sh\nprintf 'pre'\n",
  1880. );
  1881. write_file(
  1882. root.join("hooks").join("post.sh").as_path(),
  1883. "#!/bin/sh\nprintf 'post'\n",
  1884. );
  1885. write_file(
  1886. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  1887. format!(
  1888. "{{\n \"name\": \"{name}\",\n \"version\": \"{version}\",\n \"description\": \"test plugin\",\n \"hooks\": {{\n \"PreToolUse\": [\"./hooks/pre.sh\"],\n \"PostToolUse\": [\"./hooks/post.sh\"]\n }}\n}}"
  1889. )
  1890. .as_str(),
  1891. );
  1892. }
  1893. fn write_broken_plugin(root: &Path, name: &str) {
  1894. write_file(
  1895. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  1896. format!(
  1897. "{{\n \"name\": \"{name}\",\n \"version\": \"1.0.0\",\n \"description\": \"broken plugin\",\n \"hooks\": {{\n \"PreToolUse\": [\"./hooks/missing.sh\"]\n }}\n}}"
  1898. )
  1899. .as_str(),
  1900. );
  1901. }
  1902. fn write_lifecycle_plugin(root: &Path, name: &str, version: &str) -> PathBuf {
  1903. let log_path = root.join("lifecycle.log");
  1904. write_file(
  1905. root.join("lifecycle").join("init.sh").as_path(),
  1906. "#!/bin/sh\nprintf 'init\\n' >> lifecycle.log\n",
  1907. );
  1908. write_file(
  1909. root.join("lifecycle").join("shutdown.sh").as_path(),
  1910. "#!/bin/sh\nprintf 'shutdown\\n' >> lifecycle.log\n",
  1911. );
  1912. write_file(
  1913. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  1914. format!(
  1915. "{{\n \"name\": \"{name}\",\n \"version\": \"{version}\",\n \"description\": \"lifecycle plugin\",\n \"lifecycle\": {{\n \"Init\": [\"./lifecycle/init.sh\"],\n \"Shutdown\": [\"./lifecycle/shutdown.sh\"]\n }}\n}}"
  1916. )
  1917. .as_str(),
  1918. );
  1919. log_path
  1920. }
  1921. fn write_tool_plugin(root: &Path, name: &str, version: &str) {
  1922. write_tool_plugin_with_name(root, name, version, "plugin_echo");
  1923. }
  1924. fn write_tool_plugin_with_name(root: &Path, name: &str, version: &str, tool_name: &str) {
  1925. let script_path = root.join("tools").join("echo-json.sh");
  1926. write_file(
  1927. &script_path,
  1928. "#!/bin/sh\nINPUT=$(cat)\nprintf '{\"plugin\":\"%s\",\"tool\":\"%s\",\"input\":%s}\\n' \"$CLAWD_PLUGIN_ID\" \"$CLAWD_TOOL_NAME\" \"$INPUT\"\n",
  1929. );
  1930. #[cfg(unix)]
  1931. {
  1932. use std::os::unix::fs::PermissionsExt;
  1933. let mut permissions = fs::metadata(&script_path).expect("metadata").permissions();
  1934. permissions.set_mode(0o755);
  1935. fs::set_permissions(&script_path, permissions).expect("chmod");
  1936. }
  1937. write_file(
  1938. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  1939. format!(
  1940. "{{\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}}"
  1941. )
  1942. .as_str(),
  1943. );
  1944. }
  1945. fn write_bundled_plugin(root: &Path, name: &str, version: &str, default_enabled: bool) {
  1946. write_file(
  1947. root.join(MANIFEST_RELATIVE_PATH).as_path(),
  1948. format!(
  1949. "{{\n \"name\": \"{name}\",\n \"version\": \"{version}\",\n \"description\": \"bundled plugin\",\n \"defaultEnabled\": {}\n}}",
  1950. if default_enabled { "true" } else { "false" }
  1951. )
  1952. .as_str(),
  1953. );
  1954. }
  1955. fn load_enabled_plugins(path: &Path) -> BTreeMap<String, bool> {
  1956. let contents = fs::read_to_string(path).expect("settings should exist");
  1957. let root: Value = serde_json::from_str(&contents).expect("settings json");
  1958. root.get("enabledPlugins")
  1959. .and_then(Value::as_object)
  1960. .map(|enabled_plugins| {
  1961. enabled_plugins
  1962. .iter()
  1963. .map(|(plugin_id, value)| {
  1964. (
  1965. plugin_id.clone(),
  1966. value.as_bool().expect("plugin state should be a bool"),
  1967. )
  1968. })
  1969. .collect()
  1970. })
  1971. .unwrap_or_default()
  1972. }
  1973. #[test]
  1974. fn load_plugin_from_directory_validates_required_fields() {
  1975. let root = temp_dir("manifest-required");
  1976. write_file(
  1977. root.join(MANIFEST_FILE_NAME).as_path(),
  1978. r#"{"name":"","version":"1.0.0","description":"desc"}"#,
  1979. );
  1980. let error = load_plugin_from_directory(&root).expect_err("empty name should fail");
  1981. assert!(error.to_string().contains("name cannot be empty"));
  1982. let _ = fs::remove_dir_all(root);
  1983. }
  1984. #[test]
  1985. fn load_plugin_from_directory_reads_root_manifest_and_validates_entries() {
  1986. let root = temp_dir("manifest-root");
  1987. write_loader_plugin(&root);
  1988. let manifest = load_plugin_from_directory(&root).expect("manifest should load");
  1989. assert_eq!(manifest.name, "loader-demo");
  1990. assert_eq!(manifest.version, "1.2.3");
  1991. assert_eq!(
  1992. manifest
  1993. .permissions
  1994. .iter()
  1995. .map(|permission| permission.as_str())
  1996. .collect::<Vec<_>>(),
  1997. vec!["read", "write"]
  1998. );
  1999. assert_eq!(manifest.hooks.pre_tool_use, vec!["./hooks/pre.sh"]);
  2000. assert_eq!(manifest.tools.len(), 1);
  2001. assert_eq!(manifest.tools[0].name, "echo_tool");
  2002. assert_eq!(
  2003. manifest.tools[0].required_permission,
  2004. PluginToolPermission::WorkspaceWrite
  2005. );
  2006. assert_eq!(manifest.commands.len(), 1);
  2007. assert_eq!(manifest.commands[0].name, "sync");
  2008. let _ = fs::remove_dir_all(root);
  2009. }
  2010. #[test]
  2011. fn load_plugin_from_directory_supports_packaged_manifest_path() {
  2012. let root = temp_dir("manifest-packaged");
  2013. write_external_plugin(&root, "packaged-demo", "1.0.0");
  2014. let manifest = load_plugin_from_directory(&root).expect("packaged manifest should load");
  2015. assert_eq!(manifest.name, "packaged-demo");
  2016. assert!(manifest.tools.is_empty());
  2017. assert!(manifest.commands.is_empty());
  2018. let _ = fs::remove_dir_all(root);
  2019. }
  2020. #[test]
  2021. fn load_plugin_from_directory_defaults_optional_fields() {
  2022. let root = temp_dir("manifest-defaults");
  2023. write_file(
  2024. root.join(MANIFEST_FILE_NAME).as_path(),
  2025. r#"{
  2026. "name": "minimal",
  2027. "version": "0.1.0",
  2028. "description": "Minimal manifest"
  2029. }"#,
  2030. );
  2031. let manifest = load_plugin_from_directory(&root).expect("minimal manifest should load");
  2032. assert!(manifest.permissions.is_empty());
  2033. assert!(manifest.hooks.is_empty());
  2034. assert!(manifest.tools.is_empty());
  2035. assert!(manifest.commands.is_empty());
  2036. let _ = fs::remove_dir_all(root);
  2037. }
  2038. #[test]
  2039. fn load_plugin_from_directory_rejects_duplicate_permissions_and_commands() {
  2040. let root = temp_dir("manifest-duplicates");
  2041. write_file(
  2042. root.join("commands").join("sync.sh").as_path(),
  2043. "#!/bin/sh\nprintf 'sync'\n",
  2044. );
  2045. write_file(
  2046. root.join(MANIFEST_FILE_NAME).as_path(),
  2047. r#"{
  2048. "name": "duplicate-manifest",
  2049. "version": "1.0.0",
  2050. "description": "Duplicate validation",
  2051. "permissions": ["read", "read"],
  2052. "commands": [
  2053. {"name": "sync", "description": "Sync one", "command": "./commands/sync.sh"},
  2054. {"name": "sync", "description": "Sync two", "command": "./commands/sync.sh"}
  2055. ]
  2056. }"#,
  2057. );
  2058. let error = load_plugin_from_directory(&root).expect_err("duplicates should fail");
  2059. match error {
  2060. PluginError::ManifestValidation(errors) => {
  2061. assert!(errors.iter().any(|error| matches!(
  2062. error,
  2063. PluginManifestValidationError::DuplicatePermission { permission }
  2064. if permission == "read"
  2065. )));
  2066. assert!(errors.iter().any(|error| matches!(
  2067. error,
  2068. PluginManifestValidationError::DuplicateEntry { kind, name }
  2069. if *kind == "command" && name == "sync"
  2070. )));
  2071. }
  2072. other => panic!("expected manifest validation errors, got {other}"),
  2073. }
  2074. let _ = fs::remove_dir_all(root);
  2075. }
  2076. #[test]
  2077. fn load_plugin_from_directory_rejects_missing_tool_or_command_paths() {
  2078. let root = temp_dir("manifest-paths");
  2079. write_file(
  2080. root.join(MANIFEST_FILE_NAME).as_path(),
  2081. r#"{
  2082. "name": "missing-paths",
  2083. "version": "1.0.0",
  2084. "description": "Missing path validation",
  2085. "tools": [
  2086. {
  2087. "name": "tool_one",
  2088. "description": "Missing tool script",
  2089. "inputSchema": {"type": "object"},
  2090. "command": "./tools/missing.sh"
  2091. }
  2092. ]
  2093. }"#,
  2094. );
  2095. let error = load_plugin_from_directory(&root).expect_err("missing paths should fail");
  2096. assert!(error.to_string().contains("does not exist"));
  2097. let _ = fs::remove_dir_all(root);
  2098. }
  2099. #[test]
  2100. fn load_plugin_from_directory_rejects_invalid_permissions() {
  2101. let root = temp_dir("manifest-invalid-permissions");
  2102. write_file(
  2103. root.join(MANIFEST_FILE_NAME).as_path(),
  2104. r#"{
  2105. "name": "invalid-permissions",
  2106. "version": "1.0.0",
  2107. "description": "Invalid permission validation",
  2108. "permissions": ["admin"]
  2109. }"#,
  2110. );
  2111. let error = load_plugin_from_directory(&root).expect_err("invalid permissions should fail");
  2112. match error {
  2113. PluginError::ManifestValidation(errors) => {
  2114. assert!(errors.iter().any(|error| matches!(
  2115. error,
  2116. PluginManifestValidationError::InvalidPermission { permission }
  2117. if permission == "admin"
  2118. )));
  2119. }
  2120. other => panic!("expected manifest validation errors, got {other}"),
  2121. }
  2122. let _ = fs::remove_dir_all(root);
  2123. }
  2124. #[test]
  2125. fn load_plugin_from_directory_rejects_invalid_tool_required_permission() {
  2126. let root = temp_dir("manifest-invalid-tool-permission");
  2127. write_file(
  2128. root.join("tools").join("echo.sh").as_path(),
  2129. "#!/bin/sh\ncat\n",
  2130. );
  2131. write_file(
  2132. root.join(MANIFEST_FILE_NAME).as_path(),
  2133. r#"{
  2134. "name": "invalid-tool-permission",
  2135. "version": "1.0.0",
  2136. "description": "Invalid tool permission validation",
  2137. "tools": [
  2138. {
  2139. "name": "echo_tool",
  2140. "description": "Echo tool",
  2141. "inputSchema": {"type": "object"},
  2142. "command": "./tools/echo.sh",
  2143. "requiredPermission": "admin"
  2144. }
  2145. ]
  2146. }"#,
  2147. );
  2148. let error =
  2149. load_plugin_from_directory(&root).expect_err("invalid tool permission should fail");
  2150. match error {
  2151. PluginError::ManifestValidation(errors) => {
  2152. assert!(errors.iter().any(|error| matches!(
  2153. error,
  2154. PluginManifestValidationError::InvalidToolRequiredPermission {
  2155. tool_name,
  2156. permission
  2157. } if tool_name == "echo_tool" && permission == "admin"
  2158. )));
  2159. }
  2160. other => panic!("expected manifest validation errors, got {other}"),
  2161. }
  2162. let _ = fs::remove_dir_all(root);
  2163. }
  2164. #[test]
  2165. fn load_plugin_from_directory_accumulates_multiple_validation_errors() {
  2166. let root = temp_dir("manifest-multi-error");
  2167. write_file(
  2168. root.join(MANIFEST_FILE_NAME).as_path(),
  2169. r#"{
  2170. "name": "",
  2171. "version": "1.0.0",
  2172. "description": "",
  2173. "permissions": ["admin"],
  2174. "commands": [
  2175. {"name": "", "description": "", "command": "./commands/missing.sh"}
  2176. ]
  2177. }"#,
  2178. );
  2179. let error =
  2180. load_plugin_from_directory(&root).expect_err("multiple manifest errors should fail");
  2181. match error {
  2182. PluginError::ManifestValidation(errors) => {
  2183. assert!(errors.len() >= 4);
  2184. assert!(errors.iter().any(|error| matches!(
  2185. error,
  2186. PluginManifestValidationError::EmptyField { field } if *field == "name"
  2187. )));
  2188. assert!(errors.iter().any(|error| matches!(
  2189. error,
  2190. PluginManifestValidationError::EmptyField { field }
  2191. if *field == "description"
  2192. )));
  2193. assert!(errors.iter().any(|error| matches!(
  2194. error,
  2195. PluginManifestValidationError::InvalidPermission { permission }
  2196. if permission == "admin"
  2197. )));
  2198. }
  2199. other => panic!("expected manifest validation errors, got {other}"),
  2200. }
  2201. let _ = fs::remove_dir_all(root);
  2202. }
  2203. #[test]
  2204. fn discovers_builtin_and_bundled_plugins() {
  2205. let manager = PluginManager::new(PluginManagerConfig::new(temp_dir("discover")));
  2206. let plugins = manager.list_plugins().expect("plugins should list");
  2207. assert!(plugins
  2208. .iter()
  2209. .any(|plugin| plugin.metadata.kind == PluginKind::Builtin));
  2210. assert!(plugins
  2211. .iter()
  2212. .any(|plugin| plugin.metadata.kind == PluginKind::Bundled));
  2213. }
  2214. #[test]
  2215. fn installs_enables_updates_and_uninstalls_external_plugins() {
  2216. let config_home = temp_dir("home");
  2217. let source_root = temp_dir("source");
  2218. write_external_plugin(&source_root, "demo", "1.0.0");
  2219. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2220. let install = manager
  2221. .install(source_root.to_str().expect("utf8 path"))
  2222. .expect("install should succeed");
  2223. assert_eq!(install.plugin_id, "demo@external");
  2224. assert!(manager
  2225. .list_plugins()
  2226. .expect("list plugins")
  2227. .iter()
  2228. .any(|plugin| plugin.metadata.id == "demo@external" && plugin.enabled));
  2229. let hooks = manager.aggregated_hooks().expect("hooks should aggregate");
  2230. assert_eq!(hooks.pre_tool_use.len(), 1);
  2231. assert!(hooks.pre_tool_use[0].contains("pre.sh"));
  2232. manager
  2233. .disable("demo@external")
  2234. .expect("disable should work");
  2235. assert!(manager
  2236. .aggregated_hooks()
  2237. .expect("hooks after disable")
  2238. .is_empty());
  2239. manager.enable("demo@external").expect("enable should work");
  2240. write_external_plugin(&source_root, "demo", "2.0.0");
  2241. let update = manager.update("demo@external").expect("update should work");
  2242. assert_eq!(update.old_version, "1.0.0");
  2243. assert_eq!(update.new_version, "2.0.0");
  2244. manager
  2245. .uninstall("demo@external")
  2246. .expect("uninstall should work");
  2247. assert!(!manager
  2248. .list_plugins()
  2249. .expect("list plugins")
  2250. .iter()
  2251. .any(|plugin| plugin.metadata.id == "demo@external"));
  2252. let _ = fs::remove_dir_all(config_home);
  2253. let _ = fs::remove_dir_all(source_root);
  2254. }
  2255. #[test]
  2256. fn auto_installs_bundled_plugins_into_the_registry() {
  2257. let config_home = temp_dir("bundled-home");
  2258. let bundled_root = temp_dir("bundled-root");
  2259. write_bundled_plugin(&bundled_root.join("starter"), "starter", "0.1.0", false);
  2260. let mut config = PluginManagerConfig::new(&config_home);
  2261. config.bundled_root = Some(bundled_root.clone());
  2262. let manager = PluginManager::new(config);
  2263. let installed = manager
  2264. .list_installed_plugins()
  2265. .expect("bundled plugins should auto-install");
  2266. assert!(installed.iter().any(|plugin| {
  2267. plugin.metadata.id == "starter@bundled"
  2268. && plugin.metadata.kind == PluginKind::Bundled
  2269. && !plugin.enabled
  2270. }));
  2271. let registry = manager.load_registry().expect("registry should exist");
  2272. let record = registry
  2273. .plugins
  2274. .get("starter@bundled")
  2275. .expect("bundled plugin should be recorded");
  2276. assert_eq!(record.kind, PluginKind::Bundled);
  2277. assert!(record.install_path.exists());
  2278. let _ = fs::remove_dir_all(config_home);
  2279. let _ = fs::remove_dir_all(bundled_root);
  2280. }
  2281. #[test]
  2282. fn default_bundled_root_loads_repo_bundles_as_installed_plugins() {
  2283. let config_home = temp_dir("default-bundled-home");
  2284. let manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2285. let installed = manager
  2286. .list_installed_plugins()
  2287. .expect("default bundled plugins should auto-install");
  2288. assert!(installed
  2289. .iter()
  2290. .any(|plugin| plugin.metadata.id == "example-bundled@bundled"));
  2291. assert!(installed
  2292. .iter()
  2293. .any(|plugin| plugin.metadata.id == "sample-hooks@bundled"));
  2294. let _ = fs::remove_dir_all(config_home);
  2295. }
  2296. #[test]
  2297. fn bundled_sync_prunes_removed_bundled_registry_entries() {
  2298. let config_home = temp_dir("bundled-prune-home");
  2299. let bundled_root = temp_dir("bundled-prune-root");
  2300. let stale_install_path = config_home
  2301. .join("plugins")
  2302. .join("installed")
  2303. .join("stale-bundled-external");
  2304. write_bundled_plugin(&bundled_root.join("active"), "active", "0.1.0", false);
  2305. write_file(
  2306. stale_install_path.join(MANIFEST_RELATIVE_PATH).as_path(),
  2307. r#"{
  2308. "name": "stale",
  2309. "version": "0.1.0",
  2310. "description": "stale bundled plugin"
  2311. }"#,
  2312. );
  2313. let mut config = PluginManagerConfig::new(&config_home);
  2314. config.bundled_root = Some(bundled_root.clone());
  2315. config.install_root = Some(config_home.join("plugins").join("installed"));
  2316. let manager = PluginManager::new(config);
  2317. let mut registry = InstalledPluginRegistry::default();
  2318. registry.plugins.insert(
  2319. "stale@bundled".to_string(),
  2320. InstalledPluginRecord {
  2321. kind: PluginKind::Bundled,
  2322. id: "stale@bundled".to_string(),
  2323. name: "stale".to_string(),
  2324. version: "0.1.0".to_string(),
  2325. description: "stale bundled plugin".to_string(),
  2326. install_path: stale_install_path.clone(),
  2327. source: PluginInstallSource::LocalPath {
  2328. path: bundled_root.join("stale"),
  2329. },
  2330. installed_at_unix_ms: 1,
  2331. updated_at_unix_ms: 1,
  2332. },
  2333. );
  2334. manager.store_registry(&registry).expect("store registry");
  2335. manager
  2336. .write_enabled_state("stale@bundled", Some(true))
  2337. .expect("seed bundled enabled state");
  2338. let installed = manager
  2339. .list_installed_plugins()
  2340. .expect("bundled sync should succeed");
  2341. assert!(installed
  2342. .iter()
  2343. .any(|plugin| plugin.metadata.id == "active@bundled"));
  2344. assert!(!installed
  2345. .iter()
  2346. .any(|plugin| plugin.metadata.id == "stale@bundled"));
  2347. let registry = manager.load_registry().expect("load registry");
  2348. assert!(!registry.plugins.contains_key("stale@bundled"));
  2349. assert!(!stale_install_path.exists());
  2350. let _ = fs::remove_dir_all(config_home);
  2351. let _ = fs::remove_dir_all(bundled_root);
  2352. }
  2353. #[test]
  2354. fn installed_plugin_discovery_keeps_registry_entries_outside_install_root() {
  2355. let config_home = temp_dir("registry-fallback-home");
  2356. let bundled_root = temp_dir("registry-fallback-bundled");
  2357. let install_root = config_home.join("plugins").join("installed");
  2358. let external_install_path = temp_dir("registry-fallback-external");
  2359. write_file(
  2360. external_install_path.join(MANIFEST_FILE_NAME).as_path(),
  2361. r#"{
  2362. "name": "registry-fallback",
  2363. "version": "1.0.0",
  2364. "description": "Registry fallback plugin"
  2365. }"#,
  2366. );
  2367. let mut config = PluginManagerConfig::new(&config_home);
  2368. config.bundled_root = Some(bundled_root.clone());
  2369. config.install_root = Some(install_root.clone());
  2370. let manager = PluginManager::new(config);
  2371. let mut registry = InstalledPluginRegistry::default();
  2372. registry.plugins.insert(
  2373. "registry-fallback@external".to_string(),
  2374. InstalledPluginRecord {
  2375. kind: PluginKind::External,
  2376. id: "registry-fallback@external".to_string(),
  2377. name: "registry-fallback".to_string(),
  2378. version: "1.0.0".to_string(),
  2379. description: "Registry fallback plugin".to_string(),
  2380. install_path: external_install_path.clone(),
  2381. source: PluginInstallSource::LocalPath {
  2382. path: external_install_path.clone(),
  2383. },
  2384. installed_at_unix_ms: 1,
  2385. updated_at_unix_ms: 1,
  2386. },
  2387. );
  2388. manager.store_registry(&registry).expect("store registry");
  2389. manager
  2390. .write_enabled_state("stale-external@external", Some(true))
  2391. .expect("seed stale external enabled state");
  2392. let installed = manager
  2393. .list_installed_plugins()
  2394. .expect("registry fallback plugin should load");
  2395. assert!(installed
  2396. .iter()
  2397. .any(|plugin| plugin.metadata.id == "registry-fallback@external"));
  2398. let _ = fs::remove_dir_all(config_home);
  2399. let _ = fs::remove_dir_all(bundled_root);
  2400. let _ = fs::remove_dir_all(external_install_path);
  2401. }
  2402. #[test]
  2403. fn installed_plugin_discovery_prunes_stale_registry_entries() {
  2404. let config_home = temp_dir("registry-prune-home");
  2405. let bundled_root = temp_dir("registry-prune-bundled");
  2406. let install_root = config_home.join("plugins").join("installed");
  2407. let missing_install_path = temp_dir("registry-prune-missing");
  2408. let mut config = PluginManagerConfig::new(&config_home);
  2409. config.bundled_root = Some(bundled_root.clone());
  2410. config.install_root = Some(install_root);
  2411. let manager = PluginManager::new(config);
  2412. let mut registry = InstalledPluginRegistry::default();
  2413. registry.plugins.insert(
  2414. "stale-external@external".to_string(),
  2415. InstalledPluginRecord {
  2416. kind: PluginKind::External,
  2417. id: "stale-external@external".to_string(),
  2418. name: "stale-external".to_string(),
  2419. version: "1.0.0".to_string(),
  2420. description: "stale external plugin".to_string(),
  2421. install_path: missing_install_path.clone(),
  2422. source: PluginInstallSource::LocalPath {
  2423. path: missing_install_path.clone(),
  2424. },
  2425. installed_at_unix_ms: 1,
  2426. updated_at_unix_ms: 1,
  2427. },
  2428. );
  2429. manager.store_registry(&registry).expect("store registry");
  2430. let installed = manager
  2431. .list_installed_plugins()
  2432. .expect("stale registry entries should be pruned");
  2433. assert!(!installed
  2434. .iter()
  2435. .any(|plugin| plugin.metadata.id == "stale-external@external"));
  2436. let registry = manager.load_registry().expect("load registry");
  2437. assert!(!registry.plugins.contains_key("stale-external@external"));
  2438. let _ = fs::remove_dir_all(config_home);
  2439. let _ = fs::remove_dir_all(bundled_root);
  2440. }
  2441. #[test]
  2442. fn persists_bundled_plugin_enable_state_across_reloads() {
  2443. let config_home = temp_dir("bundled-state-home");
  2444. let bundled_root = temp_dir("bundled-state-root");
  2445. write_bundled_plugin(&bundled_root.join("starter"), "starter", "0.1.0", false);
  2446. let mut config = PluginManagerConfig::new(&config_home);
  2447. config.bundled_root = Some(bundled_root.clone());
  2448. let mut manager = PluginManager::new(config.clone());
  2449. manager
  2450. .enable("starter@bundled")
  2451. .expect("enable bundled plugin should succeed");
  2452. assert_eq!(
  2453. load_enabled_plugins(&manager.settings_path()).get("starter@bundled"),
  2454. Some(&true)
  2455. );
  2456. let mut reloaded_config = PluginManagerConfig::new(&config_home);
  2457. reloaded_config.bundled_root = Some(bundled_root.clone());
  2458. reloaded_config.enabled_plugins = load_enabled_plugins(&manager.settings_path());
  2459. let reloaded_manager = PluginManager::new(reloaded_config);
  2460. let reloaded = reloaded_manager
  2461. .list_installed_plugins()
  2462. .expect("bundled plugins should still be listed");
  2463. assert!(reloaded
  2464. .iter()
  2465. .any(|plugin| { plugin.metadata.id == "starter@bundled" && plugin.enabled }));
  2466. let _ = fs::remove_dir_all(config_home);
  2467. let _ = fs::remove_dir_all(bundled_root);
  2468. }
  2469. #[test]
  2470. fn persists_bundled_plugin_disable_state_across_reloads() {
  2471. let config_home = temp_dir("bundled-disabled-home");
  2472. let bundled_root = temp_dir("bundled-disabled-root");
  2473. write_bundled_plugin(&bundled_root.join("starter"), "starter", "0.1.0", true);
  2474. let mut config = PluginManagerConfig::new(&config_home);
  2475. config.bundled_root = Some(bundled_root.clone());
  2476. let mut manager = PluginManager::new(config);
  2477. manager
  2478. .disable("starter@bundled")
  2479. .expect("disable bundled plugin should succeed");
  2480. assert_eq!(
  2481. load_enabled_plugins(&manager.settings_path()).get("starter@bundled"),
  2482. Some(&false)
  2483. );
  2484. let mut reloaded_config = PluginManagerConfig::new(&config_home);
  2485. reloaded_config.bundled_root = Some(bundled_root.clone());
  2486. reloaded_config.enabled_plugins = load_enabled_plugins(&manager.settings_path());
  2487. let reloaded_manager = PluginManager::new(reloaded_config);
  2488. let reloaded = reloaded_manager
  2489. .list_installed_plugins()
  2490. .expect("bundled plugins should still be listed");
  2491. assert!(reloaded
  2492. .iter()
  2493. .any(|plugin| { plugin.metadata.id == "starter@bundled" && !plugin.enabled }));
  2494. let _ = fs::remove_dir_all(config_home);
  2495. let _ = fs::remove_dir_all(bundled_root);
  2496. }
  2497. #[test]
  2498. fn validates_plugin_source_before_install() {
  2499. let config_home = temp_dir("validate-home");
  2500. let source_root = temp_dir("validate-source");
  2501. write_external_plugin(&source_root, "validator", "1.0.0");
  2502. let manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2503. let manifest = manager
  2504. .validate_plugin_source(source_root.to_str().expect("utf8 path"))
  2505. .expect("manifest should validate");
  2506. assert_eq!(manifest.name, "validator");
  2507. let _ = fs::remove_dir_all(config_home);
  2508. let _ = fs::remove_dir_all(source_root);
  2509. }
  2510. #[test]
  2511. fn plugin_registry_tracks_enabled_state_and_lookup() {
  2512. let config_home = temp_dir("registry-home");
  2513. let source_root = temp_dir("registry-source");
  2514. write_external_plugin(&source_root, "registry-demo", "1.0.0");
  2515. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2516. manager
  2517. .install(source_root.to_str().expect("utf8 path"))
  2518. .expect("install should succeed");
  2519. manager
  2520. .disable("registry-demo@external")
  2521. .expect("disable should succeed");
  2522. let registry = manager.plugin_registry().expect("registry should build");
  2523. let plugin = registry
  2524. .get("registry-demo@external")
  2525. .expect("installed plugin should be discoverable");
  2526. assert_eq!(plugin.metadata().name, "registry-demo");
  2527. assert!(!plugin.is_enabled());
  2528. assert!(registry.contains("registry-demo@external"));
  2529. assert!(!registry.contains("missing@external"));
  2530. let _ = fs::remove_dir_all(config_home);
  2531. let _ = fs::remove_dir_all(source_root);
  2532. }
  2533. #[test]
  2534. fn rejects_plugin_sources_with_missing_hook_paths() {
  2535. let config_home = temp_dir("broken-home");
  2536. let source_root = temp_dir("broken-source");
  2537. write_broken_plugin(&source_root, "broken");
  2538. let manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2539. let error = manager
  2540. .validate_plugin_source(source_root.to_str().expect("utf8 path"))
  2541. .expect_err("missing hook file should fail validation");
  2542. assert!(error.to_string().contains("does not exist"));
  2543. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2544. let install_error = manager
  2545. .install(source_root.to_str().expect("utf8 path"))
  2546. .expect_err("install should reject invalid hook paths");
  2547. assert!(install_error.to_string().contains("does not exist"));
  2548. let _ = fs::remove_dir_all(config_home);
  2549. let _ = fs::remove_dir_all(source_root);
  2550. }
  2551. #[test]
  2552. fn plugin_registry_runs_initialize_and_shutdown_for_enabled_plugins() {
  2553. let config_home = temp_dir("lifecycle-home");
  2554. let source_root = temp_dir("lifecycle-source");
  2555. let _ = write_lifecycle_plugin(&source_root, "lifecycle-demo", "1.0.0");
  2556. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2557. let install = manager
  2558. .install(source_root.to_str().expect("utf8 path"))
  2559. .expect("install should succeed");
  2560. let log_path = install.install_path.join("lifecycle.log");
  2561. let registry = manager.plugin_registry().expect("registry should build");
  2562. registry.initialize().expect("init should succeed");
  2563. registry.shutdown().expect("shutdown should succeed");
  2564. let log = fs::read_to_string(&log_path).expect("lifecycle log should exist");
  2565. assert_eq!(log, "init\nshutdown\n");
  2566. let _ = fs::remove_dir_all(config_home);
  2567. let _ = fs::remove_dir_all(source_root);
  2568. }
  2569. #[test]
  2570. fn aggregates_and_executes_plugin_tools() {
  2571. let config_home = temp_dir("tool-home");
  2572. let source_root = temp_dir("tool-source");
  2573. write_tool_plugin(&source_root, "tool-demo", "1.0.0");
  2574. let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
  2575. manager
  2576. .install(source_root.to_str().expect("utf8 path"))
  2577. .expect("install should succeed");
  2578. let tools = manager.aggregated_tools().expect("tools should aggregate");
  2579. assert_eq!(tools.len(), 1);
  2580. assert_eq!(tools[0].definition().name, "plugin_echo");
  2581. assert_eq!(tools[0].required_permission(), "workspace-write");
  2582. let output = tools[0]
  2583. .execute(&serde_json::json!({ "message": "hello" }))
  2584. .expect("plugin tool should execute");
  2585. let payload: Value = serde_json::from_str(&output).expect("valid json");
  2586. assert_eq!(payload["plugin"], "tool-demo@external");
  2587. assert_eq!(payload["tool"], "plugin_echo");
  2588. assert_eq!(payload["input"]["message"], "hello");
  2589. let _ = fs::remove_dir_all(config_home);
  2590. let _ = fs::remove_dir_all(source_root);
  2591. }
  2592. #[test]
  2593. fn list_installed_plugins_scans_install_root_without_registry_entries() {
  2594. let config_home = temp_dir("installed-scan-home");
  2595. let bundled_root = temp_dir("installed-scan-bundled");
  2596. let install_root = config_home.join("plugins").join("installed");
  2597. let installed_plugin_root = install_root.join("scan-demo");
  2598. write_file(
  2599. installed_plugin_root.join(MANIFEST_FILE_NAME).as_path(),
  2600. r#"{
  2601. "name": "scan-demo",
  2602. "version": "1.0.0",
  2603. "description": "Scanned from install root"
  2604. }"#,
  2605. );
  2606. let mut config = PluginManagerConfig::new(&config_home);
  2607. config.bundled_root = Some(bundled_root.clone());
  2608. config.install_root = Some(install_root);
  2609. let manager = PluginManager::new(config);
  2610. let installed = manager
  2611. .list_installed_plugins()
  2612. .expect("installed plugins should scan directories");
  2613. assert!(installed
  2614. .iter()
  2615. .any(|plugin| plugin.metadata.id == "scan-demo@external"));
  2616. let _ = fs::remove_dir_all(config_home);
  2617. let _ = fs::remove_dir_all(bundled_root);
  2618. }
  2619. #[test]
  2620. fn list_installed_plugins_scans_packaged_manifests_in_install_root() {
  2621. let config_home = temp_dir("installed-packaged-scan-home");
  2622. let bundled_root = temp_dir("installed-packaged-scan-bundled");
  2623. let install_root = config_home.join("plugins").join("installed");
  2624. let installed_plugin_root = install_root.join("scan-packaged");
  2625. write_file(
  2626. installed_plugin_root.join(MANIFEST_RELATIVE_PATH).as_path(),
  2627. r#"{
  2628. "name": "scan-packaged",
  2629. "version": "1.0.0",
  2630. "description": "Packaged manifest in install root"
  2631. }"#,
  2632. );
  2633. let mut config = PluginManagerConfig::new(&config_home);
  2634. config.bundled_root = Some(bundled_root.clone());
  2635. config.install_root = Some(install_root);
  2636. let manager = PluginManager::new(config);
  2637. let installed = manager
  2638. .list_installed_plugins()
  2639. .expect("installed plugins should scan packaged manifests");
  2640. assert!(installed
  2641. .iter()
  2642. .any(|plugin| plugin.metadata.id == "scan-packaged@external"));
  2643. let _ = fs::remove_dir_all(config_home);
  2644. let _ = fs::remove_dir_all(bundled_root);
  2645. }
  2646. }