lib.rs 154 KB

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