lib.rs 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526
  1. use std::collections::{BTreeMap, BTreeSet};
  2. use std::path::{Path, PathBuf};
  3. use std::process::Command;
  4. use std::time::{Duration, Instant};
  5. use api::{
  6. max_tokens_for_model, resolve_model_alias, ContentBlockDelta, InputContentBlock, InputMessage,
  7. MessageRequest, MessageResponse, OutputContentBlock, ProviderClient,
  8. StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition, ToolResultContentBlock,
  9. };
  10. use plugins::PluginTool;
  11. use reqwest::blocking::Client;
  12. use runtime::{
  13. edit_file, execute_bash, glob_search, grep_search, load_system_prompt, read_file, write_file,
  14. ApiClient, ApiRequest, AssistantEvent, BashCommandInput, ContentBlock, ConversationMessage,
  15. ConversationRuntime, GrepSearchInput, MessageRole, PermissionMode, PermissionPolicy,
  16. PromptCacheEvent, RuntimeError, Session, ToolError, ToolExecutor,
  17. };
  18. use serde::{Deserialize, Serialize};
  19. use serde_json::{json, Value};
  20. #[derive(Debug, Clone, PartialEq, Eq)]
  21. pub struct ToolManifestEntry {
  22. pub name: String,
  23. pub source: ToolSource,
  24. }
  25. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  26. pub enum ToolSource {
  27. Base,
  28. Conditional,
  29. }
  30. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  31. pub struct ToolRegistry {
  32. entries: Vec<ToolManifestEntry>,
  33. }
  34. impl ToolRegistry {
  35. #[must_use]
  36. pub fn new(entries: Vec<ToolManifestEntry>) -> Self {
  37. Self { entries }
  38. }
  39. #[must_use]
  40. pub fn entries(&self) -> &[ToolManifestEntry] {
  41. &self.entries
  42. }
  43. }
  44. #[derive(Debug, Clone, PartialEq, Eq)]
  45. pub struct ToolSpec {
  46. pub name: &'static str,
  47. pub description: &'static str,
  48. pub input_schema: Value,
  49. pub required_permission: PermissionMode,
  50. }
  51. #[derive(Debug, Clone, PartialEq)]
  52. pub struct GlobalToolRegistry {
  53. plugin_tools: Vec<PluginTool>,
  54. }
  55. impl GlobalToolRegistry {
  56. #[must_use]
  57. pub fn builtin() -> Self {
  58. Self {
  59. plugin_tools: Vec::new(),
  60. }
  61. }
  62. pub fn with_plugin_tools(plugin_tools: Vec<PluginTool>) -> Result<Self, String> {
  63. let builtin_names = mvp_tool_specs()
  64. .into_iter()
  65. .map(|spec| spec.name.to_string())
  66. .collect::<BTreeSet<_>>();
  67. let mut seen_plugin_names = BTreeSet::new();
  68. for tool in &plugin_tools {
  69. let name = tool.definition().name.clone();
  70. if builtin_names.contains(&name) {
  71. return Err(format!(
  72. "plugin tool `{name}` conflicts with a built-in tool name"
  73. ));
  74. }
  75. if !seen_plugin_names.insert(name.clone()) {
  76. return Err(format!("duplicate plugin tool name `{name}`"));
  77. }
  78. }
  79. Ok(Self { plugin_tools })
  80. }
  81. pub fn normalize_allowed_tools(
  82. &self,
  83. values: &[String],
  84. ) -> Result<Option<BTreeSet<String>>, String> {
  85. if values.is_empty() {
  86. return Ok(None);
  87. }
  88. let builtin_specs = mvp_tool_specs();
  89. let canonical_names = builtin_specs
  90. .iter()
  91. .map(|spec| spec.name.to_string())
  92. .chain(
  93. self.plugin_tools
  94. .iter()
  95. .map(|tool| tool.definition().name.clone()),
  96. )
  97. .collect::<Vec<_>>();
  98. let mut name_map = canonical_names
  99. .iter()
  100. .map(|name| (normalize_tool_name(name), name.clone()))
  101. .collect::<BTreeMap<_, _>>();
  102. for (alias, canonical) in [
  103. ("read", "read_file"),
  104. ("write", "write_file"),
  105. ("edit", "edit_file"),
  106. ("glob", "glob_search"),
  107. ("grep", "grep_search"),
  108. ] {
  109. name_map.insert(alias.to_string(), canonical.to_string());
  110. }
  111. let mut allowed = BTreeSet::new();
  112. for value in values {
  113. for token in value
  114. .split(|ch: char| ch == ',' || ch.is_whitespace())
  115. .filter(|token| !token.is_empty())
  116. {
  117. let normalized = normalize_tool_name(token);
  118. let canonical = name_map.get(&normalized).ok_or_else(|| {
  119. format!(
  120. "unsupported tool in --allowedTools: {token} (expected one of: {})",
  121. canonical_names.join(", ")
  122. )
  123. })?;
  124. allowed.insert(canonical.clone());
  125. }
  126. }
  127. Ok(Some(allowed))
  128. }
  129. #[must_use]
  130. pub fn definitions(&self, allowed_tools: Option<&BTreeSet<String>>) -> Vec<ToolDefinition> {
  131. let builtin = mvp_tool_specs()
  132. .into_iter()
  133. .filter(|spec| allowed_tools.is_none_or(|allowed| allowed.contains(spec.name)))
  134. .map(|spec| ToolDefinition {
  135. name: spec.name.to_string(),
  136. description: Some(spec.description.to_string()),
  137. input_schema: spec.input_schema,
  138. });
  139. let plugin = self
  140. .plugin_tools
  141. .iter()
  142. .filter(|tool| {
  143. allowed_tools
  144. .is_none_or(|allowed| allowed.contains(tool.definition().name.as_str()))
  145. })
  146. .map(|tool| ToolDefinition {
  147. name: tool.definition().name.clone(),
  148. description: tool.definition().description.clone(),
  149. input_schema: tool.definition().input_schema.clone(),
  150. });
  151. builtin.chain(plugin).collect()
  152. }
  153. #[must_use]
  154. pub fn permission_specs(
  155. &self,
  156. allowed_tools: Option<&BTreeSet<String>>,
  157. ) -> Result<Vec<(String, PermissionMode)>, String> {
  158. let builtin = mvp_tool_specs()
  159. .into_iter()
  160. .filter(|spec| allowed_tools.is_none_or(|allowed| allowed.contains(spec.name)))
  161. .map(|spec| (spec.name.to_string(), spec.required_permission));
  162. let plugin = self
  163. .plugin_tools
  164. .iter()
  165. .filter(|tool| {
  166. allowed_tools
  167. .is_none_or(|allowed| allowed.contains(tool.definition().name.as_str()))
  168. })
  169. .map(|tool| {
  170. permission_mode_from_plugin(tool.required_permission())
  171. .map(|permission| (tool.definition().name.clone(), permission))
  172. })
  173. .collect::<Result<Vec<_>, _>>()?;
  174. Ok(builtin.chain(plugin).collect())
  175. }
  176. pub fn execute(&self, name: &str, input: &Value) -> Result<String, String> {
  177. if mvp_tool_specs().iter().any(|spec| spec.name == name) {
  178. return execute_tool(name, input);
  179. }
  180. self.plugin_tools
  181. .iter()
  182. .find(|tool| tool.definition().name == name)
  183. .ok_or_else(|| format!("unsupported tool: {name}"))?
  184. .execute(input)
  185. .map_err(|error| error.to_string())
  186. }
  187. }
  188. fn normalize_tool_name(value: &str) -> String {
  189. value.trim().replace('-', "_").to_ascii_lowercase()
  190. }
  191. fn permission_mode_from_plugin(value: &str) -> Result<PermissionMode, String> {
  192. match value {
  193. "read-only" => Ok(PermissionMode::ReadOnly),
  194. "workspace-write" => Ok(PermissionMode::WorkspaceWrite),
  195. "danger-full-access" => Ok(PermissionMode::DangerFullAccess),
  196. other => Err(format!("unsupported plugin permission: {other}")),
  197. }
  198. }
  199. #[must_use]
  200. #[allow(clippy::too_many_lines)]
  201. pub fn mvp_tool_specs() -> Vec<ToolSpec> {
  202. vec![
  203. ToolSpec {
  204. name: "bash",
  205. description: "Execute a shell command in the current workspace.",
  206. input_schema: json!({
  207. "type": "object",
  208. "properties": {
  209. "command": { "type": "string" },
  210. "timeout": { "type": "integer", "minimum": 1 },
  211. "description": { "type": "string" },
  212. "run_in_background": { "type": "boolean" },
  213. "dangerouslyDisableSandbox": { "type": "boolean" },
  214. "namespaceRestrictions": { "type": "boolean" },
  215. "isolateNetwork": { "type": "boolean" },
  216. "filesystemMode": { "type": "string", "enum": ["off", "workspace-only", "allow-list"] },
  217. "allowedMounts": { "type": "array", "items": { "type": "string" } }
  218. },
  219. "required": ["command"],
  220. "additionalProperties": false
  221. }),
  222. required_permission: PermissionMode::DangerFullAccess,
  223. },
  224. ToolSpec {
  225. name: "read_file",
  226. description: "Read a text file from the workspace.",
  227. input_schema: json!({
  228. "type": "object",
  229. "properties": {
  230. "path": { "type": "string" },
  231. "offset": { "type": "integer", "minimum": 0 },
  232. "limit": { "type": "integer", "minimum": 1 }
  233. },
  234. "required": ["path"],
  235. "additionalProperties": false
  236. }),
  237. required_permission: PermissionMode::ReadOnly,
  238. },
  239. ToolSpec {
  240. name: "write_file",
  241. description: "Write a text file in the workspace.",
  242. input_schema: json!({
  243. "type": "object",
  244. "properties": {
  245. "path": { "type": "string" },
  246. "content": { "type": "string" }
  247. },
  248. "required": ["path", "content"],
  249. "additionalProperties": false
  250. }),
  251. required_permission: PermissionMode::WorkspaceWrite,
  252. },
  253. ToolSpec {
  254. name: "edit_file",
  255. description: "Replace text in a workspace file.",
  256. input_schema: json!({
  257. "type": "object",
  258. "properties": {
  259. "path": { "type": "string" },
  260. "old_string": { "type": "string" },
  261. "new_string": { "type": "string" },
  262. "replace_all": { "type": "boolean" }
  263. },
  264. "required": ["path", "old_string", "new_string"],
  265. "additionalProperties": false
  266. }),
  267. required_permission: PermissionMode::WorkspaceWrite,
  268. },
  269. ToolSpec {
  270. name: "glob_search",
  271. description: "Find files by glob pattern.",
  272. input_schema: json!({
  273. "type": "object",
  274. "properties": {
  275. "pattern": { "type": "string" },
  276. "path": { "type": "string" }
  277. },
  278. "required": ["pattern"],
  279. "additionalProperties": false
  280. }),
  281. required_permission: PermissionMode::ReadOnly,
  282. },
  283. ToolSpec {
  284. name: "grep_search",
  285. description: "Search file contents with a regex pattern.",
  286. input_schema: json!({
  287. "type": "object",
  288. "properties": {
  289. "pattern": { "type": "string" },
  290. "path": { "type": "string" },
  291. "glob": { "type": "string" },
  292. "output_mode": { "type": "string" },
  293. "-B": { "type": "integer", "minimum": 0 },
  294. "-A": { "type": "integer", "minimum": 0 },
  295. "-C": { "type": "integer", "minimum": 0 },
  296. "context": { "type": "integer", "minimum": 0 },
  297. "-n": { "type": "boolean" },
  298. "-i": { "type": "boolean" },
  299. "type": { "type": "string" },
  300. "head_limit": { "type": "integer", "minimum": 1 },
  301. "offset": { "type": "integer", "minimum": 0 },
  302. "multiline": { "type": "boolean" }
  303. },
  304. "required": ["pattern"],
  305. "additionalProperties": false
  306. }),
  307. required_permission: PermissionMode::ReadOnly,
  308. },
  309. ToolSpec {
  310. name: "WebFetch",
  311. description:
  312. "Fetch a URL, convert it into readable text, and answer a prompt about it.",
  313. input_schema: json!({
  314. "type": "object",
  315. "properties": {
  316. "url": { "type": "string", "format": "uri" },
  317. "prompt": { "type": "string" }
  318. },
  319. "required": ["url", "prompt"],
  320. "additionalProperties": false
  321. }),
  322. required_permission: PermissionMode::ReadOnly,
  323. },
  324. ToolSpec {
  325. name: "WebSearch",
  326. description: "Search the web for current information and return cited results.",
  327. input_schema: json!({
  328. "type": "object",
  329. "properties": {
  330. "query": { "type": "string", "minLength": 2 },
  331. "allowed_domains": {
  332. "type": "array",
  333. "items": { "type": "string" }
  334. },
  335. "blocked_domains": {
  336. "type": "array",
  337. "items": { "type": "string" }
  338. }
  339. },
  340. "required": ["query"],
  341. "additionalProperties": false
  342. }),
  343. required_permission: PermissionMode::ReadOnly,
  344. },
  345. ToolSpec {
  346. name: "TodoWrite",
  347. description: "Update the structured task list for the current session.",
  348. input_schema: json!({
  349. "type": "object",
  350. "properties": {
  351. "todos": {
  352. "type": "array",
  353. "items": {
  354. "type": "object",
  355. "properties": {
  356. "content": { "type": "string" },
  357. "activeForm": { "type": "string" },
  358. "status": {
  359. "type": "string",
  360. "enum": ["pending", "in_progress", "completed"]
  361. }
  362. },
  363. "required": ["content", "activeForm", "status"],
  364. "additionalProperties": false
  365. }
  366. }
  367. },
  368. "required": ["todos"],
  369. "additionalProperties": false
  370. }),
  371. required_permission: PermissionMode::WorkspaceWrite,
  372. },
  373. ToolSpec {
  374. name: "Skill",
  375. description: "Load a local skill definition and its instructions.",
  376. input_schema: json!({
  377. "type": "object",
  378. "properties": {
  379. "skill": { "type": "string" },
  380. "args": { "type": "string" }
  381. },
  382. "required": ["skill"],
  383. "additionalProperties": false
  384. }),
  385. required_permission: PermissionMode::ReadOnly,
  386. },
  387. ToolSpec {
  388. name: "Agent",
  389. description: "Launch a specialized agent task and persist its handoff metadata.",
  390. input_schema: json!({
  391. "type": "object",
  392. "properties": {
  393. "description": { "type": "string" },
  394. "prompt": { "type": "string" },
  395. "subagent_type": { "type": "string" },
  396. "name": { "type": "string" },
  397. "model": { "type": "string" }
  398. },
  399. "required": ["description", "prompt"],
  400. "additionalProperties": false
  401. }),
  402. required_permission: PermissionMode::DangerFullAccess,
  403. },
  404. ToolSpec {
  405. name: "ToolSearch",
  406. description: "Search for deferred or specialized tools by exact name or keywords.",
  407. input_schema: json!({
  408. "type": "object",
  409. "properties": {
  410. "query": { "type": "string" },
  411. "max_results": { "type": "integer", "minimum": 1 }
  412. },
  413. "required": ["query"],
  414. "additionalProperties": false
  415. }),
  416. required_permission: PermissionMode::ReadOnly,
  417. },
  418. ToolSpec {
  419. name: "NotebookEdit",
  420. description: "Replace, insert, or delete a cell in a Jupyter notebook.",
  421. input_schema: json!({
  422. "type": "object",
  423. "properties": {
  424. "notebook_path": { "type": "string" },
  425. "cell_id": { "type": "string" },
  426. "new_source": { "type": "string" },
  427. "cell_type": { "type": "string", "enum": ["code", "markdown"] },
  428. "edit_mode": { "type": "string", "enum": ["replace", "insert", "delete"] }
  429. },
  430. "required": ["notebook_path"],
  431. "additionalProperties": false
  432. }),
  433. required_permission: PermissionMode::WorkspaceWrite,
  434. },
  435. ToolSpec {
  436. name: "Sleep",
  437. description: "Wait for a specified duration without holding a shell process.",
  438. input_schema: json!({
  439. "type": "object",
  440. "properties": {
  441. "duration_ms": { "type": "integer", "minimum": 0 }
  442. },
  443. "required": ["duration_ms"],
  444. "additionalProperties": false
  445. }),
  446. required_permission: PermissionMode::ReadOnly,
  447. },
  448. ToolSpec {
  449. name: "SendUserMessage",
  450. description: "Send a message to the user.",
  451. input_schema: json!({
  452. "type": "object",
  453. "properties": {
  454. "message": { "type": "string" },
  455. "attachments": {
  456. "type": "array",
  457. "items": { "type": "string" }
  458. },
  459. "status": {
  460. "type": "string",
  461. "enum": ["normal", "proactive"]
  462. }
  463. },
  464. "required": ["message", "status"],
  465. "additionalProperties": false
  466. }),
  467. required_permission: PermissionMode::ReadOnly,
  468. },
  469. ToolSpec {
  470. name: "Config",
  471. description: "Get or set Claude Code settings.",
  472. input_schema: json!({
  473. "type": "object",
  474. "properties": {
  475. "setting": { "type": "string" },
  476. "value": {
  477. "type": ["string", "boolean", "number"]
  478. }
  479. },
  480. "required": ["setting"],
  481. "additionalProperties": false
  482. }),
  483. required_permission: PermissionMode::WorkspaceWrite,
  484. },
  485. ToolSpec {
  486. name: "StructuredOutput",
  487. description: "Return structured output in the requested format.",
  488. input_schema: json!({
  489. "type": "object",
  490. "additionalProperties": true
  491. }),
  492. required_permission: PermissionMode::ReadOnly,
  493. },
  494. ToolSpec {
  495. name: "REPL",
  496. description: "Execute code in a REPL-like subprocess.",
  497. input_schema: json!({
  498. "type": "object",
  499. "properties": {
  500. "code": { "type": "string" },
  501. "language": { "type": "string" },
  502. "timeout_ms": { "type": "integer", "minimum": 1 }
  503. },
  504. "required": ["code", "language"],
  505. "additionalProperties": false
  506. }),
  507. required_permission: PermissionMode::DangerFullAccess,
  508. },
  509. ToolSpec {
  510. name: "PowerShell",
  511. description: "Execute a PowerShell command with optional timeout.",
  512. input_schema: json!({
  513. "type": "object",
  514. "properties": {
  515. "command": { "type": "string" },
  516. "timeout": { "type": "integer", "minimum": 1 },
  517. "description": { "type": "string" },
  518. "run_in_background": { "type": "boolean" }
  519. },
  520. "required": ["command"],
  521. "additionalProperties": false
  522. }),
  523. required_permission: PermissionMode::DangerFullAccess,
  524. },
  525. ]
  526. }
  527. pub fn execute_tool(name: &str, input: &Value) -> Result<String, String> {
  528. match name {
  529. "bash" => from_value::<BashCommandInput>(input).and_then(run_bash),
  530. "read_file" => from_value::<ReadFileInput>(input).and_then(run_read_file),
  531. "write_file" => from_value::<WriteFileInput>(input).and_then(run_write_file),
  532. "edit_file" => from_value::<EditFileInput>(input).and_then(run_edit_file),
  533. "glob_search" => from_value::<GlobSearchInputValue>(input).and_then(run_glob_search),
  534. "grep_search" => from_value::<GrepSearchInput>(input).and_then(run_grep_search),
  535. "WebFetch" => from_value::<WebFetchInput>(input).and_then(run_web_fetch),
  536. "WebSearch" => from_value::<WebSearchInput>(input).and_then(run_web_search),
  537. "TodoWrite" => from_value::<TodoWriteInput>(input).and_then(run_todo_write),
  538. "Skill" => from_value::<SkillInput>(input).and_then(run_skill),
  539. "Agent" => from_value::<AgentInput>(input).and_then(run_agent),
  540. "ToolSearch" => from_value::<ToolSearchInput>(input).and_then(run_tool_search),
  541. "NotebookEdit" => from_value::<NotebookEditInput>(input).and_then(run_notebook_edit),
  542. "Sleep" => from_value::<SleepInput>(input).and_then(run_sleep),
  543. "SendUserMessage" | "Brief" => from_value::<BriefInput>(input).and_then(run_brief),
  544. "Config" => from_value::<ConfigInput>(input).and_then(run_config),
  545. "StructuredOutput" => {
  546. from_value::<StructuredOutputInput>(input).and_then(run_structured_output)
  547. }
  548. "REPL" => from_value::<ReplInput>(input).and_then(run_repl),
  549. "PowerShell" => from_value::<PowerShellInput>(input).and_then(run_powershell),
  550. _ => Err(format!("unsupported tool: {name}")),
  551. }
  552. }
  553. fn from_value<T: for<'de> Deserialize<'de>>(input: &Value) -> Result<T, String> {
  554. serde_json::from_value(input.clone()).map_err(|error| error.to_string())
  555. }
  556. fn run_bash(input: BashCommandInput) -> Result<String, String> {
  557. serde_json::to_string_pretty(&execute_bash(input).map_err(|error| error.to_string())?)
  558. .map_err(|error| error.to_string())
  559. }
  560. #[allow(clippy::needless_pass_by_value)]
  561. fn run_read_file(input: ReadFileInput) -> Result<String, String> {
  562. to_pretty_json(read_file(&input.path, input.offset, input.limit).map_err(io_to_string)?)
  563. }
  564. #[allow(clippy::needless_pass_by_value)]
  565. fn run_write_file(input: WriteFileInput) -> Result<String, String> {
  566. to_pretty_json(write_file(&input.path, &input.content).map_err(io_to_string)?)
  567. }
  568. #[allow(clippy::needless_pass_by_value)]
  569. fn run_edit_file(input: EditFileInput) -> Result<String, String> {
  570. to_pretty_json(
  571. edit_file(
  572. &input.path,
  573. &input.old_string,
  574. &input.new_string,
  575. input.replace_all.unwrap_or(false),
  576. )
  577. .map_err(io_to_string)?,
  578. )
  579. }
  580. #[allow(clippy::needless_pass_by_value)]
  581. fn run_glob_search(input: GlobSearchInputValue) -> Result<String, String> {
  582. to_pretty_json(glob_search(&input.pattern, input.path.as_deref()).map_err(io_to_string)?)
  583. }
  584. #[allow(clippy::needless_pass_by_value)]
  585. fn run_grep_search(input: GrepSearchInput) -> Result<String, String> {
  586. to_pretty_json(grep_search(&input).map_err(io_to_string)?)
  587. }
  588. #[allow(clippy::needless_pass_by_value)]
  589. fn run_web_fetch(input: WebFetchInput) -> Result<String, String> {
  590. to_pretty_json(execute_web_fetch(&input)?)
  591. }
  592. #[allow(clippy::needless_pass_by_value)]
  593. fn run_web_search(input: WebSearchInput) -> Result<String, String> {
  594. to_pretty_json(execute_web_search(&input)?)
  595. }
  596. fn run_todo_write(input: TodoWriteInput) -> Result<String, String> {
  597. to_pretty_json(execute_todo_write(input)?)
  598. }
  599. fn run_skill(input: SkillInput) -> Result<String, String> {
  600. to_pretty_json(execute_skill(input)?)
  601. }
  602. fn run_agent(input: AgentInput) -> Result<String, String> {
  603. to_pretty_json(execute_agent(input)?)
  604. }
  605. fn run_tool_search(input: ToolSearchInput) -> Result<String, String> {
  606. to_pretty_json(execute_tool_search(input))
  607. }
  608. fn run_notebook_edit(input: NotebookEditInput) -> Result<String, String> {
  609. to_pretty_json(execute_notebook_edit(input)?)
  610. }
  611. fn run_sleep(input: SleepInput) -> Result<String, String> {
  612. to_pretty_json(execute_sleep(input))
  613. }
  614. fn run_brief(input: BriefInput) -> Result<String, String> {
  615. to_pretty_json(execute_brief(input)?)
  616. }
  617. fn run_config(input: ConfigInput) -> Result<String, String> {
  618. to_pretty_json(execute_config(input)?)
  619. }
  620. fn run_structured_output(input: StructuredOutputInput) -> Result<String, String> {
  621. to_pretty_json(execute_structured_output(input))
  622. }
  623. fn run_repl(input: ReplInput) -> Result<String, String> {
  624. to_pretty_json(execute_repl(input)?)
  625. }
  626. fn run_powershell(input: PowerShellInput) -> Result<String, String> {
  627. to_pretty_json(execute_powershell(input).map_err(|error| error.to_string())?)
  628. }
  629. fn to_pretty_json<T: serde::Serialize>(value: T) -> Result<String, String> {
  630. serde_json::to_string_pretty(&value).map_err(|error| error.to_string())
  631. }
  632. #[allow(clippy::needless_pass_by_value)]
  633. fn io_to_string(error: std::io::Error) -> String {
  634. error.to_string()
  635. }
  636. #[derive(Debug, Deserialize)]
  637. struct ReadFileInput {
  638. path: String,
  639. offset: Option<usize>,
  640. limit: Option<usize>,
  641. }
  642. #[derive(Debug, Deserialize)]
  643. struct WriteFileInput {
  644. path: String,
  645. content: String,
  646. }
  647. #[derive(Debug, Deserialize)]
  648. struct EditFileInput {
  649. path: String,
  650. old_string: String,
  651. new_string: String,
  652. replace_all: Option<bool>,
  653. }
  654. #[derive(Debug, Deserialize)]
  655. struct GlobSearchInputValue {
  656. pattern: String,
  657. path: Option<String>,
  658. }
  659. #[derive(Debug, Deserialize)]
  660. struct WebFetchInput {
  661. url: String,
  662. prompt: String,
  663. }
  664. #[derive(Debug, Deserialize)]
  665. struct WebSearchInput {
  666. query: String,
  667. allowed_domains: Option<Vec<String>>,
  668. blocked_domains: Option<Vec<String>>,
  669. }
  670. #[derive(Debug, Deserialize)]
  671. struct TodoWriteInput {
  672. todos: Vec<TodoItem>,
  673. }
  674. #[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
  675. struct TodoItem {
  676. content: String,
  677. #[serde(rename = "activeForm")]
  678. active_form: String,
  679. status: TodoStatus,
  680. }
  681. #[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
  682. #[serde(rename_all = "snake_case")]
  683. enum TodoStatus {
  684. Pending,
  685. InProgress,
  686. Completed,
  687. }
  688. #[derive(Debug, Deserialize)]
  689. struct SkillInput {
  690. skill: String,
  691. args: Option<String>,
  692. }
  693. #[derive(Debug, Deserialize)]
  694. struct AgentInput {
  695. description: String,
  696. prompt: String,
  697. subagent_type: Option<String>,
  698. name: Option<String>,
  699. model: Option<String>,
  700. }
  701. #[derive(Debug, Deserialize)]
  702. struct ToolSearchInput {
  703. query: String,
  704. max_results: Option<usize>,
  705. }
  706. #[derive(Debug, Deserialize)]
  707. struct NotebookEditInput {
  708. notebook_path: String,
  709. cell_id: Option<String>,
  710. new_source: Option<String>,
  711. cell_type: Option<NotebookCellType>,
  712. edit_mode: Option<NotebookEditMode>,
  713. }
  714. #[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]
  715. #[serde(rename_all = "lowercase")]
  716. enum NotebookCellType {
  717. Code,
  718. Markdown,
  719. }
  720. #[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]
  721. #[serde(rename_all = "lowercase")]
  722. enum NotebookEditMode {
  723. Replace,
  724. Insert,
  725. Delete,
  726. }
  727. #[derive(Debug, Deserialize)]
  728. struct SleepInput {
  729. duration_ms: u64,
  730. }
  731. #[derive(Debug, Deserialize)]
  732. struct BriefInput {
  733. message: String,
  734. attachments: Option<Vec<String>>,
  735. status: BriefStatus,
  736. }
  737. #[derive(Debug, Deserialize)]
  738. #[serde(rename_all = "lowercase")]
  739. enum BriefStatus {
  740. Normal,
  741. Proactive,
  742. }
  743. #[derive(Debug, Deserialize)]
  744. struct ConfigInput {
  745. setting: String,
  746. value: Option<ConfigValue>,
  747. }
  748. #[derive(Debug, Deserialize)]
  749. #[serde(untagged)]
  750. enum ConfigValue {
  751. String(String),
  752. Bool(bool),
  753. Number(f64),
  754. }
  755. #[derive(Debug, Deserialize)]
  756. #[serde(transparent)]
  757. struct StructuredOutputInput(BTreeMap<String, Value>);
  758. #[derive(Debug, Deserialize)]
  759. struct ReplInput {
  760. code: String,
  761. language: String,
  762. timeout_ms: Option<u64>,
  763. }
  764. #[derive(Debug, Deserialize)]
  765. struct PowerShellInput {
  766. command: String,
  767. timeout: Option<u64>,
  768. description: Option<String>,
  769. run_in_background: Option<bool>,
  770. }
  771. #[derive(Debug, Serialize)]
  772. struct WebFetchOutput {
  773. bytes: usize,
  774. code: u16,
  775. #[serde(rename = "codeText")]
  776. code_text: String,
  777. result: String,
  778. #[serde(rename = "durationMs")]
  779. duration_ms: u128,
  780. url: String,
  781. }
  782. #[derive(Debug, Serialize)]
  783. struct WebSearchOutput {
  784. query: String,
  785. results: Vec<WebSearchResultItem>,
  786. #[serde(rename = "durationSeconds")]
  787. duration_seconds: f64,
  788. }
  789. #[derive(Debug, Serialize)]
  790. struct TodoWriteOutput {
  791. #[serde(rename = "oldTodos")]
  792. old_todos: Vec<TodoItem>,
  793. #[serde(rename = "newTodos")]
  794. new_todos: Vec<TodoItem>,
  795. #[serde(rename = "verificationNudgeNeeded")]
  796. verification_nudge_needed: Option<bool>,
  797. }
  798. #[derive(Debug, Serialize)]
  799. struct SkillOutput {
  800. skill: String,
  801. path: String,
  802. args: Option<String>,
  803. description: Option<String>,
  804. prompt: String,
  805. }
  806. #[derive(Debug, Clone, Serialize, Deserialize)]
  807. struct AgentOutput {
  808. #[serde(rename = "agentId")]
  809. agent_id: String,
  810. name: String,
  811. description: String,
  812. #[serde(rename = "subagentType")]
  813. subagent_type: Option<String>,
  814. model: Option<String>,
  815. status: String,
  816. #[serde(rename = "outputFile")]
  817. output_file: String,
  818. #[serde(rename = "manifestFile")]
  819. manifest_file: String,
  820. #[serde(rename = "createdAt")]
  821. created_at: String,
  822. #[serde(rename = "startedAt", skip_serializing_if = "Option::is_none")]
  823. started_at: Option<String>,
  824. #[serde(rename = "completedAt", skip_serializing_if = "Option::is_none")]
  825. completed_at: Option<String>,
  826. #[serde(skip_serializing_if = "Option::is_none")]
  827. error: Option<String>,
  828. }
  829. #[derive(Debug, Clone)]
  830. struct AgentJob {
  831. manifest: AgentOutput,
  832. prompt: String,
  833. system_prompt: Vec<String>,
  834. allowed_tools: BTreeSet<String>,
  835. }
  836. #[derive(Debug, Serialize)]
  837. struct ToolSearchOutput {
  838. matches: Vec<String>,
  839. query: String,
  840. normalized_query: String,
  841. #[serde(rename = "total_deferred_tools")]
  842. total_deferred_tools: usize,
  843. #[serde(rename = "pending_mcp_servers")]
  844. pending_mcp_servers: Option<Vec<String>>,
  845. }
  846. #[derive(Debug, Serialize)]
  847. struct NotebookEditOutput {
  848. new_source: String,
  849. cell_id: Option<String>,
  850. cell_type: Option<NotebookCellType>,
  851. language: String,
  852. edit_mode: String,
  853. error: Option<String>,
  854. notebook_path: String,
  855. original_file: String,
  856. updated_file: String,
  857. }
  858. #[derive(Debug, Serialize)]
  859. struct SleepOutput {
  860. duration_ms: u64,
  861. message: String,
  862. }
  863. #[derive(Debug, Serialize)]
  864. struct BriefOutput {
  865. message: String,
  866. attachments: Option<Vec<ResolvedAttachment>>,
  867. #[serde(rename = "sentAt")]
  868. sent_at: String,
  869. }
  870. #[derive(Debug, Serialize)]
  871. struct ResolvedAttachment {
  872. path: String,
  873. size: u64,
  874. #[serde(rename = "isImage")]
  875. is_image: bool,
  876. }
  877. #[derive(Debug, Serialize)]
  878. struct ConfigOutput {
  879. success: bool,
  880. operation: Option<String>,
  881. setting: Option<String>,
  882. value: Option<Value>,
  883. #[serde(rename = "previousValue")]
  884. previous_value: Option<Value>,
  885. #[serde(rename = "newValue")]
  886. new_value: Option<Value>,
  887. error: Option<String>,
  888. }
  889. #[derive(Debug, Serialize)]
  890. struct StructuredOutputResult {
  891. data: String,
  892. structured_output: BTreeMap<String, Value>,
  893. }
  894. #[derive(Debug, Serialize)]
  895. struct ReplOutput {
  896. language: String,
  897. stdout: String,
  898. stderr: String,
  899. #[serde(rename = "exitCode")]
  900. exit_code: i32,
  901. #[serde(rename = "durationMs")]
  902. duration_ms: u128,
  903. }
  904. #[derive(Debug, Serialize)]
  905. #[serde(untagged)]
  906. enum WebSearchResultItem {
  907. SearchResult {
  908. tool_use_id: String,
  909. content: Vec<SearchHit>,
  910. },
  911. Commentary(String),
  912. }
  913. #[derive(Debug, Serialize)]
  914. struct SearchHit {
  915. title: String,
  916. url: String,
  917. }
  918. fn execute_web_fetch(input: &WebFetchInput) -> Result<WebFetchOutput, String> {
  919. let started = Instant::now();
  920. let client = build_http_client()?;
  921. let request_url = normalize_fetch_url(&input.url)?;
  922. let response = client
  923. .get(request_url.clone())
  924. .send()
  925. .map_err(|error| error.to_string())?;
  926. let status = response.status();
  927. let final_url = response.url().to_string();
  928. let code = status.as_u16();
  929. let code_text = status.canonical_reason().unwrap_or("Unknown").to_string();
  930. let content_type = response
  931. .headers()
  932. .get(reqwest::header::CONTENT_TYPE)
  933. .and_then(|value| value.to_str().ok())
  934. .unwrap_or_default()
  935. .to_string();
  936. let body = response.text().map_err(|error| error.to_string())?;
  937. let bytes = body.len();
  938. let normalized = normalize_fetched_content(&body, &content_type);
  939. let result = summarize_web_fetch(&final_url, &input.prompt, &normalized, &body, &content_type);
  940. Ok(WebFetchOutput {
  941. bytes,
  942. code,
  943. code_text,
  944. result,
  945. duration_ms: started.elapsed().as_millis(),
  946. url: final_url,
  947. })
  948. }
  949. fn execute_web_search(input: &WebSearchInput) -> Result<WebSearchOutput, String> {
  950. let started = Instant::now();
  951. let client = build_http_client()?;
  952. let search_url = build_search_url(&input.query)?;
  953. let response = client
  954. .get(search_url)
  955. .send()
  956. .map_err(|error| error.to_string())?;
  957. let final_url = response.url().clone();
  958. let html = response.text().map_err(|error| error.to_string())?;
  959. let mut hits = extract_search_hits(&html);
  960. if hits.is_empty() && final_url.host_str().is_some() {
  961. hits = extract_search_hits_from_generic_links(&html);
  962. }
  963. if let Some(allowed) = input.allowed_domains.as_ref() {
  964. hits.retain(|hit| host_matches_list(&hit.url, allowed));
  965. }
  966. if let Some(blocked) = input.blocked_domains.as_ref() {
  967. hits.retain(|hit| !host_matches_list(&hit.url, blocked));
  968. }
  969. dedupe_hits(&mut hits);
  970. hits.truncate(8);
  971. let summary = if hits.is_empty() {
  972. format!("No web search results matched the query {:?}.", input.query)
  973. } else {
  974. let rendered_hits = hits
  975. .iter()
  976. .map(|hit| format!("- [{}]({})", hit.title, hit.url))
  977. .collect::<Vec<_>>()
  978. .join("\n");
  979. format!(
  980. "Search results for {:?}. Include a Sources section in the final answer.\n{}",
  981. input.query, rendered_hits
  982. )
  983. };
  984. Ok(WebSearchOutput {
  985. query: input.query.clone(),
  986. results: vec![
  987. WebSearchResultItem::Commentary(summary),
  988. WebSearchResultItem::SearchResult {
  989. tool_use_id: String::from("web_search_1"),
  990. content: hits,
  991. },
  992. ],
  993. duration_seconds: started.elapsed().as_secs_f64(),
  994. })
  995. }
  996. fn build_http_client() -> Result<Client, String> {
  997. Client::builder()
  998. .timeout(Duration::from_secs(20))
  999. .redirect(reqwest::redirect::Policy::limited(10))
  1000. .user_agent("clawd-rust-tools/0.1")
  1001. .build()
  1002. .map_err(|error| error.to_string())
  1003. }
  1004. fn normalize_fetch_url(url: &str) -> Result<String, String> {
  1005. let parsed = reqwest::Url::parse(url).map_err(|error| error.to_string())?;
  1006. if parsed.scheme() == "http" {
  1007. let host = parsed.host_str().unwrap_or_default();
  1008. if host != "localhost" && host != "127.0.0.1" && host != "::1" {
  1009. let mut upgraded = parsed;
  1010. upgraded
  1011. .set_scheme("https")
  1012. .map_err(|()| String::from("failed to upgrade URL to https"))?;
  1013. return Ok(upgraded.to_string());
  1014. }
  1015. }
  1016. Ok(parsed.to_string())
  1017. }
  1018. fn build_search_url(query: &str) -> Result<reqwest::Url, String> {
  1019. if let Ok(base) = std::env::var("CLAWD_WEB_SEARCH_BASE_URL") {
  1020. let mut url = reqwest::Url::parse(&base).map_err(|error| error.to_string())?;
  1021. url.query_pairs_mut().append_pair("q", query);
  1022. return Ok(url);
  1023. }
  1024. let mut url = reqwest::Url::parse("https://html.duckduckgo.com/html/")
  1025. .map_err(|error| error.to_string())?;
  1026. url.query_pairs_mut().append_pair("q", query);
  1027. Ok(url)
  1028. }
  1029. fn normalize_fetched_content(body: &str, content_type: &str) -> String {
  1030. if content_type.contains("html") {
  1031. html_to_text(body)
  1032. } else {
  1033. body.trim().to_string()
  1034. }
  1035. }
  1036. fn summarize_web_fetch(
  1037. url: &str,
  1038. prompt: &str,
  1039. content: &str,
  1040. raw_body: &str,
  1041. content_type: &str,
  1042. ) -> String {
  1043. let lower_prompt = prompt.to_lowercase();
  1044. let compact = collapse_whitespace(content);
  1045. let detail = if lower_prompt.contains("title") {
  1046. extract_title(content, raw_body, content_type).map_or_else(
  1047. || preview_text(&compact, 600),
  1048. |title| format!("Title: {title}"),
  1049. )
  1050. } else if lower_prompt.contains("summary") || lower_prompt.contains("summarize") {
  1051. preview_text(&compact, 900)
  1052. } else {
  1053. let preview = preview_text(&compact, 900);
  1054. format!("Prompt: {prompt}\nContent preview:\n{preview}")
  1055. };
  1056. format!("Fetched {url}\n{detail}")
  1057. }
  1058. fn extract_title(content: &str, raw_body: &str, content_type: &str) -> Option<String> {
  1059. if content_type.contains("html") {
  1060. let lowered = raw_body.to_lowercase();
  1061. if let Some(start) = lowered.find("<title>") {
  1062. let after = start + "<title>".len();
  1063. if let Some(end_rel) = lowered[after..].find("</title>") {
  1064. let title =
  1065. collapse_whitespace(&decode_html_entities(&raw_body[after..after + end_rel]));
  1066. if !title.is_empty() {
  1067. return Some(title);
  1068. }
  1069. }
  1070. }
  1071. }
  1072. for line in content.lines() {
  1073. let trimmed = line.trim();
  1074. if !trimmed.is_empty() {
  1075. return Some(trimmed.to_string());
  1076. }
  1077. }
  1078. None
  1079. }
  1080. fn html_to_text(html: &str) -> String {
  1081. let mut text = String::with_capacity(html.len());
  1082. let mut in_tag = false;
  1083. let mut previous_was_space = false;
  1084. for ch in html.chars() {
  1085. match ch {
  1086. '<' => in_tag = true,
  1087. '>' => in_tag = false,
  1088. _ if in_tag => {}
  1089. '&' => {
  1090. text.push('&');
  1091. previous_was_space = false;
  1092. }
  1093. ch if ch.is_whitespace() => {
  1094. if !previous_was_space {
  1095. text.push(' ');
  1096. previous_was_space = true;
  1097. }
  1098. }
  1099. _ => {
  1100. text.push(ch);
  1101. previous_was_space = false;
  1102. }
  1103. }
  1104. }
  1105. collapse_whitespace(&decode_html_entities(&text))
  1106. }
  1107. fn decode_html_entities(input: &str) -> String {
  1108. input
  1109. .replace("&amp;", "&")
  1110. .replace("&lt;", "<")
  1111. .replace("&gt;", ">")
  1112. .replace("&quot;", "\"")
  1113. .replace("&#39;", "'")
  1114. .replace("&nbsp;", " ")
  1115. }
  1116. fn collapse_whitespace(input: &str) -> String {
  1117. input.split_whitespace().collect::<Vec<_>>().join(" ")
  1118. }
  1119. fn preview_text(input: &str, max_chars: usize) -> String {
  1120. if input.chars().count() <= max_chars {
  1121. return input.to_string();
  1122. }
  1123. let shortened = input.chars().take(max_chars).collect::<String>();
  1124. format!("{}…", shortened.trim_end())
  1125. }
  1126. fn extract_search_hits(html: &str) -> Vec<SearchHit> {
  1127. let mut hits = Vec::new();
  1128. let mut remaining = html;
  1129. while let Some(anchor_start) = remaining.find("result__a") {
  1130. let after_class = &remaining[anchor_start..];
  1131. let Some(href_idx) = after_class.find("href=") else {
  1132. remaining = &after_class[1..];
  1133. continue;
  1134. };
  1135. let href_slice = &after_class[href_idx + 5..];
  1136. let Some((url, rest)) = extract_quoted_value(href_slice) else {
  1137. remaining = &after_class[1..];
  1138. continue;
  1139. };
  1140. let Some(close_tag_idx) = rest.find('>') else {
  1141. remaining = &after_class[1..];
  1142. continue;
  1143. };
  1144. let after_tag = &rest[close_tag_idx + 1..];
  1145. let Some(end_anchor_idx) = after_tag.find("</a>") else {
  1146. remaining = &after_tag[1..];
  1147. continue;
  1148. };
  1149. let title = html_to_text(&after_tag[..end_anchor_idx]);
  1150. if let Some(decoded_url) = decode_duckduckgo_redirect(&url) {
  1151. hits.push(SearchHit {
  1152. title: title.trim().to_string(),
  1153. url: decoded_url,
  1154. });
  1155. }
  1156. remaining = &after_tag[end_anchor_idx + 4..];
  1157. }
  1158. hits
  1159. }
  1160. fn extract_search_hits_from_generic_links(html: &str) -> Vec<SearchHit> {
  1161. let mut hits = Vec::new();
  1162. let mut remaining = html;
  1163. while let Some(anchor_start) = remaining.find("<a") {
  1164. let after_anchor = &remaining[anchor_start..];
  1165. let Some(href_idx) = after_anchor.find("href=") else {
  1166. remaining = &after_anchor[2..];
  1167. continue;
  1168. };
  1169. let href_slice = &after_anchor[href_idx + 5..];
  1170. let Some((url, rest)) = extract_quoted_value(href_slice) else {
  1171. remaining = &after_anchor[2..];
  1172. continue;
  1173. };
  1174. let Some(close_tag_idx) = rest.find('>') else {
  1175. remaining = &after_anchor[2..];
  1176. continue;
  1177. };
  1178. let after_tag = &rest[close_tag_idx + 1..];
  1179. let Some(end_anchor_idx) = after_tag.find("</a>") else {
  1180. remaining = &after_anchor[2..];
  1181. continue;
  1182. };
  1183. let title = html_to_text(&after_tag[..end_anchor_idx]);
  1184. if title.trim().is_empty() {
  1185. remaining = &after_tag[end_anchor_idx + 4..];
  1186. continue;
  1187. }
  1188. let decoded_url = decode_duckduckgo_redirect(&url).unwrap_or(url);
  1189. if decoded_url.starts_with("http://") || decoded_url.starts_with("https://") {
  1190. hits.push(SearchHit {
  1191. title: title.trim().to_string(),
  1192. url: decoded_url,
  1193. });
  1194. }
  1195. remaining = &after_tag[end_anchor_idx + 4..];
  1196. }
  1197. hits
  1198. }
  1199. fn extract_quoted_value(input: &str) -> Option<(String, &str)> {
  1200. let quote = input.chars().next()?;
  1201. if quote != '"' && quote != '\'' {
  1202. return None;
  1203. }
  1204. let rest = &input[quote.len_utf8()..];
  1205. let end = rest.find(quote)?;
  1206. Some((rest[..end].to_string(), &rest[end + quote.len_utf8()..]))
  1207. }
  1208. fn decode_duckduckgo_redirect(url: &str) -> Option<String> {
  1209. if url.starts_with("http://") || url.starts_with("https://") {
  1210. return Some(html_entity_decode_url(url));
  1211. }
  1212. let joined = if url.starts_with("//") {
  1213. format!("https:{url}")
  1214. } else if url.starts_with('/') {
  1215. format!("https://duckduckgo.com{url}")
  1216. } else {
  1217. return None;
  1218. };
  1219. let parsed = reqwest::Url::parse(&joined).ok()?;
  1220. if parsed.path() == "/l/" || parsed.path() == "/l" {
  1221. for (key, value) in parsed.query_pairs() {
  1222. if key == "uddg" {
  1223. return Some(html_entity_decode_url(value.as_ref()));
  1224. }
  1225. }
  1226. }
  1227. Some(joined)
  1228. }
  1229. fn html_entity_decode_url(url: &str) -> String {
  1230. decode_html_entities(url)
  1231. }
  1232. fn host_matches_list(url: &str, domains: &[String]) -> bool {
  1233. let Ok(parsed) = reqwest::Url::parse(url) else {
  1234. return false;
  1235. };
  1236. let Some(host) = parsed.host_str() else {
  1237. return false;
  1238. };
  1239. let host = host.to_ascii_lowercase();
  1240. domains.iter().any(|domain| {
  1241. let normalized = normalize_domain_filter(domain);
  1242. !normalized.is_empty() && (host == normalized || host.ends_with(&format!(".{normalized}")))
  1243. })
  1244. }
  1245. fn normalize_domain_filter(domain: &str) -> String {
  1246. let trimmed = domain.trim();
  1247. let candidate = reqwest::Url::parse(trimmed)
  1248. .ok()
  1249. .and_then(|url| url.host_str().map(str::to_string))
  1250. .unwrap_or_else(|| trimmed.to_string());
  1251. candidate
  1252. .trim()
  1253. .trim_start_matches('.')
  1254. .trim_end_matches('/')
  1255. .to_ascii_lowercase()
  1256. }
  1257. fn dedupe_hits(hits: &mut Vec<SearchHit>) {
  1258. let mut seen = BTreeSet::new();
  1259. hits.retain(|hit| seen.insert(hit.url.clone()));
  1260. }
  1261. fn execute_todo_write(input: TodoWriteInput) -> Result<TodoWriteOutput, String> {
  1262. validate_todos(&input.todos)?;
  1263. let store_path = todo_store_path()?;
  1264. let old_todos = if store_path.exists() {
  1265. serde_json::from_str::<Vec<TodoItem>>(
  1266. &std::fs::read_to_string(&store_path).map_err(|error| error.to_string())?,
  1267. )
  1268. .map_err(|error| error.to_string())?
  1269. } else {
  1270. Vec::new()
  1271. };
  1272. let all_done = input
  1273. .todos
  1274. .iter()
  1275. .all(|todo| matches!(todo.status, TodoStatus::Completed));
  1276. let persisted = if all_done {
  1277. Vec::new()
  1278. } else {
  1279. input.todos.clone()
  1280. };
  1281. if let Some(parent) = store_path.parent() {
  1282. std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
  1283. }
  1284. std::fs::write(
  1285. &store_path,
  1286. serde_json::to_string_pretty(&persisted).map_err(|error| error.to_string())?,
  1287. )
  1288. .map_err(|error| error.to_string())?;
  1289. let verification_nudge_needed = (all_done
  1290. && input.todos.len() >= 3
  1291. && !input
  1292. .todos
  1293. .iter()
  1294. .any(|todo| todo.content.to_lowercase().contains("verif")))
  1295. .then_some(true);
  1296. Ok(TodoWriteOutput {
  1297. old_todos,
  1298. new_todos: input.todos,
  1299. verification_nudge_needed,
  1300. })
  1301. }
  1302. fn execute_skill(input: SkillInput) -> Result<SkillOutput, String> {
  1303. let skill_path = resolve_skill_path(&input.skill)?;
  1304. let prompt = std::fs::read_to_string(&skill_path).map_err(|error| error.to_string())?;
  1305. let description = parse_skill_description(&prompt);
  1306. Ok(SkillOutput {
  1307. skill: input.skill,
  1308. path: skill_path.display().to_string(),
  1309. args: input.args,
  1310. description,
  1311. prompt,
  1312. })
  1313. }
  1314. fn validate_todos(todos: &[TodoItem]) -> Result<(), String> {
  1315. if todos.is_empty() {
  1316. return Err(String::from("todos must not be empty"));
  1317. }
  1318. // Allow multiple in_progress items for parallel workflows
  1319. if todos.iter().any(|todo| todo.content.trim().is_empty()) {
  1320. return Err(String::from("todo content must not be empty"));
  1321. }
  1322. if todos.iter().any(|todo| todo.active_form.trim().is_empty()) {
  1323. return Err(String::from("todo activeForm must not be empty"));
  1324. }
  1325. Ok(())
  1326. }
  1327. fn todo_store_path() -> Result<std::path::PathBuf, String> {
  1328. if let Ok(path) = std::env::var("CLAWD_TODO_STORE") {
  1329. return Ok(std::path::PathBuf::from(path));
  1330. }
  1331. let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
  1332. Ok(cwd.join(".clawd-todos.json"))
  1333. }
  1334. fn resolve_skill_path(skill: &str) -> Result<std::path::PathBuf, String> {
  1335. let requested = skill.trim().trim_start_matches('/').trim_start_matches('$');
  1336. if requested.is_empty() {
  1337. return Err(String::from("skill must not be empty"));
  1338. }
  1339. let mut candidates = Vec::new();
  1340. if let Ok(codex_home) = std::env::var("CODEX_HOME") {
  1341. candidates.push(std::path::PathBuf::from(codex_home).join("skills"));
  1342. }
  1343. if let Ok(home) = std::env::var("HOME") {
  1344. let home = std::path::PathBuf::from(home);
  1345. candidates.push(home.join(".agents").join("skills"));
  1346. candidates.push(home.join(".config").join("opencode").join("skills"));
  1347. candidates.push(home.join(".codex").join("skills"));
  1348. }
  1349. candidates.push(std::path::PathBuf::from("/home/bellman/.codex/skills"));
  1350. for root in candidates {
  1351. let direct = root.join(requested).join("SKILL.md");
  1352. if direct.exists() {
  1353. return Ok(direct);
  1354. }
  1355. if let Ok(entries) = std::fs::read_dir(&root) {
  1356. for entry in entries.flatten() {
  1357. let path = entry.path().join("SKILL.md");
  1358. if !path.exists() {
  1359. continue;
  1360. }
  1361. if entry
  1362. .file_name()
  1363. .to_string_lossy()
  1364. .eq_ignore_ascii_case(requested)
  1365. {
  1366. return Ok(path);
  1367. }
  1368. }
  1369. }
  1370. }
  1371. Err(format!("unknown skill: {requested}"))
  1372. }
  1373. const DEFAULT_AGENT_MODEL: &str = "claude-opus-4-6";
  1374. const DEFAULT_AGENT_SYSTEM_DATE: &str = "2026-03-31";
  1375. const DEFAULT_AGENT_MAX_ITERATIONS: usize = 32;
  1376. fn execute_agent(input: AgentInput) -> Result<AgentOutput, String> {
  1377. execute_agent_with_spawn(input, spawn_agent_job)
  1378. }
  1379. fn execute_agent_with_spawn<F>(input: AgentInput, spawn_fn: F) -> Result<AgentOutput, String>
  1380. where
  1381. F: FnOnce(AgentJob) -> Result<(), String>,
  1382. {
  1383. if input.description.trim().is_empty() {
  1384. return Err(String::from("description must not be empty"));
  1385. }
  1386. if input.prompt.trim().is_empty() {
  1387. return Err(String::from("prompt must not be empty"));
  1388. }
  1389. let agent_id = make_agent_id();
  1390. let output_dir = agent_store_dir()?;
  1391. std::fs::create_dir_all(&output_dir).map_err(|error| error.to_string())?;
  1392. let output_file = output_dir.join(format!("{agent_id}.md"));
  1393. let manifest_file = output_dir.join(format!("{agent_id}.json"));
  1394. let normalized_subagent_type = normalize_subagent_type(input.subagent_type.as_deref());
  1395. let model = resolve_agent_model(input.model.as_deref());
  1396. let agent_name = input
  1397. .name
  1398. .as_deref()
  1399. .map(slugify_agent_name)
  1400. .filter(|name| !name.is_empty())
  1401. .unwrap_or_else(|| slugify_agent_name(&input.description));
  1402. let created_at = iso8601_now();
  1403. let system_prompt = build_agent_system_prompt(&normalized_subagent_type)?;
  1404. let allowed_tools = allowed_tools_for_subagent(&normalized_subagent_type);
  1405. let output_contents = format!(
  1406. "# Agent Task
  1407. - id: {}
  1408. - name: {}
  1409. - description: {}
  1410. - subagent_type: {}
  1411. - created_at: {}
  1412. ## Prompt
  1413. {}
  1414. ",
  1415. agent_id, agent_name, input.description, normalized_subagent_type, created_at, input.prompt
  1416. );
  1417. std::fs::write(&output_file, output_contents).map_err(|error| error.to_string())?;
  1418. let manifest = AgentOutput {
  1419. agent_id,
  1420. name: agent_name,
  1421. description: input.description,
  1422. subagent_type: Some(normalized_subagent_type),
  1423. model: Some(model),
  1424. status: String::from("running"),
  1425. output_file: output_file.display().to_string(),
  1426. manifest_file: manifest_file.display().to_string(),
  1427. created_at: created_at.clone(),
  1428. started_at: Some(created_at),
  1429. completed_at: None,
  1430. error: None,
  1431. };
  1432. write_agent_manifest(&manifest)?;
  1433. let manifest_for_spawn = manifest.clone();
  1434. let job = AgentJob {
  1435. manifest: manifest_for_spawn,
  1436. prompt: input.prompt,
  1437. system_prompt,
  1438. allowed_tools,
  1439. };
  1440. if let Err(error) = spawn_fn(job) {
  1441. let error = format!("failed to spawn sub-agent: {error}");
  1442. persist_agent_terminal_state(&manifest, "failed", None, Some(error.clone()))?;
  1443. return Err(error);
  1444. }
  1445. Ok(manifest)
  1446. }
  1447. fn spawn_agent_job(job: AgentJob) -> Result<(), String> {
  1448. let thread_name = format!("clawd-agent-{}", job.manifest.agent_id);
  1449. std::thread::Builder::new()
  1450. .name(thread_name)
  1451. .spawn(move || {
  1452. let result =
  1453. std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run_agent_job(&job)));
  1454. match result {
  1455. Ok(Ok(())) => {}
  1456. Ok(Err(error)) => {
  1457. let _ =
  1458. persist_agent_terminal_state(&job.manifest, "failed", None, Some(error));
  1459. }
  1460. Err(_) => {
  1461. let _ = persist_agent_terminal_state(
  1462. &job.manifest,
  1463. "failed",
  1464. None,
  1465. Some(String::from("sub-agent thread panicked")),
  1466. );
  1467. }
  1468. }
  1469. })
  1470. .map(|_| ())
  1471. .map_err(|error| error.to_string())
  1472. }
  1473. fn run_agent_job(job: &AgentJob) -> Result<(), String> {
  1474. let mut runtime = build_agent_runtime(job)?.with_max_iterations(DEFAULT_AGENT_MAX_ITERATIONS);
  1475. let summary = runtime
  1476. .run_turn(job.prompt.clone(), None)
  1477. .map_err(|error| error.to_string())?;
  1478. let final_text = final_assistant_text(&summary);
  1479. persist_agent_terminal_state(&job.manifest, "completed", Some(final_text.as_str()), None)
  1480. }
  1481. fn build_agent_runtime(
  1482. job: &AgentJob,
  1483. ) -> Result<ConversationRuntime<ProviderRuntimeClient, SubagentToolExecutor>, String> {
  1484. let model = job
  1485. .manifest
  1486. .model
  1487. .clone()
  1488. .unwrap_or_else(|| DEFAULT_AGENT_MODEL.to_string());
  1489. let allowed_tools = job.allowed_tools.clone();
  1490. let api_client = ProviderRuntimeClient::new(model, allowed_tools.clone())?;
  1491. let tool_executor = SubagentToolExecutor::new(allowed_tools);
  1492. Ok(ConversationRuntime::new(
  1493. Session::new(),
  1494. api_client,
  1495. tool_executor,
  1496. agent_permission_policy(),
  1497. job.system_prompt.clone(),
  1498. ))
  1499. }
  1500. fn build_agent_system_prompt(subagent_type: &str) -> Result<Vec<String>, String> {
  1501. let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
  1502. let mut prompt = load_system_prompt(
  1503. cwd,
  1504. DEFAULT_AGENT_SYSTEM_DATE.to_string(),
  1505. std::env::consts::OS,
  1506. "unknown",
  1507. )
  1508. .map_err(|error| error.to_string())?;
  1509. prompt.push(format!(
  1510. "You are a background sub-agent of type `{subagent_type}`. Work only on the delegated task, use only the tools available to you, do not ask the user questions, and finish with a concise result."
  1511. ));
  1512. Ok(prompt)
  1513. }
  1514. fn resolve_agent_model(model: Option<&str>) -> String {
  1515. model
  1516. .map(str::trim)
  1517. .filter(|model| !model.is_empty())
  1518. .unwrap_or(DEFAULT_AGENT_MODEL)
  1519. .to_string()
  1520. }
  1521. fn allowed_tools_for_subagent(subagent_type: &str) -> BTreeSet<String> {
  1522. let tools = match subagent_type {
  1523. "Explore" => vec![
  1524. "read_file",
  1525. "glob_search",
  1526. "grep_search",
  1527. "WebFetch",
  1528. "WebSearch",
  1529. "ToolSearch",
  1530. "Skill",
  1531. "StructuredOutput",
  1532. ],
  1533. "Plan" => vec![
  1534. "read_file",
  1535. "glob_search",
  1536. "grep_search",
  1537. "WebFetch",
  1538. "WebSearch",
  1539. "ToolSearch",
  1540. "Skill",
  1541. "TodoWrite",
  1542. "StructuredOutput",
  1543. "SendUserMessage",
  1544. ],
  1545. "Verification" => vec![
  1546. "bash",
  1547. "read_file",
  1548. "glob_search",
  1549. "grep_search",
  1550. "WebFetch",
  1551. "WebSearch",
  1552. "ToolSearch",
  1553. "TodoWrite",
  1554. "StructuredOutput",
  1555. "SendUserMessage",
  1556. "PowerShell",
  1557. ],
  1558. "claw-guide" => vec![
  1559. "read_file",
  1560. "glob_search",
  1561. "grep_search",
  1562. "WebFetch",
  1563. "WebSearch",
  1564. "ToolSearch",
  1565. "Skill",
  1566. "StructuredOutput",
  1567. "SendUserMessage",
  1568. ],
  1569. "statusline-setup" => vec![
  1570. "bash",
  1571. "read_file",
  1572. "write_file",
  1573. "edit_file",
  1574. "glob_search",
  1575. "grep_search",
  1576. "ToolSearch",
  1577. ],
  1578. _ => vec![
  1579. "bash",
  1580. "read_file",
  1581. "write_file",
  1582. "edit_file",
  1583. "glob_search",
  1584. "grep_search",
  1585. "WebFetch",
  1586. "WebSearch",
  1587. "TodoWrite",
  1588. "Skill",
  1589. "ToolSearch",
  1590. "NotebookEdit",
  1591. "Sleep",
  1592. "SendUserMessage",
  1593. "Config",
  1594. "StructuredOutput",
  1595. "REPL",
  1596. "PowerShell",
  1597. ],
  1598. };
  1599. tools.into_iter().map(str::to_string).collect()
  1600. }
  1601. fn agent_permission_policy() -> PermissionPolicy {
  1602. mvp_tool_specs().into_iter().fold(
  1603. PermissionPolicy::new(PermissionMode::DangerFullAccess),
  1604. |policy, spec| policy.with_tool_requirement(spec.name, spec.required_permission),
  1605. )
  1606. }
  1607. fn write_agent_manifest(manifest: &AgentOutput) -> Result<(), String> {
  1608. std::fs::write(
  1609. &manifest.manifest_file,
  1610. serde_json::to_string_pretty(manifest).map_err(|error| error.to_string())?,
  1611. )
  1612. .map_err(|error| error.to_string())
  1613. }
  1614. fn persist_agent_terminal_state(
  1615. manifest: &AgentOutput,
  1616. status: &str,
  1617. result: Option<&str>,
  1618. error: Option<String>,
  1619. ) -> Result<(), String> {
  1620. append_agent_output(
  1621. &manifest.output_file,
  1622. &format_agent_terminal_output(status, result, error.as_deref()),
  1623. )?;
  1624. let mut next_manifest = manifest.clone();
  1625. next_manifest.status = status.to_string();
  1626. next_manifest.completed_at = Some(iso8601_now());
  1627. next_manifest.error = error;
  1628. write_agent_manifest(&next_manifest)
  1629. }
  1630. fn append_agent_output(path: &str, suffix: &str) -> Result<(), String> {
  1631. use std::io::Write as _;
  1632. let mut file = std::fs::OpenOptions::new()
  1633. .append(true)
  1634. .open(path)
  1635. .map_err(|error| error.to_string())?;
  1636. file.write_all(suffix.as_bytes())
  1637. .map_err(|error| error.to_string())
  1638. }
  1639. fn format_agent_terminal_output(status: &str, result: Option<&str>, error: Option<&str>) -> String {
  1640. let mut sections = vec![format!("\n## Result\n\n- status: {status}\n")];
  1641. if let Some(result) = result.filter(|value| !value.trim().is_empty()) {
  1642. sections.push(format!("\n### Final response\n\n{}\n", result.trim()));
  1643. }
  1644. if let Some(error) = error.filter(|value| !value.trim().is_empty()) {
  1645. sections.push(format!("\n### Error\n\n{}\n", error.trim()));
  1646. }
  1647. sections.join("")
  1648. }
  1649. struct ProviderRuntimeClient {
  1650. runtime: tokio::runtime::Runtime,
  1651. client: ProviderClient,
  1652. model: String,
  1653. allowed_tools: BTreeSet<String>,
  1654. }
  1655. impl ProviderRuntimeClient {
  1656. #[allow(clippy::needless_pass_by_value)]
  1657. fn new(model: String, allowed_tools: BTreeSet<String>) -> Result<Self, String> {
  1658. let model = resolve_model_alias(&model).clone();
  1659. let client = ProviderClient::from_model(&model).map_err(|error| error.to_string())?;
  1660. Ok(Self {
  1661. runtime: tokio::runtime::Runtime::new().map_err(|error| error.to_string())?,
  1662. client,
  1663. model,
  1664. allowed_tools,
  1665. })
  1666. }
  1667. }
  1668. impl ApiClient for ProviderRuntimeClient {
  1669. #[allow(clippy::too_many_lines)]
  1670. fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
  1671. let tools = tool_specs_for_allowed_tools(Some(&self.allowed_tools))
  1672. .into_iter()
  1673. .map(|spec| ToolDefinition {
  1674. name: spec.name.to_string(),
  1675. description: Some(spec.description.to_string()),
  1676. input_schema: spec.input_schema,
  1677. })
  1678. .collect::<Vec<_>>();
  1679. let message_request = MessageRequest {
  1680. model: self.model.clone(),
  1681. max_tokens: max_tokens_for_model(&self.model),
  1682. messages: convert_messages(&request.messages),
  1683. system: (!request.system_prompt.is_empty()).then(|| request.system_prompt.join("\n\n")),
  1684. tools: (!tools.is_empty()).then_some(tools),
  1685. tool_choice: (!self.allowed_tools.is_empty()).then_some(ToolChoice::Auto),
  1686. stream: true,
  1687. };
  1688. self.runtime.block_on(async {
  1689. let mut stream = self
  1690. .client
  1691. .stream_message(&message_request)
  1692. .await
  1693. .map_err(|error| RuntimeError::new(error.to_string()))?;
  1694. let mut events = Vec::new();
  1695. let mut pending_tools: BTreeMap<u32, (String, String, String)> = BTreeMap::new();
  1696. let mut saw_stop = false;
  1697. while let Some(event) = stream
  1698. .next_event()
  1699. .await
  1700. .map_err(|error| RuntimeError::new(error.to_string()))?
  1701. {
  1702. match event {
  1703. ApiStreamEvent::MessageStart(start) => {
  1704. for block in start.message.content {
  1705. push_output_block(block, 0, &mut events, &mut pending_tools, true);
  1706. }
  1707. }
  1708. ApiStreamEvent::ContentBlockStart(start) => {
  1709. push_output_block(
  1710. start.content_block,
  1711. start.index,
  1712. &mut events,
  1713. &mut pending_tools,
  1714. true,
  1715. );
  1716. }
  1717. ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
  1718. ContentBlockDelta::TextDelta { text } => {
  1719. if !text.is_empty() {
  1720. events.push(AssistantEvent::TextDelta(text));
  1721. }
  1722. }
  1723. ContentBlockDelta::InputJsonDelta { partial_json } => {
  1724. if let Some((_, _, input)) = pending_tools.get_mut(&delta.index) {
  1725. input.push_str(&partial_json);
  1726. }
  1727. }
  1728. ContentBlockDelta::ThinkingDelta { .. }
  1729. | ContentBlockDelta::SignatureDelta { .. } => {}
  1730. },
  1731. ApiStreamEvent::ContentBlockStop(stop) => {
  1732. if let Some((id, name, input)) = pending_tools.remove(&stop.index) {
  1733. events.push(AssistantEvent::ToolUse { id, name, input });
  1734. }
  1735. }
  1736. ApiStreamEvent::MessageDelta(delta) => {
  1737. events.push(AssistantEvent::Usage(delta.usage.token_usage()));
  1738. }
  1739. ApiStreamEvent::MessageStop(_) => {
  1740. saw_stop = true;
  1741. events.push(AssistantEvent::MessageStop);
  1742. }
  1743. }
  1744. }
  1745. push_prompt_cache_record(&self.client, &mut events);
  1746. if !saw_stop
  1747. && events.iter().any(|event| {
  1748. matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty())
  1749. || matches!(event, AssistantEvent::ToolUse { .. })
  1750. })
  1751. {
  1752. events.push(AssistantEvent::MessageStop);
  1753. }
  1754. if events
  1755. .iter()
  1756. .any(|event| matches!(event, AssistantEvent::MessageStop))
  1757. {
  1758. return Ok(events);
  1759. }
  1760. let response = self
  1761. .client
  1762. .send_message(&MessageRequest {
  1763. stream: false,
  1764. ..message_request.clone()
  1765. })
  1766. .await
  1767. .map_err(|error| RuntimeError::new(error.to_string()))?;
  1768. let mut events = response_to_events(response);
  1769. push_prompt_cache_record(&self.client, &mut events);
  1770. Ok(events)
  1771. })
  1772. }
  1773. }
  1774. struct SubagentToolExecutor {
  1775. allowed_tools: BTreeSet<String>,
  1776. }
  1777. impl SubagentToolExecutor {
  1778. fn new(allowed_tools: BTreeSet<String>) -> Self {
  1779. Self { allowed_tools }
  1780. }
  1781. }
  1782. impl ToolExecutor for SubagentToolExecutor {
  1783. fn execute(&mut self, tool_name: &str, input: &str) -> Result<String, ToolError> {
  1784. if !self.allowed_tools.contains(tool_name) {
  1785. return Err(ToolError::new(format!(
  1786. "tool `{tool_name}` is not enabled for this sub-agent"
  1787. )));
  1788. }
  1789. let value = serde_json::from_str(input)
  1790. .map_err(|error| ToolError::new(format!("invalid tool input JSON: {error}")))?;
  1791. execute_tool(tool_name, &value).map_err(ToolError::new)
  1792. }
  1793. }
  1794. fn tool_specs_for_allowed_tools(allowed_tools: Option<&BTreeSet<String>>) -> Vec<ToolSpec> {
  1795. mvp_tool_specs()
  1796. .into_iter()
  1797. .filter(|spec| allowed_tools.is_none_or(|allowed| allowed.contains(spec.name)))
  1798. .collect()
  1799. }
  1800. fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
  1801. messages
  1802. .iter()
  1803. .filter_map(|message| {
  1804. let role = match message.role {
  1805. MessageRole::System | MessageRole::User | MessageRole::Tool => "user",
  1806. MessageRole::Assistant => "assistant",
  1807. };
  1808. let content = message
  1809. .blocks
  1810. .iter()
  1811. .map(|block| match block {
  1812. ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
  1813. ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
  1814. id: id.clone(),
  1815. name: name.clone(),
  1816. input: serde_json::from_str(input)
  1817. .unwrap_or_else(|_| serde_json::json!({ "raw": input })),
  1818. },
  1819. ContentBlock::ToolResult {
  1820. tool_use_id,
  1821. output,
  1822. is_error,
  1823. ..
  1824. } => InputContentBlock::ToolResult {
  1825. tool_use_id: tool_use_id.clone(),
  1826. content: vec![ToolResultContentBlock::Text {
  1827. text: output.clone(),
  1828. }],
  1829. is_error: *is_error,
  1830. },
  1831. })
  1832. .collect::<Vec<_>>();
  1833. (!content.is_empty()).then(|| InputMessage {
  1834. role: role.to_string(),
  1835. content,
  1836. })
  1837. })
  1838. .collect()
  1839. }
  1840. fn push_output_block(
  1841. block: OutputContentBlock,
  1842. block_index: u32,
  1843. events: &mut Vec<AssistantEvent>,
  1844. pending_tools: &mut BTreeMap<u32, (String, String, String)>,
  1845. streaming_tool_input: bool,
  1846. ) {
  1847. match block {
  1848. OutputContentBlock::Text { text } => {
  1849. if !text.is_empty() {
  1850. events.push(AssistantEvent::TextDelta(text));
  1851. }
  1852. }
  1853. OutputContentBlock::ToolUse { id, name, input } => {
  1854. let initial_input = if streaming_tool_input
  1855. && input.is_object()
  1856. && input.as_object().is_some_and(serde_json::Map::is_empty)
  1857. {
  1858. String::new()
  1859. } else {
  1860. input.to_string()
  1861. };
  1862. pending_tools.insert(block_index, (id, name, initial_input));
  1863. }
  1864. OutputContentBlock::Thinking { .. } | OutputContentBlock::RedactedThinking { .. } => {}
  1865. }
  1866. }
  1867. fn response_to_events(response: MessageResponse) -> Vec<AssistantEvent> {
  1868. let mut events = Vec::new();
  1869. let mut pending_tools = BTreeMap::new();
  1870. for (index, block) in response.content.into_iter().enumerate() {
  1871. let index = u32::try_from(index).expect("response block index overflow");
  1872. push_output_block(block, index, &mut events, &mut pending_tools, false);
  1873. if let Some((id, name, input)) = pending_tools.remove(&index) {
  1874. events.push(AssistantEvent::ToolUse { id, name, input });
  1875. }
  1876. }
  1877. events.push(AssistantEvent::Usage(response.usage.token_usage()));
  1878. events.push(AssistantEvent::MessageStop);
  1879. events
  1880. }
  1881. fn push_prompt_cache_record(client: &ProviderClient, events: &mut Vec<AssistantEvent>) {
  1882. if let Some(record) = client.take_last_prompt_cache_record() {
  1883. if let Some(event) = prompt_cache_record_to_runtime_event(record) {
  1884. events.push(AssistantEvent::PromptCache(event));
  1885. }
  1886. }
  1887. }
  1888. fn prompt_cache_record_to_runtime_event(
  1889. record: api::PromptCacheRecord,
  1890. ) -> Option<PromptCacheEvent> {
  1891. let cache_break = record.cache_break?;
  1892. Some(PromptCacheEvent {
  1893. unexpected: cache_break.unexpected,
  1894. reason: cache_break.reason,
  1895. previous_cache_read_input_tokens: cache_break.previous_cache_read_input_tokens,
  1896. current_cache_read_input_tokens: cache_break.current_cache_read_input_tokens,
  1897. token_drop: cache_break.token_drop,
  1898. })
  1899. }
  1900. fn final_assistant_text(summary: &runtime::TurnSummary) -> String {
  1901. summary
  1902. .assistant_messages
  1903. .last()
  1904. .map(|message| {
  1905. message
  1906. .blocks
  1907. .iter()
  1908. .filter_map(|block| match block {
  1909. ContentBlock::Text { text } => Some(text.as_str()),
  1910. _ => None,
  1911. })
  1912. .collect::<Vec<_>>()
  1913. .join("")
  1914. })
  1915. .unwrap_or_default()
  1916. }
  1917. #[allow(clippy::needless_pass_by_value)]
  1918. fn execute_tool_search(input: ToolSearchInput) -> ToolSearchOutput {
  1919. let deferred = deferred_tool_specs();
  1920. let max_results = input.max_results.unwrap_or(5).max(1);
  1921. let query = input.query.trim().to_string();
  1922. let normalized_query = normalize_tool_search_query(&query);
  1923. let matches = search_tool_specs(&query, max_results, &deferred);
  1924. ToolSearchOutput {
  1925. matches,
  1926. query,
  1927. normalized_query,
  1928. total_deferred_tools: deferred.len(),
  1929. pending_mcp_servers: None,
  1930. }
  1931. }
  1932. fn deferred_tool_specs() -> Vec<ToolSpec> {
  1933. mvp_tool_specs()
  1934. .into_iter()
  1935. .filter(|spec| {
  1936. !matches!(
  1937. spec.name,
  1938. "bash" | "read_file" | "write_file" | "edit_file" | "glob_search" | "grep_search"
  1939. )
  1940. })
  1941. .collect()
  1942. }
  1943. fn search_tool_specs(query: &str, max_results: usize, specs: &[ToolSpec]) -> Vec<String> {
  1944. let lowered = query.to_lowercase();
  1945. if let Some(selection) = lowered.strip_prefix("select:") {
  1946. return selection
  1947. .split(',')
  1948. .map(str::trim)
  1949. .filter(|part| !part.is_empty())
  1950. .filter_map(|wanted| {
  1951. let wanted = canonical_tool_token(wanted);
  1952. specs
  1953. .iter()
  1954. .find(|spec| canonical_tool_token(spec.name) == wanted)
  1955. .map(|spec| spec.name.to_string())
  1956. })
  1957. .take(max_results)
  1958. .collect();
  1959. }
  1960. let mut required = Vec::new();
  1961. let mut optional = Vec::new();
  1962. for term in lowered.split_whitespace() {
  1963. if let Some(rest) = term.strip_prefix('+') {
  1964. if !rest.is_empty() {
  1965. required.push(rest);
  1966. }
  1967. } else {
  1968. optional.push(term);
  1969. }
  1970. }
  1971. let terms = if required.is_empty() {
  1972. optional.clone()
  1973. } else {
  1974. required.iter().chain(optional.iter()).copied().collect()
  1975. };
  1976. let mut scored = specs
  1977. .iter()
  1978. .filter_map(|spec| {
  1979. let name = spec.name.to_lowercase();
  1980. let canonical_name = canonical_tool_token(spec.name);
  1981. let normalized_description = normalize_tool_search_query(spec.description);
  1982. let haystack = format!(
  1983. "{name} {} {canonical_name}",
  1984. spec.description.to_lowercase()
  1985. );
  1986. let normalized_haystack = format!("{canonical_name} {normalized_description}");
  1987. if required.iter().any(|term| !haystack.contains(term)) {
  1988. return None;
  1989. }
  1990. let mut score = 0_i32;
  1991. for term in &terms {
  1992. let canonical_term = canonical_tool_token(term);
  1993. if haystack.contains(term) {
  1994. score += 2;
  1995. }
  1996. if name == *term {
  1997. score += 8;
  1998. }
  1999. if name.contains(term) {
  2000. score += 4;
  2001. }
  2002. if canonical_name == canonical_term {
  2003. score += 12;
  2004. }
  2005. if normalized_haystack.contains(&canonical_term) {
  2006. score += 3;
  2007. }
  2008. }
  2009. if score == 0 && !lowered.is_empty() {
  2010. return None;
  2011. }
  2012. Some((score, spec.name.to_string()))
  2013. })
  2014. .collect::<Vec<_>>();
  2015. scored.sort_by(|left, right| right.0.cmp(&left.0).then_with(|| left.1.cmp(&right.1)));
  2016. scored
  2017. .into_iter()
  2018. .map(|(_, name)| name)
  2019. .take(max_results)
  2020. .collect()
  2021. }
  2022. fn normalize_tool_search_query(query: &str) -> String {
  2023. query
  2024. .trim()
  2025. .split(|ch: char| ch.is_whitespace() || ch == ',')
  2026. .filter(|term| !term.is_empty())
  2027. .map(canonical_tool_token)
  2028. .collect::<Vec<_>>()
  2029. .join(" ")
  2030. }
  2031. fn canonical_tool_token(value: &str) -> String {
  2032. let mut canonical = value
  2033. .chars()
  2034. .filter(char::is_ascii_alphanumeric)
  2035. .flat_map(char::to_lowercase)
  2036. .collect::<String>();
  2037. if let Some(stripped) = canonical.strip_suffix("tool") {
  2038. canonical = stripped.to_string();
  2039. }
  2040. canonical
  2041. }
  2042. fn agent_store_dir() -> Result<std::path::PathBuf, String> {
  2043. if let Ok(path) = std::env::var("CLAWD_AGENT_STORE") {
  2044. return Ok(std::path::PathBuf::from(path));
  2045. }
  2046. let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
  2047. if let Some(workspace_root) = cwd.ancestors().nth(2) {
  2048. return Ok(workspace_root.join(".clawd-agents"));
  2049. }
  2050. Ok(cwd.join(".clawd-agents"))
  2051. }
  2052. fn make_agent_id() -> String {
  2053. let nanos = std::time::SystemTime::now()
  2054. .duration_since(std::time::UNIX_EPOCH)
  2055. .unwrap_or_default()
  2056. .as_nanos();
  2057. format!("agent-{nanos}")
  2058. }
  2059. fn slugify_agent_name(description: &str) -> String {
  2060. let mut out = description
  2061. .chars()
  2062. .map(|ch| {
  2063. if ch.is_ascii_alphanumeric() {
  2064. ch.to_ascii_lowercase()
  2065. } else {
  2066. '-'
  2067. }
  2068. })
  2069. .collect::<String>();
  2070. while out.contains("--") {
  2071. out = out.replace("--", "-");
  2072. }
  2073. out.trim_matches('-').chars().take(32).collect()
  2074. }
  2075. fn normalize_subagent_type(subagent_type: Option<&str>) -> String {
  2076. let trimmed = subagent_type.map(str::trim).unwrap_or_default();
  2077. if trimmed.is_empty() {
  2078. return String::from("general-purpose");
  2079. }
  2080. match canonical_tool_token(trimmed).as_str() {
  2081. "general" | "generalpurpose" | "generalpurposeagent" => String::from("general-purpose"),
  2082. "explore" | "explorer" | "exploreagent" => String::from("Explore"),
  2083. "plan" | "planagent" => String::from("Plan"),
  2084. "verification" | "verificationagent" | "verify" | "verifier" => {
  2085. String::from("Verification")
  2086. }
  2087. "clawguide" | "clawguideagent" | "guide" => String::from("claw-guide"),
  2088. "statusline" | "statuslinesetup" => String::from("statusline-setup"),
  2089. _ => trimmed.to_string(),
  2090. }
  2091. }
  2092. fn iso8601_now() -> String {
  2093. std::time::SystemTime::now()
  2094. .duration_since(std::time::UNIX_EPOCH)
  2095. .unwrap_or_default()
  2096. .as_secs()
  2097. .to_string()
  2098. }
  2099. #[allow(clippy::too_many_lines)]
  2100. fn execute_notebook_edit(input: NotebookEditInput) -> Result<NotebookEditOutput, String> {
  2101. let path = std::path::PathBuf::from(&input.notebook_path);
  2102. if path.extension().and_then(|ext| ext.to_str()) != Some("ipynb") {
  2103. return Err(String::from(
  2104. "File must be a Jupyter notebook (.ipynb file).",
  2105. ));
  2106. }
  2107. let original_file = std::fs::read_to_string(&path).map_err(|error| error.to_string())?;
  2108. let mut notebook: serde_json::Value =
  2109. serde_json::from_str(&original_file).map_err(|error| error.to_string())?;
  2110. let language = notebook
  2111. .get("metadata")
  2112. .and_then(|metadata| metadata.get("kernelspec"))
  2113. .and_then(|kernelspec| kernelspec.get("language"))
  2114. .and_then(serde_json::Value::as_str)
  2115. .unwrap_or("python")
  2116. .to_string();
  2117. let cells = notebook
  2118. .get_mut("cells")
  2119. .and_then(serde_json::Value::as_array_mut)
  2120. .ok_or_else(|| String::from("Notebook cells array not found"))?;
  2121. let edit_mode = input.edit_mode.unwrap_or(NotebookEditMode::Replace);
  2122. let target_index = match input.cell_id.as_deref() {
  2123. Some(cell_id) => Some(resolve_cell_index(cells, Some(cell_id), edit_mode)?),
  2124. None if matches!(
  2125. edit_mode,
  2126. NotebookEditMode::Replace | NotebookEditMode::Delete
  2127. ) =>
  2128. {
  2129. Some(resolve_cell_index(cells, None, edit_mode)?)
  2130. }
  2131. None => None,
  2132. };
  2133. let resolved_cell_type = match edit_mode {
  2134. NotebookEditMode::Delete => None,
  2135. NotebookEditMode::Insert => Some(input.cell_type.unwrap_or(NotebookCellType::Code)),
  2136. NotebookEditMode::Replace => Some(input.cell_type.unwrap_or_else(|| {
  2137. target_index
  2138. .and_then(|index| cells.get(index))
  2139. .and_then(cell_kind)
  2140. .unwrap_or(NotebookCellType::Code)
  2141. })),
  2142. };
  2143. let new_source = require_notebook_source(input.new_source, edit_mode)?;
  2144. let cell_id = match edit_mode {
  2145. NotebookEditMode::Insert => {
  2146. let resolved_cell_type = resolved_cell_type.expect("insert cell type");
  2147. let new_id = make_cell_id(cells.len());
  2148. let new_cell = build_notebook_cell(&new_id, resolved_cell_type, &new_source);
  2149. let insert_at = target_index.map_or(cells.len(), |index| index + 1);
  2150. cells.insert(insert_at, new_cell);
  2151. cells
  2152. .get(insert_at)
  2153. .and_then(|cell| cell.get("id"))
  2154. .and_then(serde_json::Value::as_str)
  2155. .map(ToString::to_string)
  2156. }
  2157. NotebookEditMode::Delete => {
  2158. let removed = cells.remove(target_index.expect("delete target index"));
  2159. removed
  2160. .get("id")
  2161. .and_then(serde_json::Value::as_str)
  2162. .map(ToString::to_string)
  2163. }
  2164. NotebookEditMode::Replace => {
  2165. let resolved_cell_type = resolved_cell_type.expect("replace cell type");
  2166. let cell = cells
  2167. .get_mut(target_index.expect("replace target index"))
  2168. .ok_or_else(|| String::from("Cell index out of range"))?;
  2169. cell["source"] = serde_json::Value::Array(source_lines(&new_source));
  2170. cell["cell_type"] = serde_json::Value::String(match resolved_cell_type {
  2171. NotebookCellType::Code => String::from("code"),
  2172. NotebookCellType::Markdown => String::from("markdown"),
  2173. });
  2174. match resolved_cell_type {
  2175. NotebookCellType::Code => {
  2176. if !cell.get("outputs").is_some_and(serde_json::Value::is_array) {
  2177. cell["outputs"] = json!([]);
  2178. }
  2179. if cell.get("execution_count").is_none() {
  2180. cell["execution_count"] = serde_json::Value::Null;
  2181. }
  2182. }
  2183. NotebookCellType::Markdown => {
  2184. if let Some(object) = cell.as_object_mut() {
  2185. object.remove("outputs");
  2186. object.remove("execution_count");
  2187. }
  2188. }
  2189. }
  2190. cell.get("id")
  2191. .and_then(serde_json::Value::as_str)
  2192. .map(ToString::to_string)
  2193. }
  2194. };
  2195. let updated_file =
  2196. serde_json::to_string_pretty(&notebook).map_err(|error| error.to_string())?;
  2197. std::fs::write(&path, &updated_file).map_err(|error| error.to_string())?;
  2198. Ok(NotebookEditOutput {
  2199. new_source,
  2200. cell_id,
  2201. cell_type: resolved_cell_type,
  2202. language,
  2203. edit_mode: format_notebook_edit_mode(edit_mode),
  2204. error: None,
  2205. notebook_path: path.display().to_string(),
  2206. original_file,
  2207. updated_file,
  2208. })
  2209. }
  2210. fn require_notebook_source(
  2211. source: Option<String>,
  2212. edit_mode: NotebookEditMode,
  2213. ) -> Result<String, String> {
  2214. match edit_mode {
  2215. NotebookEditMode::Delete => Ok(source.unwrap_or_default()),
  2216. NotebookEditMode::Insert | NotebookEditMode::Replace => source
  2217. .ok_or_else(|| String::from("new_source is required for insert and replace edits")),
  2218. }
  2219. }
  2220. fn build_notebook_cell(cell_id: &str, cell_type: NotebookCellType, source: &str) -> Value {
  2221. let mut cell = json!({
  2222. "cell_type": match cell_type {
  2223. NotebookCellType::Code => "code",
  2224. NotebookCellType::Markdown => "markdown",
  2225. },
  2226. "id": cell_id,
  2227. "metadata": {},
  2228. "source": source_lines(source),
  2229. });
  2230. if let Some(object) = cell.as_object_mut() {
  2231. match cell_type {
  2232. NotebookCellType::Code => {
  2233. object.insert(String::from("outputs"), json!([]));
  2234. object.insert(String::from("execution_count"), Value::Null);
  2235. }
  2236. NotebookCellType::Markdown => {}
  2237. }
  2238. }
  2239. cell
  2240. }
  2241. fn cell_kind(cell: &serde_json::Value) -> Option<NotebookCellType> {
  2242. cell.get("cell_type")
  2243. .and_then(serde_json::Value::as_str)
  2244. .map(|kind| {
  2245. if kind == "markdown" {
  2246. NotebookCellType::Markdown
  2247. } else {
  2248. NotebookCellType::Code
  2249. }
  2250. })
  2251. }
  2252. #[allow(clippy::needless_pass_by_value)]
  2253. fn execute_sleep(input: SleepInput) -> SleepOutput {
  2254. std::thread::sleep(Duration::from_millis(input.duration_ms));
  2255. SleepOutput {
  2256. duration_ms: input.duration_ms,
  2257. message: format!("Slept for {}ms", input.duration_ms),
  2258. }
  2259. }
  2260. fn execute_brief(input: BriefInput) -> Result<BriefOutput, String> {
  2261. if input.message.trim().is_empty() {
  2262. return Err(String::from("message must not be empty"));
  2263. }
  2264. let attachments = input
  2265. .attachments
  2266. .as_ref()
  2267. .map(|paths| {
  2268. paths
  2269. .iter()
  2270. .map(|path| resolve_attachment(path))
  2271. .collect::<Result<Vec<_>, String>>()
  2272. })
  2273. .transpose()?;
  2274. let message = match input.status {
  2275. BriefStatus::Normal | BriefStatus::Proactive => input.message,
  2276. };
  2277. Ok(BriefOutput {
  2278. message,
  2279. attachments,
  2280. sent_at: iso8601_timestamp(),
  2281. })
  2282. }
  2283. fn resolve_attachment(path: &str) -> Result<ResolvedAttachment, String> {
  2284. let resolved = std::fs::canonicalize(path).map_err(|error| error.to_string())?;
  2285. let metadata = std::fs::metadata(&resolved).map_err(|error| error.to_string())?;
  2286. Ok(ResolvedAttachment {
  2287. path: resolved.display().to_string(),
  2288. size: metadata.len(),
  2289. is_image: is_image_path(&resolved),
  2290. })
  2291. }
  2292. fn is_image_path(path: &Path) -> bool {
  2293. matches!(
  2294. path.extension()
  2295. .and_then(|ext| ext.to_str())
  2296. .map(str::to_ascii_lowercase)
  2297. .as_deref(),
  2298. Some("png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "svg")
  2299. )
  2300. }
  2301. fn execute_config(input: ConfigInput) -> Result<ConfigOutput, String> {
  2302. let setting = input.setting.trim();
  2303. if setting.is_empty() {
  2304. return Err(String::from("setting must not be empty"));
  2305. }
  2306. let Some(spec) = supported_config_setting(setting) else {
  2307. return Ok(ConfigOutput {
  2308. success: false,
  2309. operation: None,
  2310. setting: None,
  2311. value: None,
  2312. previous_value: None,
  2313. new_value: None,
  2314. error: Some(format!("Unknown setting: \"{setting}\"")),
  2315. });
  2316. };
  2317. let path = config_file_for_scope(spec.scope)?;
  2318. let mut document = read_json_object(&path)?;
  2319. if let Some(value) = input.value {
  2320. let normalized = normalize_config_value(spec, value)?;
  2321. let previous_value = get_nested_value(&document, spec.path).cloned();
  2322. set_nested_value(&mut document, spec.path, normalized.clone());
  2323. write_json_object(&path, &document)?;
  2324. Ok(ConfigOutput {
  2325. success: true,
  2326. operation: Some(String::from("set")),
  2327. setting: Some(setting.to_string()),
  2328. value: Some(normalized.clone()),
  2329. previous_value,
  2330. new_value: Some(normalized),
  2331. error: None,
  2332. })
  2333. } else {
  2334. Ok(ConfigOutput {
  2335. success: true,
  2336. operation: Some(String::from("get")),
  2337. setting: Some(setting.to_string()),
  2338. value: get_nested_value(&document, spec.path).cloned(),
  2339. previous_value: None,
  2340. new_value: None,
  2341. error: None,
  2342. })
  2343. }
  2344. }
  2345. fn execute_structured_output(input: StructuredOutputInput) -> StructuredOutputResult {
  2346. StructuredOutputResult {
  2347. data: String::from("Structured output provided successfully"),
  2348. structured_output: input.0,
  2349. }
  2350. }
  2351. fn execute_repl(input: ReplInput) -> Result<ReplOutput, String> {
  2352. if input.code.trim().is_empty() {
  2353. return Err(String::from("code must not be empty"));
  2354. }
  2355. let _ = input.timeout_ms;
  2356. let runtime = resolve_repl_runtime(&input.language)?;
  2357. let started = Instant::now();
  2358. let output = Command::new(runtime.program)
  2359. .args(runtime.args)
  2360. .arg(&input.code)
  2361. .output()
  2362. .map_err(|error| error.to_string())?;
  2363. Ok(ReplOutput {
  2364. language: input.language,
  2365. stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
  2366. stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
  2367. exit_code: output.status.code().unwrap_or(1),
  2368. duration_ms: started.elapsed().as_millis(),
  2369. })
  2370. }
  2371. struct ReplRuntime {
  2372. program: &'static str,
  2373. args: &'static [&'static str],
  2374. }
  2375. fn resolve_repl_runtime(language: &str) -> Result<ReplRuntime, String> {
  2376. match language.trim().to_ascii_lowercase().as_str() {
  2377. "python" | "py" => Ok(ReplRuntime {
  2378. program: detect_first_command(&["python3", "python"])
  2379. .ok_or_else(|| String::from("python runtime not found"))?,
  2380. args: &["-c"],
  2381. }),
  2382. "javascript" | "js" | "node" => Ok(ReplRuntime {
  2383. program: detect_first_command(&["node"])
  2384. .ok_or_else(|| String::from("node runtime not found"))?,
  2385. args: &["-e"],
  2386. }),
  2387. "sh" | "shell" | "bash" => Ok(ReplRuntime {
  2388. program: detect_first_command(&["bash", "sh"])
  2389. .ok_or_else(|| String::from("shell runtime not found"))?,
  2390. args: &["-lc"],
  2391. }),
  2392. other => Err(format!("unsupported REPL language: {other}")),
  2393. }
  2394. }
  2395. fn detect_first_command(commands: &[&'static str]) -> Option<&'static str> {
  2396. commands
  2397. .iter()
  2398. .copied()
  2399. .find(|command| command_exists(command))
  2400. }
  2401. #[derive(Clone, Copy)]
  2402. enum ConfigScope {
  2403. Global,
  2404. Settings,
  2405. }
  2406. #[derive(Clone, Copy)]
  2407. struct ConfigSettingSpec {
  2408. scope: ConfigScope,
  2409. kind: ConfigKind,
  2410. path: &'static [&'static str],
  2411. options: Option<&'static [&'static str]>,
  2412. }
  2413. #[derive(Clone, Copy)]
  2414. enum ConfigKind {
  2415. Boolean,
  2416. String,
  2417. }
  2418. fn supported_config_setting(setting: &str) -> Option<ConfigSettingSpec> {
  2419. Some(match setting {
  2420. "theme" => ConfigSettingSpec {
  2421. scope: ConfigScope::Global,
  2422. kind: ConfigKind::String,
  2423. path: &["theme"],
  2424. options: None,
  2425. },
  2426. "editorMode" => ConfigSettingSpec {
  2427. scope: ConfigScope::Global,
  2428. kind: ConfigKind::String,
  2429. path: &["editorMode"],
  2430. options: Some(&["default", "vim", "emacs"]),
  2431. },
  2432. "verbose" => ConfigSettingSpec {
  2433. scope: ConfigScope::Global,
  2434. kind: ConfigKind::Boolean,
  2435. path: &["verbose"],
  2436. options: None,
  2437. },
  2438. "preferredNotifChannel" => ConfigSettingSpec {
  2439. scope: ConfigScope::Global,
  2440. kind: ConfigKind::String,
  2441. path: &["preferredNotifChannel"],
  2442. options: None,
  2443. },
  2444. "autoCompactEnabled" => ConfigSettingSpec {
  2445. scope: ConfigScope::Global,
  2446. kind: ConfigKind::Boolean,
  2447. path: &["autoCompactEnabled"],
  2448. options: None,
  2449. },
  2450. "autoMemoryEnabled" => ConfigSettingSpec {
  2451. scope: ConfigScope::Settings,
  2452. kind: ConfigKind::Boolean,
  2453. path: &["autoMemoryEnabled"],
  2454. options: None,
  2455. },
  2456. "autoDreamEnabled" => ConfigSettingSpec {
  2457. scope: ConfigScope::Settings,
  2458. kind: ConfigKind::Boolean,
  2459. path: &["autoDreamEnabled"],
  2460. options: None,
  2461. },
  2462. "fileCheckpointingEnabled" => ConfigSettingSpec {
  2463. scope: ConfigScope::Global,
  2464. kind: ConfigKind::Boolean,
  2465. path: &["fileCheckpointingEnabled"],
  2466. options: None,
  2467. },
  2468. "showTurnDuration" => ConfigSettingSpec {
  2469. scope: ConfigScope::Global,
  2470. kind: ConfigKind::Boolean,
  2471. path: &["showTurnDuration"],
  2472. options: None,
  2473. },
  2474. "terminalProgressBarEnabled" => ConfigSettingSpec {
  2475. scope: ConfigScope::Global,
  2476. kind: ConfigKind::Boolean,
  2477. path: &["terminalProgressBarEnabled"],
  2478. options: None,
  2479. },
  2480. "todoFeatureEnabled" => ConfigSettingSpec {
  2481. scope: ConfigScope::Global,
  2482. kind: ConfigKind::Boolean,
  2483. path: &["todoFeatureEnabled"],
  2484. options: None,
  2485. },
  2486. "model" => ConfigSettingSpec {
  2487. scope: ConfigScope::Settings,
  2488. kind: ConfigKind::String,
  2489. path: &["model"],
  2490. options: None,
  2491. },
  2492. "alwaysThinkingEnabled" => ConfigSettingSpec {
  2493. scope: ConfigScope::Settings,
  2494. kind: ConfigKind::Boolean,
  2495. path: &["alwaysThinkingEnabled"],
  2496. options: None,
  2497. },
  2498. "permissions.defaultMode" => ConfigSettingSpec {
  2499. scope: ConfigScope::Settings,
  2500. kind: ConfigKind::String,
  2501. path: &["permissions", "defaultMode"],
  2502. options: Some(&["default", "plan", "acceptEdits", "dontAsk", "auto"]),
  2503. },
  2504. "language" => ConfigSettingSpec {
  2505. scope: ConfigScope::Settings,
  2506. kind: ConfigKind::String,
  2507. path: &["language"],
  2508. options: None,
  2509. },
  2510. "teammateMode" => ConfigSettingSpec {
  2511. scope: ConfigScope::Global,
  2512. kind: ConfigKind::String,
  2513. path: &["teammateMode"],
  2514. options: Some(&["tmux", "in-process", "auto"]),
  2515. },
  2516. _ => return None,
  2517. })
  2518. }
  2519. fn normalize_config_value(spec: ConfigSettingSpec, value: ConfigValue) -> Result<Value, String> {
  2520. let normalized = match (spec.kind, value) {
  2521. (ConfigKind::Boolean, ConfigValue::Bool(value)) => Value::Bool(value),
  2522. (ConfigKind::Boolean, ConfigValue::String(value)) => {
  2523. match value.trim().to_ascii_lowercase().as_str() {
  2524. "true" => Value::Bool(true),
  2525. "false" => Value::Bool(false),
  2526. _ => return Err(String::from("setting requires true or false")),
  2527. }
  2528. }
  2529. (ConfigKind::Boolean, ConfigValue::Number(_)) => {
  2530. return Err(String::from("setting requires true or false"))
  2531. }
  2532. (ConfigKind::String, ConfigValue::String(value)) => Value::String(value),
  2533. (ConfigKind::String, ConfigValue::Bool(value)) => Value::String(value.to_string()),
  2534. (ConfigKind::String, ConfigValue::Number(value)) => json!(value),
  2535. };
  2536. if let Some(options) = spec.options {
  2537. let Some(as_str) = normalized.as_str() else {
  2538. return Err(String::from("setting requires a string value"));
  2539. };
  2540. if !options.iter().any(|option| option == &as_str) {
  2541. return Err(format!(
  2542. "Invalid value \"{as_str}\". Options: {}",
  2543. options.join(", ")
  2544. ));
  2545. }
  2546. }
  2547. Ok(normalized)
  2548. }
  2549. fn config_file_for_scope(scope: ConfigScope) -> Result<PathBuf, String> {
  2550. let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
  2551. Ok(match scope {
  2552. ConfigScope::Global => config_home_dir()?.join("settings.json"),
  2553. ConfigScope::Settings => cwd.join(".claw").join("settings.local.json"),
  2554. })
  2555. }
  2556. fn config_home_dir() -> Result<PathBuf, String> {
  2557. if let Ok(path) = std::env::var("CLAW_CONFIG_HOME") {
  2558. return Ok(PathBuf::from(path));
  2559. }
  2560. let home = std::env::var("HOME").map_err(|_| String::from("HOME is not set"))?;
  2561. Ok(PathBuf::from(home).join(".claw"))
  2562. }
  2563. fn read_json_object(path: &Path) -> Result<serde_json::Map<String, Value>, String> {
  2564. match std::fs::read_to_string(path) {
  2565. Ok(contents) => {
  2566. if contents.trim().is_empty() {
  2567. return Ok(serde_json::Map::new());
  2568. }
  2569. serde_json::from_str::<Value>(&contents)
  2570. .map_err(|error| error.to_string())?
  2571. .as_object()
  2572. .cloned()
  2573. .ok_or_else(|| String::from("config file must contain a JSON object"))
  2574. }
  2575. Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(serde_json::Map::new()),
  2576. Err(error) => Err(error.to_string()),
  2577. }
  2578. }
  2579. fn write_json_object(path: &Path, value: &serde_json::Map<String, Value>) -> Result<(), String> {
  2580. if let Some(parent) = path.parent() {
  2581. std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
  2582. }
  2583. std::fs::write(
  2584. path,
  2585. serde_json::to_string_pretty(value).map_err(|error| error.to_string())?,
  2586. )
  2587. .map_err(|error| error.to_string())
  2588. }
  2589. fn get_nested_value<'a>(
  2590. value: &'a serde_json::Map<String, Value>,
  2591. path: &[&str],
  2592. ) -> Option<&'a Value> {
  2593. let (first, rest) = path.split_first()?;
  2594. let mut current = value.get(*first)?;
  2595. for key in rest {
  2596. current = current.as_object()?.get(*key)?;
  2597. }
  2598. Some(current)
  2599. }
  2600. fn set_nested_value(root: &mut serde_json::Map<String, Value>, path: &[&str], new_value: Value) {
  2601. let (first, rest) = path.split_first().expect("config path must not be empty");
  2602. if rest.is_empty() {
  2603. root.insert((*first).to_string(), new_value);
  2604. return;
  2605. }
  2606. let entry = root
  2607. .entry((*first).to_string())
  2608. .or_insert_with(|| Value::Object(serde_json::Map::new()));
  2609. if !entry.is_object() {
  2610. *entry = Value::Object(serde_json::Map::new());
  2611. }
  2612. let map = entry.as_object_mut().expect("object inserted");
  2613. set_nested_value(map, rest, new_value);
  2614. }
  2615. fn iso8601_timestamp() -> String {
  2616. if let Ok(output) = Command::new("date")
  2617. .args(["-u", "+%Y-%m-%dT%H:%M:%SZ"])
  2618. .output()
  2619. {
  2620. if output.status.success() {
  2621. return String::from_utf8_lossy(&output.stdout).trim().to_string();
  2622. }
  2623. }
  2624. iso8601_now()
  2625. }
  2626. #[allow(clippy::needless_pass_by_value)]
  2627. fn execute_powershell(input: PowerShellInput) -> std::io::Result<runtime::BashCommandOutput> {
  2628. let _ = &input.description;
  2629. let shell = detect_powershell_shell()?;
  2630. execute_shell_command(
  2631. shell,
  2632. &input.command,
  2633. input.timeout,
  2634. input.run_in_background,
  2635. )
  2636. }
  2637. fn detect_powershell_shell() -> std::io::Result<&'static str> {
  2638. if command_exists("pwsh") {
  2639. Ok("pwsh")
  2640. } else if command_exists("powershell") {
  2641. Ok("powershell")
  2642. } else {
  2643. Err(std::io::Error::new(
  2644. std::io::ErrorKind::NotFound,
  2645. "PowerShell executable not found (expected `pwsh` or `powershell` in PATH)",
  2646. ))
  2647. }
  2648. }
  2649. fn command_exists(command: &str) -> bool {
  2650. std::process::Command::new("sh")
  2651. .arg("-lc")
  2652. .arg(format!("command -v {command} >/dev/null 2>&1"))
  2653. .status()
  2654. .map(|status| status.success())
  2655. .unwrap_or(false)
  2656. }
  2657. #[allow(clippy::too_many_lines)]
  2658. fn execute_shell_command(
  2659. shell: &str,
  2660. command: &str,
  2661. timeout: Option<u64>,
  2662. run_in_background: Option<bool>,
  2663. ) -> std::io::Result<runtime::BashCommandOutput> {
  2664. if run_in_background.unwrap_or(false) {
  2665. let child = std::process::Command::new(shell)
  2666. .arg("-NoProfile")
  2667. .arg("-NonInteractive")
  2668. .arg("-Command")
  2669. .arg(command)
  2670. .stdin(std::process::Stdio::null())
  2671. .stdout(std::process::Stdio::null())
  2672. .stderr(std::process::Stdio::null())
  2673. .spawn()?;
  2674. return Ok(runtime::BashCommandOutput {
  2675. stdout: String::new(),
  2676. stderr: String::new(),
  2677. raw_output_path: None,
  2678. interrupted: false,
  2679. is_image: None,
  2680. background_task_id: Some(child.id().to_string()),
  2681. backgrounded_by_user: Some(true),
  2682. assistant_auto_backgrounded: Some(false),
  2683. dangerously_disable_sandbox: None,
  2684. return_code_interpretation: None,
  2685. no_output_expected: Some(true),
  2686. structured_content: None,
  2687. persisted_output_path: None,
  2688. persisted_output_size: None,
  2689. sandbox_status: None,
  2690. });
  2691. }
  2692. let mut process = std::process::Command::new(shell);
  2693. process
  2694. .arg("-NoProfile")
  2695. .arg("-NonInteractive")
  2696. .arg("-Command")
  2697. .arg(command);
  2698. process
  2699. .stdout(std::process::Stdio::piped())
  2700. .stderr(std::process::Stdio::piped());
  2701. if let Some(timeout_ms) = timeout {
  2702. let mut child = process.spawn()?;
  2703. let started = Instant::now();
  2704. loop {
  2705. if let Some(status) = child.try_wait()? {
  2706. let output = child.wait_with_output()?;
  2707. return Ok(runtime::BashCommandOutput {
  2708. stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
  2709. stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
  2710. raw_output_path: None,
  2711. interrupted: false,
  2712. is_image: None,
  2713. background_task_id: None,
  2714. backgrounded_by_user: None,
  2715. assistant_auto_backgrounded: None,
  2716. dangerously_disable_sandbox: None,
  2717. return_code_interpretation: status
  2718. .code()
  2719. .filter(|code| *code != 0)
  2720. .map(|code| format!("exit_code:{code}")),
  2721. no_output_expected: Some(output.stdout.is_empty() && output.stderr.is_empty()),
  2722. structured_content: None,
  2723. persisted_output_path: None,
  2724. persisted_output_size: None,
  2725. sandbox_status: None,
  2726. });
  2727. }
  2728. if started.elapsed() >= Duration::from_millis(timeout_ms) {
  2729. let _ = child.kill();
  2730. let output = child.wait_with_output()?;
  2731. let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
  2732. let stderr = if stderr.trim().is_empty() {
  2733. format!("Command exceeded timeout of {timeout_ms} ms")
  2734. } else {
  2735. format!(
  2736. "{}
  2737. Command exceeded timeout of {timeout_ms} ms",
  2738. stderr.trim_end()
  2739. )
  2740. };
  2741. return Ok(runtime::BashCommandOutput {
  2742. stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
  2743. stderr,
  2744. raw_output_path: None,
  2745. interrupted: true,
  2746. is_image: None,
  2747. background_task_id: None,
  2748. backgrounded_by_user: None,
  2749. assistant_auto_backgrounded: None,
  2750. dangerously_disable_sandbox: None,
  2751. return_code_interpretation: Some(String::from("timeout")),
  2752. no_output_expected: Some(false),
  2753. structured_content: None,
  2754. persisted_output_path: None,
  2755. persisted_output_size: None,
  2756. sandbox_status: None,
  2757. });
  2758. }
  2759. std::thread::sleep(Duration::from_millis(10));
  2760. }
  2761. }
  2762. let output = process.output()?;
  2763. Ok(runtime::BashCommandOutput {
  2764. stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
  2765. stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
  2766. raw_output_path: None,
  2767. interrupted: false,
  2768. is_image: None,
  2769. background_task_id: None,
  2770. backgrounded_by_user: None,
  2771. assistant_auto_backgrounded: None,
  2772. dangerously_disable_sandbox: None,
  2773. return_code_interpretation: output
  2774. .status
  2775. .code()
  2776. .filter(|code| *code != 0)
  2777. .map(|code| format!("exit_code:{code}")),
  2778. no_output_expected: Some(output.stdout.is_empty() && output.stderr.is_empty()),
  2779. structured_content: None,
  2780. persisted_output_path: None,
  2781. persisted_output_size: None,
  2782. sandbox_status: None,
  2783. })
  2784. }
  2785. fn resolve_cell_index(
  2786. cells: &[serde_json::Value],
  2787. cell_id: Option<&str>,
  2788. edit_mode: NotebookEditMode,
  2789. ) -> Result<usize, String> {
  2790. if cells.is_empty()
  2791. && matches!(
  2792. edit_mode,
  2793. NotebookEditMode::Replace | NotebookEditMode::Delete
  2794. )
  2795. {
  2796. return Err(String::from("Notebook has no cells to edit"));
  2797. }
  2798. if let Some(cell_id) = cell_id {
  2799. cells
  2800. .iter()
  2801. .position(|cell| cell.get("id").and_then(serde_json::Value::as_str) == Some(cell_id))
  2802. .ok_or_else(|| format!("Cell id not found: {cell_id}"))
  2803. } else {
  2804. Ok(cells.len().saturating_sub(1))
  2805. }
  2806. }
  2807. fn source_lines(source: &str) -> Vec<serde_json::Value> {
  2808. if source.is_empty() {
  2809. return vec![serde_json::Value::String(String::new())];
  2810. }
  2811. source
  2812. .split_inclusive('\n')
  2813. .map(|line| serde_json::Value::String(line.to_string()))
  2814. .collect()
  2815. }
  2816. fn format_notebook_edit_mode(mode: NotebookEditMode) -> String {
  2817. match mode {
  2818. NotebookEditMode::Replace => String::from("replace"),
  2819. NotebookEditMode::Insert => String::from("insert"),
  2820. NotebookEditMode::Delete => String::from("delete"),
  2821. }
  2822. }
  2823. fn make_cell_id(index: usize) -> String {
  2824. format!("cell-{}", index + 1)
  2825. }
  2826. fn parse_skill_description(contents: &str) -> Option<String> {
  2827. for line in contents.lines() {
  2828. if let Some(value) = line.strip_prefix("description:") {
  2829. let trimmed = value.trim();
  2830. if !trimmed.is_empty() {
  2831. return Some(trimmed.to_string());
  2832. }
  2833. }
  2834. }
  2835. None
  2836. }
  2837. #[cfg(test)]
  2838. mod tests {
  2839. use std::collections::BTreeMap;
  2840. use std::collections::BTreeSet;
  2841. use std::fs;
  2842. use std::io::{Read, Write};
  2843. use std::net::{SocketAddr, TcpListener};
  2844. use std::path::PathBuf;
  2845. use std::sync::{Arc, Mutex, OnceLock};
  2846. use std::thread;
  2847. use std::time::Duration;
  2848. use super::{
  2849. agent_permission_policy, allowed_tools_for_subagent, execute_agent_with_spawn,
  2850. execute_tool, final_assistant_text, mvp_tool_specs, permission_mode_from_plugin,
  2851. persist_agent_terminal_state, push_output_block, AgentInput, AgentJob,
  2852. SubagentToolExecutor,
  2853. };
  2854. use api::OutputContentBlock;
  2855. use runtime::{ApiRequest, AssistantEvent, ConversationRuntime, RuntimeError, Session};
  2856. use serde_json::json;
  2857. fn env_lock() -> &'static Mutex<()> {
  2858. static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
  2859. LOCK.get_or_init(|| Mutex::new(()))
  2860. }
  2861. fn temp_path(name: &str) -> PathBuf {
  2862. let unique = std::time::SystemTime::now()
  2863. .duration_since(std::time::UNIX_EPOCH)
  2864. .expect("time")
  2865. .as_nanos();
  2866. std::env::temp_dir().join(format!("clawd-tools-{unique}-{name}"))
  2867. }
  2868. #[test]
  2869. fn exposes_mvp_tools() {
  2870. let names = mvp_tool_specs()
  2871. .into_iter()
  2872. .map(|spec| spec.name)
  2873. .collect::<Vec<_>>();
  2874. assert!(names.contains(&"bash"));
  2875. assert!(names.contains(&"read_file"));
  2876. assert!(names.contains(&"WebFetch"));
  2877. assert!(names.contains(&"WebSearch"));
  2878. assert!(names.contains(&"TodoWrite"));
  2879. assert!(names.contains(&"Skill"));
  2880. assert!(names.contains(&"Agent"));
  2881. assert!(names.contains(&"ToolSearch"));
  2882. assert!(names.contains(&"NotebookEdit"));
  2883. assert!(names.contains(&"Sleep"));
  2884. assert!(names.contains(&"SendUserMessage"));
  2885. assert!(names.contains(&"Config"));
  2886. assert!(names.contains(&"StructuredOutput"));
  2887. assert!(names.contains(&"REPL"));
  2888. assert!(names.contains(&"PowerShell"));
  2889. }
  2890. #[test]
  2891. fn rejects_unknown_tool_names() {
  2892. let error = execute_tool("nope", &json!({})).expect_err("tool should be rejected");
  2893. assert!(error.contains("unsupported tool"));
  2894. }
  2895. #[test]
  2896. fn permission_mode_from_plugin_rejects_invalid_inputs() {
  2897. let unknown_permission = permission_mode_from_plugin("admin")
  2898. .expect_err("unknown plugin permission should fail");
  2899. assert!(unknown_permission.contains("unsupported plugin permission: admin"));
  2900. let empty_permission =
  2901. permission_mode_from_plugin("").expect_err("empty plugin permission should fail");
  2902. assert!(empty_permission.contains("unsupported plugin permission: "));
  2903. }
  2904. #[test]
  2905. fn web_fetch_returns_prompt_aware_summary() {
  2906. let server = TestServer::spawn(Arc::new(|request_line: &str| {
  2907. assert!(request_line.starts_with("GET /page "));
  2908. HttpResponse::html(
  2909. 200,
  2910. "OK",
  2911. "<html><head><title>Ignored</title></head><body><h1>Test Page</h1><p>Hello <b>world</b> from local server.</p></body></html>",
  2912. )
  2913. }));
  2914. let result = execute_tool(
  2915. "WebFetch",
  2916. &json!({
  2917. "url": format!("http://{}/page", server.addr()),
  2918. "prompt": "Summarize this page"
  2919. }),
  2920. )
  2921. .expect("WebFetch should succeed");
  2922. let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
  2923. assert_eq!(output["code"], 200);
  2924. let summary = output["result"].as_str().expect("result string");
  2925. assert!(summary.contains("Fetched"));
  2926. assert!(summary.contains("Test Page"));
  2927. assert!(summary.contains("Hello world from local server"));
  2928. let titled = execute_tool(
  2929. "WebFetch",
  2930. &json!({
  2931. "url": format!("http://{}/page", server.addr()),
  2932. "prompt": "What is the page title?"
  2933. }),
  2934. )
  2935. .expect("WebFetch title query should succeed");
  2936. let titled_output: serde_json::Value = serde_json::from_str(&titled).expect("valid json");
  2937. let titled_summary = titled_output["result"].as_str().expect("result string");
  2938. assert!(titled_summary.contains("Title: Ignored"));
  2939. }
  2940. #[test]
  2941. fn web_fetch_supports_plain_text_and_rejects_invalid_url() {
  2942. let server = TestServer::spawn(Arc::new(|request_line: &str| {
  2943. assert!(request_line.starts_with("GET /plain "));
  2944. HttpResponse::text(200, "OK", "plain text response")
  2945. }));
  2946. let result = execute_tool(
  2947. "WebFetch",
  2948. &json!({
  2949. "url": format!("http://{}/plain", server.addr()),
  2950. "prompt": "Show me the content"
  2951. }),
  2952. )
  2953. .expect("WebFetch should succeed for text content");
  2954. let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
  2955. assert_eq!(output["url"], format!("http://{}/plain", server.addr()));
  2956. assert!(output["result"]
  2957. .as_str()
  2958. .expect("result")
  2959. .contains("plain text response"));
  2960. let error = execute_tool(
  2961. "WebFetch",
  2962. &json!({
  2963. "url": "not a url",
  2964. "prompt": "Summarize"
  2965. }),
  2966. )
  2967. .expect_err("invalid URL should fail");
  2968. assert!(error.contains("relative URL without a base") || error.contains("invalid"));
  2969. }
  2970. #[test]
  2971. fn web_search_extracts_and_filters_results() {
  2972. let server = TestServer::spawn(Arc::new(|request_line: &str| {
  2973. assert!(request_line.contains("GET /search?q=rust+web+search "));
  2974. HttpResponse::html(
  2975. 200,
  2976. "OK",
  2977. r#"
  2978. <html><body>
  2979. <a class="result__a" href="https://docs.rs/reqwest">Reqwest docs</a>
  2980. <a class="result__a" href="https://example.com/blocked">Blocked result</a>
  2981. </body></html>
  2982. "#,
  2983. )
  2984. }));
  2985. std::env::set_var(
  2986. "CLAWD_WEB_SEARCH_BASE_URL",
  2987. format!("http://{}/search", server.addr()),
  2988. );
  2989. let result = execute_tool(
  2990. "WebSearch",
  2991. &json!({
  2992. "query": "rust web search",
  2993. "allowed_domains": ["https://DOCS.rs/"],
  2994. "blocked_domains": ["HTTPS://EXAMPLE.COM"]
  2995. }),
  2996. )
  2997. .expect("WebSearch should succeed");
  2998. std::env::remove_var("CLAWD_WEB_SEARCH_BASE_URL");
  2999. let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
  3000. assert_eq!(output["query"], "rust web search");
  3001. let results = output["results"].as_array().expect("results array");
  3002. let search_result = results
  3003. .iter()
  3004. .find(|item| item.get("content").is_some())
  3005. .expect("search result block present");
  3006. let content = search_result["content"].as_array().expect("content array");
  3007. assert_eq!(content.len(), 1);
  3008. assert_eq!(content[0]["title"], "Reqwest docs");
  3009. assert_eq!(content[0]["url"], "https://docs.rs/reqwest");
  3010. }
  3011. #[test]
  3012. fn web_search_handles_generic_links_and_invalid_base_url() {
  3013. let _guard = env_lock()
  3014. .lock()
  3015. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3016. let server = TestServer::spawn(Arc::new(|request_line: &str| {
  3017. assert!(request_line.contains("GET /fallback?q=generic+links "));
  3018. HttpResponse::html(
  3019. 200,
  3020. "OK",
  3021. r#"
  3022. <html><body>
  3023. <a href="https://example.com/one">Example One</a>
  3024. <a href="https://example.com/one">Duplicate Example One</a>
  3025. <a href="https://docs.rs/tokio">Tokio Docs</a>
  3026. </body></html>
  3027. "#,
  3028. )
  3029. }));
  3030. std::env::set_var(
  3031. "CLAWD_WEB_SEARCH_BASE_URL",
  3032. format!("http://{}/fallback", server.addr()),
  3033. );
  3034. let result = execute_tool(
  3035. "WebSearch",
  3036. &json!({
  3037. "query": "generic links"
  3038. }),
  3039. )
  3040. .expect("WebSearch fallback parsing should succeed");
  3041. std::env::remove_var("CLAWD_WEB_SEARCH_BASE_URL");
  3042. let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
  3043. let results = output["results"].as_array().expect("results array");
  3044. let search_result = results
  3045. .iter()
  3046. .find(|item| item.get("content").is_some())
  3047. .expect("search result block present");
  3048. let content = search_result["content"].as_array().expect("content array");
  3049. assert_eq!(content.len(), 2);
  3050. assert_eq!(content[0]["url"], "https://example.com/one");
  3051. assert_eq!(content[1]["url"], "https://docs.rs/tokio");
  3052. std::env::set_var("CLAWD_WEB_SEARCH_BASE_URL", "://bad-base-url");
  3053. let error = execute_tool("WebSearch", &json!({ "query": "generic links" }))
  3054. .expect_err("invalid base URL should fail");
  3055. std::env::remove_var("CLAWD_WEB_SEARCH_BASE_URL");
  3056. assert!(error.contains("relative URL without a base") || error.contains("empty host"));
  3057. }
  3058. #[test]
  3059. fn pending_tools_preserve_multiple_streaming_tool_calls_by_index() {
  3060. let mut events = Vec::new();
  3061. let mut pending_tools = BTreeMap::new();
  3062. push_output_block(
  3063. OutputContentBlock::ToolUse {
  3064. id: "tool-1".to_string(),
  3065. name: "read_file".to_string(),
  3066. input: json!({}),
  3067. },
  3068. 1,
  3069. &mut events,
  3070. &mut pending_tools,
  3071. true,
  3072. );
  3073. push_output_block(
  3074. OutputContentBlock::ToolUse {
  3075. id: "tool-2".to_string(),
  3076. name: "grep_search".to_string(),
  3077. input: json!({}),
  3078. },
  3079. 2,
  3080. &mut events,
  3081. &mut pending_tools,
  3082. true,
  3083. );
  3084. pending_tools
  3085. .get_mut(&1)
  3086. .expect("first tool pending")
  3087. .2
  3088. .push_str("{\"path\":\"src/main.rs\"}");
  3089. pending_tools
  3090. .get_mut(&2)
  3091. .expect("second tool pending")
  3092. .2
  3093. .push_str("{\"pattern\":\"TODO\"}");
  3094. assert_eq!(
  3095. pending_tools.remove(&1),
  3096. Some((
  3097. "tool-1".to_string(),
  3098. "read_file".to_string(),
  3099. "{\"path\":\"src/main.rs\"}".to_string(),
  3100. ))
  3101. );
  3102. assert_eq!(
  3103. pending_tools.remove(&2),
  3104. Some((
  3105. "tool-2".to_string(),
  3106. "grep_search".to_string(),
  3107. "{\"pattern\":\"TODO\"}".to_string(),
  3108. ))
  3109. );
  3110. }
  3111. #[test]
  3112. fn todo_write_persists_and_returns_previous_state() {
  3113. let _guard = env_lock()
  3114. .lock()
  3115. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3116. let path = temp_path("todos.json");
  3117. std::env::set_var("CLAWD_TODO_STORE", &path);
  3118. let first = execute_tool(
  3119. "TodoWrite",
  3120. &json!({
  3121. "todos": [
  3122. {"content": "Add tool", "activeForm": "Adding tool", "status": "in_progress"},
  3123. {"content": "Run tests", "activeForm": "Running tests", "status": "pending"}
  3124. ]
  3125. }),
  3126. )
  3127. .expect("TodoWrite should succeed");
  3128. let first_output: serde_json::Value = serde_json::from_str(&first).expect("valid json");
  3129. assert_eq!(first_output["oldTodos"].as_array().expect("array").len(), 0);
  3130. let second = execute_tool(
  3131. "TodoWrite",
  3132. &json!({
  3133. "todos": [
  3134. {"content": "Add tool", "activeForm": "Adding tool", "status": "completed"},
  3135. {"content": "Run tests", "activeForm": "Running tests", "status": "completed"},
  3136. {"content": "Verify", "activeForm": "Verifying", "status": "completed"}
  3137. ]
  3138. }),
  3139. )
  3140. .expect("TodoWrite should succeed");
  3141. std::env::remove_var("CLAWD_TODO_STORE");
  3142. let _ = std::fs::remove_file(path);
  3143. let second_output: serde_json::Value = serde_json::from_str(&second).expect("valid json");
  3144. assert_eq!(
  3145. second_output["oldTodos"].as_array().expect("array").len(),
  3146. 2
  3147. );
  3148. assert_eq!(
  3149. second_output["newTodos"].as_array().expect("array").len(),
  3150. 3
  3151. );
  3152. assert!(second_output["verificationNudgeNeeded"].is_null());
  3153. }
  3154. #[test]
  3155. fn todo_write_rejects_invalid_payloads_and_sets_verification_nudge() {
  3156. let _guard = env_lock()
  3157. .lock()
  3158. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3159. let path = temp_path("todos-errors.json");
  3160. std::env::set_var("CLAWD_TODO_STORE", &path);
  3161. let empty = execute_tool("TodoWrite", &json!({ "todos": [] }))
  3162. .expect_err("empty todos should fail");
  3163. assert!(empty.contains("todos must not be empty"));
  3164. // Multiple in_progress items are now allowed for parallel workflows
  3165. let _multi_active = execute_tool(
  3166. "TodoWrite",
  3167. &json!({
  3168. "todos": [
  3169. {"content": "One", "activeForm": "Doing one", "status": "in_progress"},
  3170. {"content": "Two", "activeForm": "Doing two", "status": "in_progress"}
  3171. ]
  3172. }),
  3173. )
  3174. .expect("multiple in-progress todos should succeed");
  3175. let blank_content = execute_tool(
  3176. "TodoWrite",
  3177. &json!({
  3178. "todos": [
  3179. {"content": " ", "activeForm": "Doing it", "status": "pending"}
  3180. ]
  3181. }),
  3182. )
  3183. .expect_err("blank content should fail");
  3184. assert!(blank_content.contains("todo content must not be empty"));
  3185. let nudge = execute_tool(
  3186. "TodoWrite",
  3187. &json!({
  3188. "todos": [
  3189. {"content": "Write tests", "activeForm": "Writing tests", "status": "completed"},
  3190. {"content": "Fix errors", "activeForm": "Fixing errors", "status": "completed"},
  3191. {"content": "Ship branch", "activeForm": "Shipping branch", "status": "completed"}
  3192. ]
  3193. }),
  3194. )
  3195. .expect("completed todos should succeed");
  3196. std::env::remove_var("CLAWD_TODO_STORE");
  3197. let _ = fs::remove_file(path);
  3198. let output: serde_json::Value = serde_json::from_str(&nudge).expect("valid json");
  3199. assert_eq!(output["verificationNudgeNeeded"], true);
  3200. }
  3201. #[test]
  3202. fn skill_loads_local_skill_prompt() {
  3203. let _guard = env_lock().lock().expect("env lock should acquire");
  3204. let home = temp_path("skills-home");
  3205. let skill_dir = home.join(".agents").join("skills").join("help");
  3206. fs::create_dir_all(&skill_dir).expect("skill dir should exist");
  3207. fs::write(
  3208. skill_dir.join("SKILL.md"),
  3209. "# help\n\nGuide on using oh-my-codex plugin\n",
  3210. )
  3211. .expect("skill file should exist");
  3212. let original_home = std::env::var("HOME").ok();
  3213. std::env::set_var("HOME", &home);
  3214. let result = execute_tool(
  3215. "Skill",
  3216. &json!({
  3217. "skill": "help",
  3218. "args": "overview"
  3219. }),
  3220. )
  3221. .expect("Skill should succeed");
  3222. let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
  3223. assert_eq!(output["skill"], "help");
  3224. assert!(output["path"]
  3225. .as_str()
  3226. .expect("path")
  3227. .ends_with("/help/SKILL.md"));
  3228. assert!(output["prompt"]
  3229. .as_str()
  3230. .expect("prompt")
  3231. .contains("Guide on using oh-my-codex plugin"));
  3232. let dollar_result = execute_tool(
  3233. "Skill",
  3234. &json!({
  3235. "skill": "$help"
  3236. }),
  3237. )
  3238. .expect("Skill should accept $skill invocation form");
  3239. let dollar_output: serde_json::Value =
  3240. serde_json::from_str(&dollar_result).expect("valid json");
  3241. assert_eq!(dollar_output["skill"], "$help");
  3242. assert!(dollar_output["path"]
  3243. .as_str()
  3244. .expect("path")
  3245. .ends_with("/help/SKILL.md"));
  3246. if let Some(home) = original_home {
  3247. std::env::set_var("HOME", home);
  3248. } else {
  3249. std::env::remove_var("HOME");
  3250. }
  3251. fs::remove_dir_all(home).expect("temp home should clean up");
  3252. }
  3253. #[test]
  3254. fn tool_search_supports_keyword_and_select_queries() {
  3255. let keyword = execute_tool(
  3256. "ToolSearch",
  3257. &json!({"query": "web current", "max_results": 3}),
  3258. )
  3259. .expect("ToolSearch should succeed");
  3260. let keyword_output: serde_json::Value = serde_json::from_str(&keyword).expect("valid json");
  3261. let matches = keyword_output["matches"].as_array().expect("matches");
  3262. assert!(matches.iter().any(|value| value == "WebSearch"));
  3263. let selected = execute_tool("ToolSearch", &json!({"query": "select:Agent,Skill"}))
  3264. .expect("ToolSearch should succeed");
  3265. let selected_output: serde_json::Value =
  3266. serde_json::from_str(&selected).expect("valid json");
  3267. assert_eq!(selected_output["matches"][0], "Agent");
  3268. assert_eq!(selected_output["matches"][1], "Skill");
  3269. let aliased = execute_tool("ToolSearch", &json!({"query": "AgentTool"}))
  3270. .expect("ToolSearch should support tool aliases");
  3271. let aliased_output: serde_json::Value = serde_json::from_str(&aliased).expect("valid json");
  3272. assert_eq!(aliased_output["matches"][0], "Agent");
  3273. assert_eq!(aliased_output["normalized_query"], "agent");
  3274. let selected_with_alias =
  3275. execute_tool("ToolSearch", &json!({"query": "select:AgentTool,Skill"}))
  3276. .expect("ToolSearch alias select should succeed");
  3277. let selected_with_alias_output: serde_json::Value =
  3278. serde_json::from_str(&selected_with_alias).expect("valid json");
  3279. assert_eq!(selected_with_alias_output["matches"][0], "Agent");
  3280. assert_eq!(selected_with_alias_output["matches"][1], "Skill");
  3281. }
  3282. #[test]
  3283. fn agent_persists_handoff_metadata() {
  3284. let _guard = env_lock()
  3285. .lock()
  3286. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3287. let dir = temp_path("agent-store");
  3288. std::env::set_var("CLAWD_AGENT_STORE", &dir);
  3289. let captured = Arc::new(Mutex::new(None::<AgentJob>));
  3290. let captured_for_spawn = Arc::clone(&captured);
  3291. let manifest = execute_agent_with_spawn(
  3292. AgentInput {
  3293. description: "Audit the branch".to_string(),
  3294. prompt: "Check tests and outstanding work.".to_string(),
  3295. subagent_type: Some("Explore".to_string()),
  3296. name: Some("ship-audit".to_string()),
  3297. model: None,
  3298. },
  3299. move |job| {
  3300. *captured_for_spawn
  3301. .lock()
  3302. .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(job);
  3303. Ok(())
  3304. },
  3305. )
  3306. .expect("Agent should succeed");
  3307. std::env::remove_var("CLAWD_AGENT_STORE");
  3308. assert_eq!(manifest.name, "ship-audit");
  3309. assert_eq!(manifest.subagent_type.as_deref(), Some("Explore"));
  3310. assert_eq!(manifest.status, "running");
  3311. assert!(!manifest.created_at.is_empty());
  3312. assert!(manifest.started_at.is_some());
  3313. assert!(manifest.completed_at.is_none());
  3314. let contents = std::fs::read_to_string(&manifest.output_file).expect("agent file exists");
  3315. let manifest_contents =
  3316. std::fs::read_to_string(&manifest.manifest_file).expect("manifest file exists");
  3317. assert!(contents.contains("Audit the branch"));
  3318. assert!(contents.contains("Check tests and outstanding work."));
  3319. assert!(manifest_contents.contains("\"subagentType\": \"Explore\""));
  3320. assert!(manifest_contents.contains("\"status\": \"running\""));
  3321. let captured_job = captured
  3322. .lock()
  3323. .unwrap_or_else(std::sync::PoisonError::into_inner)
  3324. .clone()
  3325. .expect("spawn job should be captured");
  3326. assert_eq!(captured_job.prompt, "Check tests and outstanding work.");
  3327. assert!(captured_job.allowed_tools.contains("read_file"));
  3328. assert!(!captured_job.allowed_tools.contains("Agent"));
  3329. let normalized = execute_tool(
  3330. "Agent",
  3331. &json!({
  3332. "description": "Verify the branch",
  3333. "prompt": "Check tests.",
  3334. "subagent_type": "explorer"
  3335. }),
  3336. )
  3337. .expect("Agent should normalize built-in aliases");
  3338. let normalized_output: serde_json::Value =
  3339. serde_json::from_str(&normalized).expect("valid json");
  3340. assert_eq!(normalized_output["subagentType"], "Explore");
  3341. let named = execute_tool(
  3342. "Agent",
  3343. &json!({
  3344. "description": "Review the branch",
  3345. "prompt": "Inspect diff.",
  3346. "name": "Ship Audit!!!"
  3347. }),
  3348. )
  3349. .expect("Agent should normalize explicit names");
  3350. let named_output: serde_json::Value = serde_json::from_str(&named).expect("valid json");
  3351. assert_eq!(named_output["name"], "ship-audit");
  3352. let _ = std::fs::remove_dir_all(dir);
  3353. }
  3354. #[test]
  3355. fn agent_fake_runner_can_persist_completion_and_failure() {
  3356. let _guard = env_lock()
  3357. .lock()
  3358. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3359. let dir = temp_path("agent-runner");
  3360. std::env::set_var("CLAWD_AGENT_STORE", &dir);
  3361. let completed = execute_agent_with_spawn(
  3362. AgentInput {
  3363. description: "Complete the task".to_string(),
  3364. prompt: "Do the work".to_string(),
  3365. subagent_type: Some("Explore".to_string()),
  3366. name: Some("complete-task".to_string()),
  3367. model: Some("claude-sonnet-4-6".to_string()),
  3368. },
  3369. |job| {
  3370. persist_agent_terminal_state(
  3371. &job.manifest,
  3372. "completed",
  3373. Some("Finished successfully"),
  3374. None,
  3375. )
  3376. },
  3377. )
  3378. .expect("completed agent should succeed");
  3379. let completed_manifest = std::fs::read_to_string(&completed.manifest_file)
  3380. .expect("completed manifest should exist");
  3381. let completed_output =
  3382. std::fs::read_to_string(&completed.output_file).expect("completed output should exist");
  3383. assert!(completed_manifest.contains("\"status\": \"completed\""));
  3384. assert!(completed_output.contains("Finished successfully"));
  3385. let failed = execute_agent_with_spawn(
  3386. AgentInput {
  3387. description: "Fail the task".to_string(),
  3388. prompt: "Do the failing work".to_string(),
  3389. subagent_type: Some("Verification".to_string()),
  3390. name: Some("fail-task".to_string()),
  3391. model: None,
  3392. },
  3393. |job| {
  3394. persist_agent_terminal_state(
  3395. &job.manifest,
  3396. "failed",
  3397. None,
  3398. Some(String::from("simulated failure")),
  3399. )
  3400. },
  3401. )
  3402. .expect("failed agent should still spawn");
  3403. let failed_manifest =
  3404. std::fs::read_to_string(&failed.manifest_file).expect("failed manifest should exist");
  3405. let failed_output =
  3406. std::fs::read_to_string(&failed.output_file).expect("failed output should exist");
  3407. assert!(failed_manifest.contains("\"status\": \"failed\""));
  3408. assert!(failed_manifest.contains("simulated failure"));
  3409. assert!(failed_output.contains("simulated failure"));
  3410. let spawn_error = execute_agent_with_spawn(
  3411. AgentInput {
  3412. description: "Spawn error task".to_string(),
  3413. prompt: "Never starts".to_string(),
  3414. subagent_type: None,
  3415. name: Some("spawn-error".to_string()),
  3416. model: None,
  3417. },
  3418. |_| Err(String::from("thread creation failed")),
  3419. )
  3420. .expect_err("spawn errors should surface");
  3421. assert!(spawn_error.contains("failed to spawn sub-agent"));
  3422. let spawn_error_manifest = std::fs::read_dir(&dir)
  3423. .expect("agent dir should exist")
  3424. .filter_map(Result::ok)
  3425. .map(|entry| entry.path())
  3426. .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("json"))
  3427. .find_map(|path| {
  3428. let contents = std::fs::read_to_string(&path).ok()?;
  3429. contents
  3430. .contains("\"name\": \"spawn-error\"")
  3431. .then_some(contents)
  3432. })
  3433. .expect("failed manifest should still be written");
  3434. assert!(spawn_error_manifest.contains("\"status\": \"failed\""));
  3435. assert!(spawn_error_manifest.contains("thread creation failed"));
  3436. std::env::remove_var("CLAWD_AGENT_STORE");
  3437. let _ = std::fs::remove_dir_all(dir);
  3438. }
  3439. #[test]
  3440. fn agent_tool_subset_mapping_is_expected() {
  3441. let general = allowed_tools_for_subagent("general-purpose");
  3442. assert!(general.contains("bash"));
  3443. assert!(general.contains("write_file"));
  3444. assert!(!general.contains("Agent"));
  3445. let explore = allowed_tools_for_subagent("Explore");
  3446. assert!(explore.contains("read_file"));
  3447. assert!(explore.contains("grep_search"));
  3448. assert!(!explore.contains("bash"));
  3449. let plan = allowed_tools_for_subagent("Plan");
  3450. assert!(plan.contains("TodoWrite"));
  3451. assert!(plan.contains("StructuredOutput"));
  3452. assert!(!plan.contains("Agent"));
  3453. let verification = allowed_tools_for_subagent("Verification");
  3454. assert!(verification.contains("bash"));
  3455. assert!(verification.contains("PowerShell"));
  3456. assert!(!verification.contains("write_file"));
  3457. }
  3458. #[derive(Debug)]
  3459. struct MockSubagentApiClient {
  3460. calls: usize,
  3461. input_path: String,
  3462. }
  3463. impl runtime::ApiClient for MockSubagentApiClient {
  3464. fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
  3465. self.calls += 1;
  3466. match self.calls {
  3467. 1 => {
  3468. assert_eq!(request.messages.len(), 1);
  3469. Ok(vec![
  3470. AssistantEvent::ToolUse {
  3471. id: "tool-1".to_string(),
  3472. name: "read_file".to_string(),
  3473. input: json!({ "path": self.input_path }).to_string(),
  3474. },
  3475. AssistantEvent::MessageStop,
  3476. ])
  3477. }
  3478. 2 => {
  3479. assert!(request.messages.len() >= 3);
  3480. Ok(vec![
  3481. AssistantEvent::TextDelta("Scope: completed mock review".to_string()),
  3482. AssistantEvent::MessageStop,
  3483. ])
  3484. }
  3485. _ => panic!("unexpected mock stream call"),
  3486. }
  3487. }
  3488. }
  3489. #[test]
  3490. fn subagent_runtime_executes_tool_loop_with_isolated_session() {
  3491. let _guard = env_lock()
  3492. .lock()
  3493. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3494. let path = temp_path("subagent-input.txt");
  3495. std::fs::write(&path, "hello from child").expect("write input file");
  3496. let mut runtime = ConversationRuntime::new(
  3497. Session::new(),
  3498. MockSubagentApiClient {
  3499. calls: 0,
  3500. input_path: path.display().to_string(),
  3501. },
  3502. SubagentToolExecutor::new(BTreeSet::from([String::from("read_file")])),
  3503. agent_permission_policy(),
  3504. vec![String::from("system prompt")],
  3505. );
  3506. let summary = runtime
  3507. .run_turn("Inspect the delegated file", None)
  3508. .expect("subagent loop should succeed");
  3509. assert_eq!(
  3510. final_assistant_text(&summary),
  3511. "Scope: completed mock review"
  3512. );
  3513. assert!(runtime
  3514. .session()
  3515. .messages
  3516. .iter()
  3517. .flat_map(|message| message.blocks.iter())
  3518. .any(|block| matches!(
  3519. block,
  3520. runtime::ContentBlock::ToolResult { output, .. }
  3521. if output.contains("hello from child")
  3522. )));
  3523. let _ = std::fs::remove_file(path);
  3524. }
  3525. #[test]
  3526. fn agent_rejects_blank_required_fields() {
  3527. let missing_description = execute_tool(
  3528. "Agent",
  3529. &json!({
  3530. "description": " ",
  3531. "prompt": "Inspect"
  3532. }),
  3533. )
  3534. .expect_err("blank description should fail");
  3535. assert!(missing_description.contains("description must not be empty"));
  3536. let missing_prompt = execute_tool(
  3537. "Agent",
  3538. &json!({
  3539. "description": "Inspect branch",
  3540. "prompt": " "
  3541. }),
  3542. )
  3543. .expect_err("blank prompt should fail");
  3544. assert!(missing_prompt.contains("prompt must not be empty"));
  3545. }
  3546. #[test]
  3547. fn notebook_edit_replaces_inserts_and_deletes_cells() {
  3548. let path = temp_path("notebook.ipynb");
  3549. std::fs::write(
  3550. &path,
  3551. r#"{
  3552. "cells": [
  3553. {"cell_type": "code", "id": "cell-a", "metadata": {}, "source": ["print(1)\n"], "outputs": [], "execution_count": null}
  3554. ],
  3555. "metadata": {"kernelspec": {"language": "python"}},
  3556. "nbformat": 4,
  3557. "nbformat_minor": 5
  3558. }"#,
  3559. )
  3560. .expect("write notebook");
  3561. let replaced = execute_tool(
  3562. "NotebookEdit",
  3563. &json!({
  3564. "notebook_path": path.display().to_string(),
  3565. "cell_id": "cell-a",
  3566. "new_source": "print(2)\n",
  3567. "edit_mode": "replace"
  3568. }),
  3569. )
  3570. .expect("NotebookEdit replace should succeed");
  3571. let replaced_output: serde_json::Value = serde_json::from_str(&replaced).expect("json");
  3572. assert_eq!(replaced_output["cell_id"], "cell-a");
  3573. assert_eq!(replaced_output["cell_type"], "code");
  3574. let inserted = execute_tool(
  3575. "NotebookEdit",
  3576. &json!({
  3577. "notebook_path": path.display().to_string(),
  3578. "cell_id": "cell-a",
  3579. "new_source": "# heading\n",
  3580. "cell_type": "markdown",
  3581. "edit_mode": "insert"
  3582. }),
  3583. )
  3584. .expect("NotebookEdit insert should succeed");
  3585. let inserted_output: serde_json::Value = serde_json::from_str(&inserted).expect("json");
  3586. assert_eq!(inserted_output["cell_type"], "markdown");
  3587. let appended = execute_tool(
  3588. "NotebookEdit",
  3589. &json!({
  3590. "notebook_path": path.display().to_string(),
  3591. "new_source": "print(3)\n",
  3592. "edit_mode": "insert"
  3593. }),
  3594. )
  3595. .expect("NotebookEdit append should succeed");
  3596. let appended_output: serde_json::Value = serde_json::from_str(&appended).expect("json");
  3597. assert_eq!(appended_output["cell_type"], "code");
  3598. let deleted = execute_tool(
  3599. "NotebookEdit",
  3600. &json!({
  3601. "notebook_path": path.display().to_string(),
  3602. "cell_id": "cell-a",
  3603. "edit_mode": "delete"
  3604. }),
  3605. )
  3606. .expect("NotebookEdit delete should succeed without new_source");
  3607. let deleted_output: serde_json::Value = serde_json::from_str(&deleted).expect("json");
  3608. assert!(deleted_output["cell_type"].is_null());
  3609. assert_eq!(deleted_output["new_source"], "");
  3610. let final_notebook: serde_json::Value =
  3611. serde_json::from_str(&std::fs::read_to_string(&path).expect("read notebook"))
  3612. .expect("valid notebook json");
  3613. let cells = final_notebook["cells"].as_array().expect("cells array");
  3614. assert_eq!(cells.len(), 2);
  3615. assert_eq!(cells[0]["cell_type"], "markdown");
  3616. assert!(cells[0].get("outputs").is_none());
  3617. assert_eq!(cells[1]["cell_type"], "code");
  3618. assert_eq!(cells[1]["source"][0], "print(3)\n");
  3619. let _ = std::fs::remove_file(path);
  3620. }
  3621. #[test]
  3622. fn notebook_edit_rejects_invalid_inputs() {
  3623. let text_path = temp_path("notebook.txt");
  3624. fs::write(&text_path, "not a notebook").expect("write text file");
  3625. let wrong_extension = execute_tool(
  3626. "NotebookEdit",
  3627. &json!({
  3628. "notebook_path": text_path.display().to_string(),
  3629. "new_source": "print(1)\n"
  3630. }),
  3631. )
  3632. .expect_err("non-ipynb file should fail");
  3633. assert!(wrong_extension.contains("Jupyter notebook"));
  3634. let _ = fs::remove_file(&text_path);
  3635. let empty_notebook = temp_path("empty.ipynb");
  3636. fs::write(
  3637. &empty_notebook,
  3638. r#"{"cells":[],"metadata":{"kernelspec":{"language":"python"}},"nbformat":4,"nbformat_minor":5}"#,
  3639. )
  3640. .expect("write empty notebook");
  3641. let missing_source = execute_tool(
  3642. "NotebookEdit",
  3643. &json!({
  3644. "notebook_path": empty_notebook.display().to_string(),
  3645. "edit_mode": "insert"
  3646. }),
  3647. )
  3648. .expect_err("insert without source should fail");
  3649. assert!(missing_source.contains("new_source is required"));
  3650. let missing_cell = execute_tool(
  3651. "NotebookEdit",
  3652. &json!({
  3653. "notebook_path": empty_notebook.display().to_string(),
  3654. "edit_mode": "delete"
  3655. }),
  3656. )
  3657. .expect_err("delete on empty notebook should fail");
  3658. assert!(missing_cell.contains("Notebook has no cells to edit"));
  3659. let _ = fs::remove_file(empty_notebook);
  3660. }
  3661. #[test]
  3662. fn bash_tool_reports_success_exit_failure_timeout_and_background() {
  3663. let success = execute_tool("bash", &json!({ "command": "printf 'hello'" }))
  3664. .expect("bash should succeed");
  3665. let success_output: serde_json::Value = serde_json::from_str(&success).expect("json");
  3666. assert_eq!(success_output["stdout"], "hello");
  3667. assert_eq!(success_output["interrupted"], false);
  3668. let failure = execute_tool("bash", &json!({ "command": "printf 'oops' >&2; exit 7" }))
  3669. .expect("bash failure should still return structured output");
  3670. let failure_output: serde_json::Value = serde_json::from_str(&failure).expect("json");
  3671. assert_eq!(failure_output["returnCodeInterpretation"], "exit_code:7");
  3672. assert!(failure_output["stderr"]
  3673. .as_str()
  3674. .expect("stderr")
  3675. .contains("oops"));
  3676. let timeout = execute_tool("bash", &json!({ "command": "sleep 1", "timeout": 10 }))
  3677. .expect("bash timeout should return output");
  3678. let timeout_output: serde_json::Value = serde_json::from_str(&timeout).expect("json");
  3679. assert_eq!(timeout_output["interrupted"], true);
  3680. assert_eq!(timeout_output["returnCodeInterpretation"], "timeout");
  3681. assert!(timeout_output["stderr"]
  3682. .as_str()
  3683. .expect("stderr")
  3684. .contains("Command exceeded timeout"));
  3685. let background = execute_tool(
  3686. "bash",
  3687. &json!({ "command": "sleep 1", "run_in_background": true }),
  3688. )
  3689. .expect("bash background should succeed");
  3690. let background_output: serde_json::Value = serde_json::from_str(&background).expect("json");
  3691. assert!(background_output["backgroundTaskId"].as_str().is_some());
  3692. assert_eq!(background_output["noOutputExpected"], true);
  3693. }
  3694. #[test]
  3695. fn file_tools_cover_read_write_and_edit_behaviors() {
  3696. let _guard = env_lock()
  3697. .lock()
  3698. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3699. let root = temp_path("fs-suite");
  3700. fs::create_dir_all(&root).expect("create root");
  3701. let original_dir = std::env::current_dir().expect("cwd");
  3702. std::env::set_current_dir(&root).expect("set cwd");
  3703. let write_create = execute_tool(
  3704. "write_file",
  3705. &json!({ "path": "nested/demo.txt", "content": "alpha\nbeta\nalpha\n" }),
  3706. )
  3707. .expect("write create should succeed");
  3708. let write_create_output: serde_json::Value =
  3709. serde_json::from_str(&write_create).expect("json");
  3710. assert_eq!(write_create_output["type"], "create");
  3711. assert!(root.join("nested/demo.txt").exists());
  3712. let write_update = execute_tool(
  3713. "write_file",
  3714. &json!({ "path": "nested/demo.txt", "content": "alpha\nbeta\ngamma\n" }),
  3715. )
  3716. .expect("write update should succeed");
  3717. let write_update_output: serde_json::Value =
  3718. serde_json::from_str(&write_update).expect("json");
  3719. assert_eq!(write_update_output["type"], "update");
  3720. assert_eq!(write_update_output["originalFile"], "alpha\nbeta\nalpha\n");
  3721. let read_full = execute_tool("read_file", &json!({ "path": "nested/demo.txt" }))
  3722. .expect("read full should succeed");
  3723. let read_full_output: serde_json::Value = serde_json::from_str(&read_full).expect("json");
  3724. assert_eq!(read_full_output["file"]["content"], "alpha\nbeta\ngamma");
  3725. assert_eq!(read_full_output["file"]["startLine"], 1);
  3726. let read_slice = execute_tool(
  3727. "read_file",
  3728. &json!({ "path": "nested/demo.txt", "offset": 1, "limit": 1 }),
  3729. )
  3730. .expect("read slice should succeed");
  3731. let read_slice_output: serde_json::Value = serde_json::from_str(&read_slice).expect("json");
  3732. assert_eq!(read_slice_output["file"]["content"], "beta");
  3733. assert_eq!(read_slice_output["file"]["startLine"], 2);
  3734. let read_past_end = execute_tool(
  3735. "read_file",
  3736. &json!({ "path": "nested/demo.txt", "offset": 50 }),
  3737. )
  3738. .expect("read past EOF should succeed");
  3739. let read_past_end_output: serde_json::Value =
  3740. serde_json::from_str(&read_past_end).expect("json");
  3741. assert_eq!(read_past_end_output["file"]["content"], "");
  3742. assert_eq!(read_past_end_output["file"]["startLine"], 4);
  3743. let read_error = execute_tool("read_file", &json!({ "path": "missing.txt" }))
  3744. .expect_err("missing file should fail");
  3745. assert!(!read_error.is_empty());
  3746. let edit_once = execute_tool(
  3747. "edit_file",
  3748. &json!({ "path": "nested/demo.txt", "old_string": "alpha", "new_string": "omega" }),
  3749. )
  3750. .expect("single edit should succeed");
  3751. let edit_once_output: serde_json::Value = serde_json::from_str(&edit_once).expect("json");
  3752. assert_eq!(edit_once_output["replaceAll"], false);
  3753. assert_eq!(
  3754. fs::read_to_string(root.join("nested/demo.txt")).expect("read file"),
  3755. "omega\nbeta\ngamma\n"
  3756. );
  3757. execute_tool(
  3758. "write_file",
  3759. &json!({ "path": "nested/demo.txt", "content": "alpha\nbeta\nalpha\n" }),
  3760. )
  3761. .expect("reset file");
  3762. let edit_all = execute_tool(
  3763. "edit_file",
  3764. &json!({
  3765. "path": "nested/demo.txt",
  3766. "old_string": "alpha",
  3767. "new_string": "omega",
  3768. "replace_all": true
  3769. }),
  3770. )
  3771. .expect("replace all should succeed");
  3772. let edit_all_output: serde_json::Value = serde_json::from_str(&edit_all).expect("json");
  3773. assert_eq!(edit_all_output["replaceAll"], true);
  3774. assert_eq!(
  3775. fs::read_to_string(root.join("nested/demo.txt")).expect("read file"),
  3776. "omega\nbeta\nomega\n"
  3777. );
  3778. let edit_same = execute_tool(
  3779. "edit_file",
  3780. &json!({ "path": "nested/demo.txt", "old_string": "omega", "new_string": "omega" }),
  3781. )
  3782. .expect_err("identical old/new should fail");
  3783. assert!(edit_same.contains("must differ"));
  3784. let edit_missing = execute_tool(
  3785. "edit_file",
  3786. &json!({ "path": "nested/demo.txt", "old_string": "missing", "new_string": "omega" }),
  3787. )
  3788. .expect_err("missing substring should fail");
  3789. assert!(edit_missing.contains("old_string not found"));
  3790. std::env::set_current_dir(&original_dir).expect("restore cwd");
  3791. let _ = fs::remove_dir_all(root);
  3792. }
  3793. #[test]
  3794. fn glob_and_grep_tools_cover_success_and_errors() {
  3795. let _guard = env_lock()
  3796. .lock()
  3797. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3798. let root = temp_path("search-suite");
  3799. fs::create_dir_all(root.join("nested")).expect("create root");
  3800. let original_dir = std::env::current_dir().expect("cwd");
  3801. std::env::set_current_dir(&root).expect("set cwd");
  3802. fs::write(
  3803. root.join("nested/lib.rs"),
  3804. "fn main() {}\nlet alpha = 1;\nlet alpha = 2;\n",
  3805. )
  3806. .expect("write rust file");
  3807. fs::write(root.join("nested/notes.txt"), "alpha\nbeta\n").expect("write txt file");
  3808. let globbed = execute_tool("glob_search", &json!({ "pattern": "nested/*.rs" }))
  3809. .expect("glob should succeed");
  3810. let globbed_output: serde_json::Value = serde_json::from_str(&globbed).expect("json");
  3811. assert_eq!(globbed_output["numFiles"], 1);
  3812. assert!(globbed_output["filenames"][0]
  3813. .as_str()
  3814. .expect("filename")
  3815. .ends_with("nested/lib.rs"));
  3816. let glob_error = execute_tool("glob_search", &json!({ "pattern": "[" }))
  3817. .expect_err("invalid glob should fail");
  3818. assert!(!glob_error.is_empty());
  3819. let grep_content = execute_tool(
  3820. "grep_search",
  3821. &json!({
  3822. "pattern": "alpha",
  3823. "path": "nested",
  3824. "glob": "*.rs",
  3825. "output_mode": "content",
  3826. "-n": true,
  3827. "head_limit": 1,
  3828. "offset": 1
  3829. }),
  3830. )
  3831. .expect("grep content should succeed");
  3832. let grep_content_output: serde_json::Value =
  3833. serde_json::from_str(&grep_content).expect("json");
  3834. assert_eq!(grep_content_output["numFiles"], 0);
  3835. assert!(grep_content_output["appliedLimit"].is_null());
  3836. assert_eq!(grep_content_output["appliedOffset"], 1);
  3837. assert!(grep_content_output["content"]
  3838. .as_str()
  3839. .expect("content")
  3840. .contains("let alpha = 2;"));
  3841. let grep_count = execute_tool(
  3842. "grep_search",
  3843. &json!({ "pattern": "alpha", "path": "nested", "output_mode": "count" }),
  3844. )
  3845. .expect("grep count should succeed");
  3846. let grep_count_output: serde_json::Value = serde_json::from_str(&grep_count).expect("json");
  3847. assert_eq!(grep_count_output["numMatches"], 3);
  3848. let grep_error = execute_tool(
  3849. "grep_search",
  3850. &json!({ "pattern": "(alpha", "path": "nested" }),
  3851. )
  3852. .expect_err("invalid regex should fail");
  3853. assert!(!grep_error.is_empty());
  3854. std::env::set_current_dir(&original_dir).expect("restore cwd");
  3855. let _ = fs::remove_dir_all(root);
  3856. }
  3857. #[test]
  3858. fn sleep_waits_and_reports_duration() {
  3859. let started = std::time::Instant::now();
  3860. let result =
  3861. execute_tool("Sleep", &json!({"duration_ms": 20})).expect("Sleep should succeed");
  3862. let elapsed = started.elapsed();
  3863. let output: serde_json::Value = serde_json::from_str(&result).expect("json");
  3864. assert_eq!(output["duration_ms"], 20);
  3865. assert!(output["message"]
  3866. .as_str()
  3867. .expect("message")
  3868. .contains("Slept for 20ms"));
  3869. assert!(elapsed >= Duration::from_millis(15));
  3870. }
  3871. #[test]
  3872. fn brief_returns_sent_message_and_attachment_metadata() {
  3873. let attachment = std::env::temp_dir().join(format!(
  3874. "clawd-brief-{}.png",
  3875. std::time::SystemTime::now()
  3876. .duration_since(std::time::UNIX_EPOCH)
  3877. .expect("time")
  3878. .as_nanos()
  3879. ));
  3880. std::fs::write(&attachment, b"png-data").expect("write attachment");
  3881. let result = execute_tool(
  3882. "SendUserMessage",
  3883. &json!({
  3884. "message": "hello user",
  3885. "attachments": [attachment.display().to_string()],
  3886. "status": "normal"
  3887. }),
  3888. )
  3889. .expect("SendUserMessage should succeed");
  3890. let output: serde_json::Value = serde_json::from_str(&result).expect("json");
  3891. assert_eq!(output["message"], "hello user");
  3892. assert!(output["sentAt"].as_str().is_some());
  3893. assert_eq!(output["attachments"][0]["isImage"], true);
  3894. let _ = std::fs::remove_file(attachment);
  3895. }
  3896. #[test]
  3897. fn config_reads_and_writes_supported_values() {
  3898. let _guard = env_lock()
  3899. .lock()
  3900. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3901. let root = std::env::temp_dir().join(format!(
  3902. "clawd-config-{}",
  3903. std::time::SystemTime::now()
  3904. .duration_since(std::time::UNIX_EPOCH)
  3905. .expect("time")
  3906. .as_nanos()
  3907. ));
  3908. let home = root.join("home");
  3909. let cwd = root.join("cwd");
  3910. std::fs::create_dir_all(home.join(".claw")).expect("home dir");
  3911. std::fs::create_dir_all(cwd.join(".claw")).expect("cwd dir");
  3912. std::fs::write(
  3913. home.join(".claw").join("settings.json"),
  3914. r#"{"verbose":false}"#,
  3915. )
  3916. .expect("write global settings");
  3917. let original_home = std::env::var("HOME").ok();
  3918. let original_config_home = std::env::var("CLAW_CONFIG_HOME").ok();
  3919. let original_dir = std::env::current_dir().expect("cwd");
  3920. std::env::set_var("HOME", &home);
  3921. std::env::remove_var("CLAW_CONFIG_HOME");
  3922. std::env::set_current_dir(&cwd).expect("set cwd");
  3923. let get = execute_tool("Config", &json!({"setting": "verbose"})).expect("get config");
  3924. let get_output: serde_json::Value = serde_json::from_str(&get).expect("json");
  3925. assert_eq!(get_output["value"], false);
  3926. let set = execute_tool(
  3927. "Config",
  3928. &json!({"setting": "permissions.defaultMode", "value": "plan"}),
  3929. )
  3930. .expect("set config");
  3931. let set_output: serde_json::Value = serde_json::from_str(&set).expect("json");
  3932. assert_eq!(set_output["operation"], "set");
  3933. assert_eq!(set_output["newValue"], "plan");
  3934. let invalid = execute_tool(
  3935. "Config",
  3936. &json!({"setting": "permissions.defaultMode", "value": "bogus"}),
  3937. )
  3938. .expect_err("invalid config value should error");
  3939. assert!(invalid.contains("Invalid value"));
  3940. let unknown =
  3941. execute_tool("Config", &json!({"setting": "nope"})).expect("unknown setting result");
  3942. let unknown_output: serde_json::Value = serde_json::from_str(&unknown).expect("json");
  3943. assert_eq!(unknown_output["success"], false);
  3944. std::env::set_current_dir(&original_dir).expect("restore cwd");
  3945. match original_home {
  3946. Some(value) => std::env::set_var("HOME", value),
  3947. None => std::env::remove_var("HOME"),
  3948. }
  3949. match original_config_home {
  3950. Some(value) => std::env::set_var("CLAW_CONFIG_HOME", value),
  3951. None => std::env::remove_var("CLAW_CONFIG_HOME"),
  3952. }
  3953. let _ = std::fs::remove_dir_all(root);
  3954. }
  3955. #[test]
  3956. fn structured_output_echoes_input_payload() {
  3957. let result = execute_tool("StructuredOutput", &json!({"ok": true, "items": [1, 2, 3]}))
  3958. .expect("StructuredOutput should succeed");
  3959. let output: serde_json::Value = serde_json::from_str(&result).expect("json");
  3960. assert_eq!(output["data"], "Structured output provided successfully");
  3961. assert_eq!(output["structured_output"]["ok"], true);
  3962. assert_eq!(output["structured_output"]["items"][1], 2);
  3963. }
  3964. #[test]
  3965. fn repl_executes_python_code() {
  3966. let result = execute_tool(
  3967. "REPL",
  3968. &json!({"language": "python", "code": "print(1 + 1)", "timeout_ms": 500}),
  3969. )
  3970. .expect("REPL should succeed");
  3971. let output: serde_json::Value = serde_json::from_str(&result).expect("json");
  3972. assert_eq!(output["language"], "python");
  3973. assert_eq!(output["exitCode"], 0);
  3974. assert!(output["stdout"].as_str().expect("stdout").contains('2'));
  3975. }
  3976. #[test]
  3977. fn powershell_runs_via_stub_shell() {
  3978. let _guard = env_lock()
  3979. .lock()
  3980. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3981. let dir = std::env::temp_dir().join(format!(
  3982. "clawd-pwsh-bin-{}",
  3983. std::time::SystemTime::now()
  3984. .duration_since(std::time::UNIX_EPOCH)
  3985. .expect("time")
  3986. .as_nanos()
  3987. ));
  3988. std::fs::create_dir_all(&dir).expect("create dir");
  3989. let script = dir.join("pwsh");
  3990. std::fs::write(
  3991. &script,
  3992. r#"#!/bin/sh
  3993. while [ "$1" != "-Command" ] && [ $# -gt 0 ]; do shift; done
  3994. shift
  3995. printf 'pwsh:%s' "$1"
  3996. "#,
  3997. )
  3998. .expect("write script");
  3999. std::process::Command::new("/bin/chmod")
  4000. .arg("+x")
  4001. .arg(&script)
  4002. .status()
  4003. .expect("chmod");
  4004. let original_path = std::env::var("PATH").unwrap_or_default();
  4005. std::env::set_var("PATH", format!("{}:{}", dir.display(), original_path));
  4006. let result = execute_tool(
  4007. "PowerShell",
  4008. &json!({"command": "Write-Output hello", "timeout": 1000}),
  4009. )
  4010. .expect("PowerShell should succeed");
  4011. let background = execute_tool(
  4012. "PowerShell",
  4013. &json!({"command": "Write-Output hello", "run_in_background": true}),
  4014. )
  4015. .expect("PowerShell background should succeed");
  4016. std::env::set_var("PATH", original_path);
  4017. let _ = std::fs::remove_dir_all(dir);
  4018. let output: serde_json::Value = serde_json::from_str(&result).expect("json");
  4019. assert_eq!(output["stdout"], "pwsh:Write-Output hello");
  4020. assert!(output["stderr"].as_str().expect("stderr").is_empty());
  4021. let background_output: serde_json::Value = serde_json::from_str(&background).expect("json");
  4022. assert!(background_output["backgroundTaskId"].as_str().is_some());
  4023. assert_eq!(background_output["backgroundedByUser"], true);
  4024. assert_eq!(background_output["assistantAutoBackgrounded"], false);
  4025. }
  4026. #[test]
  4027. fn powershell_errors_when_shell_is_missing() {
  4028. let _guard = env_lock()
  4029. .lock()
  4030. .unwrap_or_else(std::sync::PoisonError::into_inner);
  4031. let original_path = std::env::var("PATH").unwrap_or_default();
  4032. let empty_dir = std::env::temp_dir().join(format!(
  4033. "clawd-empty-bin-{}",
  4034. std::time::SystemTime::now()
  4035. .duration_since(std::time::UNIX_EPOCH)
  4036. .expect("time")
  4037. .as_nanos()
  4038. ));
  4039. std::fs::create_dir_all(&empty_dir).expect("create empty dir");
  4040. std::env::set_var("PATH", empty_dir.display().to_string());
  4041. let err = execute_tool("PowerShell", &json!({"command": "Write-Output hello"}))
  4042. .expect_err("PowerShell should fail when shell is missing");
  4043. std::env::set_var("PATH", original_path);
  4044. let _ = std::fs::remove_dir_all(empty_dir);
  4045. assert!(err.contains("PowerShell executable not found"));
  4046. }
  4047. struct TestServer {
  4048. addr: SocketAddr,
  4049. shutdown: Option<std::sync::mpsc::Sender<()>>,
  4050. handle: Option<thread::JoinHandle<()>>,
  4051. }
  4052. impl TestServer {
  4053. fn spawn(handler: Arc<dyn Fn(&str) -> HttpResponse + Send + Sync + 'static>) -> Self {
  4054. let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
  4055. listener
  4056. .set_nonblocking(true)
  4057. .expect("set nonblocking listener");
  4058. let addr = listener.local_addr().expect("local addr");
  4059. let (tx, rx) = std::sync::mpsc::channel::<()>();
  4060. let handle = thread::spawn(move || loop {
  4061. if rx.try_recv().is_ok() {
  4062. break;
  4063. }
  4064. match listener.accept() {
  4065. Ok((mut stream, _)) => {
  4066. let mut buffer = [0_u8; 4096];
  4067. let size = stream.read(&mut buffer).expect("read request");
  4068. let request = String::from_utf8_lossy(&buffer[..size]).into_owned();
  4069. let request_line = request.lines().next().unwrap_or_default().to_string();
  4070. let response = handler(&request_line);
  4071. stream
  4072. .write_all(response.to_bytes().as_slice())
  4073. .expect("write response");
  4074. }
  4075. Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
  4076. thread::sleep(Duration::from_millis(10));
  4077. }
  4078. Err(error) => panic!("server accept failed: {error}"),
  4079. }
  4080. });
  4081. Self {
  4082. addr,
  4083. shutdown: Some(tx),
  4084. handle: Some(handle),
  4085. }
  4086. }
  4087. fn addr(&self) -> SocketAddr {
  4088. self.addr
  4089. }
  4090. }
  4091. impl Drop for TestServer {
  4092. fn drop(&mut self) {
  4093. if let Some(tx) = self.shutdown.take() {
  4094. let _ = tx.send(());
  4095. }
  4096. if let Some(handle) = self.handle.take() {
  4097. handle.join().expect("join test server");
  4098. }
  4099. }
  4100. }
  4101. struct HttpResponse {
  4102. status: u16,
  4103. reason: &'static str,
  4104. content_type: &'static str,
  4105. body: String,
  4106. }
  4107. impl HttpResponse {
  4108. fn html(status: u16, reason: &'static str, body: &str) -> Self {
  4109. Self {
  4110. status,
  4111. reason,
  4112. content_type: "text/html; charset=utf-8",
  4113. body: body.to_string(),
  4114. }
  4115. }
  4116. fn text(status: u16, reason: &'static str, body: &str) -> Self {
  4117. Self {
  4118. status,
  4119. reason,
  4120. content_type: "text/plain; charset=utf-8",
  4121. body: body.to_string(),
  4122. }
  4123. }
  4124. fn to_bytes(&self) -> Vec<u8> {
  4125. format!(
  4126. "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
  4127. self.status,
  4128. self.reason,
  4129. self.content_type,
  4130. self.body.len(),
  4131. self.body
  4132. )
  4133. .into_bytes()
  4134. }
  4135. }
  4136. }