lib.rs 148 KB

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