lib.rs 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248
  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. read_base_url, AnthropicClient, ContentBlockDelta, InputContentBlock, InputMessage,
  7. MessageRequest, MessageResponse, OutputContentBlock, StreamEvent as ApiStreamEvent, ToolChoice,
  8. 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. let in_progress = todos
  1166. .iter()
  1167. .filter(|todo| matches!(todo.status, TodoStatus::InProgress))
  1168. .count();
  1169. if in_progress > 1 {
  1170. return Err(String::from(
  1171. "exactly zero or one todo items may be in_progress",
  1172. ));
  1173. }
  1174. if todos.iter().any(|todo| todo.content.trim().is_empty()) {
  1175. return Err(String::from("todo content must not be empty"));
  1176. }
  1177. if todos.iter().any(|todo| todo.active_form.trim().is_empty()) {
  1178. return Err(String::from("todo activeForm must not be empty"));
  1179. }
  1180. Ok(())
  1181. }
  1182. fn todo_store_path() -> Result<std::path::PathBuf, String> {
  1183. if let Ok(path) = std::env::var("CLAWD_TODO_STORE") {
  1184. return Ok(std::path::PathBuf::from(path));
  1185. }
  1186. let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
  1187. Ok(cwd.join(".clawd-todos.json"))
  1188. }
  1189. fn resolve_skill_path(skill: &str) -> Result<std::path::PathBuf, String> {
  1190. let requested = skill.trim().trim_start_matches('/').trim_start_matches('$');
  1191. if requested.is_empty() {
  1192. return Err(String::from("skill must not be empty"));
  1193. }
  1194. let mut candidates = Vec::new();
  1195. if let Ok(codex_home) = std::env::var("CODEX_HOME") {
  1196. candidates.push(std::path::PathBuf::from(codex_home).join("skills"));
  1197. }
  1198. candidates.push(std::path::PathBuf::from("/home/bellman/.codex/skills"));
  1199. for root in candidates {
  1200. let direct = root.join(requested).join("SKILL.md");
  1201. if direct.exists() {
  1202. return Ok(direct);
  1203. }
  1204. if let Ok(entries) = std::fs::read_dir(&root) {
  1205. for entry in entries.flatten() {
  1206. let path = entry.path().join("SKILL.md");
  1207. if !path.exists() {
  1208. continue;
  1209. }
  1210. if entry
  1211. .file_name()
  1212. .to_string_lossy()
  1213. .eq_ignore_ascii_case(requested)
  1214. {
  1215. return Ok(path);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. Err(format!("unknown skill: {requested}"))
  1221. }
  1222. const DEFAULT_AGENT_MODEL: &str = "claude-opus-4-6";
  1223. const DEFAULT_AGENT_SYSTEM_DATE: &str = "2026-03-31";
  1224. const DEFAULT_AGENT_MAX_ITERATIONS: usize = 32;
  1225. fn execute_agent(input: AgentInput) -> Result<AgentOutput, String> {
  1226. execute_agent_with_spawn(input, spawn_agent_job)
  1227. }
  1228. fn execute_agent_with_spawn<F>(input: AgentInput, spawn_fn: F) -> Result<AgentOutput, String>
  1229. where
  1230. F: FnOnce(AgentJob) -> Result<(), String>,
  1231. {
  1232. if input.description.trim().is_empty() {
  1233. return Err(String::from("description must not be empty"));
  1234. }
  1235. if input.prompt.trim().is_empty() {
  1236. return Err(String::from("prompt must not be empty"));
  1237. }
  1238. let agent_id = make_agent_id();
  1239. let output_dir = agent_store_dir()?;
  1240. std::fs::create_dir_all(&output_dir).map_err(|error| error.to_string())?;
  1241. let output_file = output_dir.join(format!("{agent_id}.md"));
  1242. let manifest_file = output_dir.join(format!("{agent_id}.json"));
  1243. let normalized_subagent_type = normalize_subagent_type(input.subagent_type.as_deref());
  1244. let model = resolve_agent_model(input.model.as_deref());
  1245. let agent_name = input
  1246. .name
  1247. .as_deref()
  1248. .map(slugify_agent_name)
  1249. .filter(|name| !name.is_empty())
  1250. .unwrap_or_else(|| slugify_agent_name(&input.description));
  1251. let created_at = iso8601_now();
  1252. let system_prompt = build_agent_system_prompt(&normalized_subagent_type)?;
  1253. let allowed_tools = allowed_tools_for_subagent(&normalized_subagent_type);
  1254. let output_contents = format!(
  1255. "# Agent Task
  1256. - id: {}
  1257. - name: {}
  1258. - description: {}
  1259. - subagent_type: {}
  1260. - created_at: {}
  1261. ## Prompt
  1262. {}
  1263. ",
  1264. agent_id, agent_name, input.description, normalized_subagent_type, created_at, input.prompt
  1265. );
  1266. std::fs::write(&output_file, output_contents).map_err(|error| error.to_string())?;
  1267. let manifest = AgentOutput {
  1268. agent_id,
  1269. name: agent_name,
  1270. description: input.description,
  1271. subagent_type: Some(normalized_subagent_type),
  1272. model: Some(model),
  1273. status: String::from("running"),
  1274. output_file: output_file.display().to_string(),
  1275. manifest_file: manifest_file.display().to_string(),
  1276. created_at: created_at.clone(),
  1277. started_at: Some(created_at),
  1278. completed_at: None,
  1279. error: None,
  1280. };
  1281. write_agent_manifest(&manifest)?;
  1282. let manifest_for_spawn = manifest.clone();
  1283. let job = AgentJob {
  1284. manifest: manifest_for_spawn,
  1285. prompt: input.prompt,
  1286. system_prompt,
  1287. allowed_tools,
  1288. };
  1289. if let Err(error) = spawn_fn(job) {
  1290. let error = format!("failed to spawn sub-agent: {error}");
  1291. persist_agent_terminal_state(&manifest, "failed", None, Some(error.clone()))?;
  1292. return Err(error);
  1293. }
  1294. Ok(manifest)
  1295. }
  1296. fn spawn_agent_job(job: AgentJob) -> Result<(), String> {
  1297. let thread_name = format!("clawd-agent-{}", job.manifest.agent_id);
  1298. std::thread::Builder::new()
  1299. .name(thread_name)
  1300. .spawn(move || {
  1301. let result =
  1302. std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run_agent_job(&job)));
  1303. match result {
  1304. Ok(Ok(())) => {}
  1305. Ok(Err(error)) => {
  1306. let _ =
  1307. persist_agent_terminal_state(&job.manifest, "failed", None, Some(error));
  1308. }
  1309. Err(_) => {
  1310. let _ = persist_agent_terminal_state(
  1311. &job.manifest,
  1312. "failed",
  1313. None,
  1314. Some(String::from("sub-agent thread panicked")),
  1315. );
  1316. }
  1317. }
  1318. })
  1319. .map(|_| ())
  1320. .map_err(|error| error.to_string())
  1321. }
  1322. fn run_agent_job(job: &AgentJob) -> Result<(), String> {
  1323. let mut runtime = build_agent_runtime(job)?.with_max_iterations(DEFAULT_AGENT_MAX_ITERATIONS);
  1324. let summary = runtime
  1325. .run_turn(job.prompt.clone(), None)
  1326. .map_err(|error| error.to_string())?;
  1327. let final_text = final_assistant_text(&summary);
  1328. persist_agent_terminal_state(&job.manifest, "completed", Some(final_text.as_str()), None)
  1329. }
  1330. fn build_agent_runtime(
  1331. job: &AgentJob,
  1332. ) -> Result<ConversationRuntime<AnthropicRuntimeClient, SubagentToolExecutor>, String> {
  1333. let model = job
  1334. .manifest
  1335. .model
  1336. .clone()
  1337. .unwrap_or_else(|| DEFAULT_AGENT_MODEL.to_string());
  1338. let allowed_tools = job.allowed_tools.clone();
  1339. let api_client = AnthropicRuntimeClient::new(model, allowed_tools.clone())?;
  1340. let tool_executor = SubagentToolExecutor::new(allowed_tools);
  1341. Ok(ConversationRuntime::new(
  1342. Session::new(),
  1343. api_client,
  1344. tool_executor,
  1345. agent_permission_policy(),
  1346. job.system_prompt.clone(),
  1347. ))
  1348. }
  1349. fn build_agent_system_prompt(subagent_type: &str) -> Result<Vec<String>, String> {
  1350. let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
  1351. let mut prompt = load_system_prompt(
  1352. cwd,
  1353. DEFAULT_AGENT_SYSTEM_DATE.to_string(),
  1354. std::env::consts::OS,
  1355. "unknown",
  1356. )
  1357. .map_err(|error| error.to_string())?;
  1358. prompt.push(format!(
  1359. "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."
  1360. ));
  1361. Ok(prompt)
  1362. }
  1363. fn resolve_agent_model(model: Option<&str>) -> String {
  1364. model
  1365. .map(str::trim)
  1366. .filter(|model| !model.is_empty())
  1367. .unwrap_or(DEFAULT_AGENT_MODEL)
  1368. .to_string()
  1369. }
  1370. fn allowed_tools_for_subagent(subagent_type: &str) -> BTreeSet<String> {
  1371. let tools = match subagent_type {
  1372. "Explore" => vec![
  1373. "read_file",
  1374. "glob_search",
  1375. "grep_search",
  1376. "WebFetch",
  1377. "WebSearch",
  1378. "ToolSearch",
  1379. "Skill",
  1380. "StructuredOutput",
  1381. ],
  1382. "Plan" => vec![
  1383. "read_file",
  1384. "glob_search",
  1385. "grep_search",
  1386. "WebFetch",
  1387. "WebSearch",
  1388. "ToolSearch",
  1389. "Skill",
  1390. "TodoWrite",
  1391. "StructuredOutput",
  1392. "SendUserMessage",
  1393. ],
  1394. "Verification" => vec![
  1395. "bash",
  1396. "read_file",
  1397. "glob_search",
  1398. "grep_search",
  1399. "WebFetch",
  1400. "WebSearch",
  1401. "ToolSearch",
  1402. "TodoWrite",
  1403. "StructuredOutput",
  1404. "SendUserMessage",
  1405. "PowerShell",
  1406. ],
  1407. "claude-code-guide" => vec![
  1408. "read_file",
  1409. "glob_search",
  1410. "grep_search",
  1411. "WebFetch",
  1412. "WebSearch",
  1413. "ToolSearch",
  1414. "Skill",
  1415. "StructuredOutput",
  1416. "SendUserMessage",
  1417. ],
  1418. "statusline-setup" => vec![
  1419. "bash",
  1420. "read_file",
  1421. "write_file",
  1422. "edit_file",
  1423. "glob_search",
  1424. "grep_search",
  1425. "ToolSearch",
  1426. ],
  1427. _ => vec![
  1428. "bash",
  1429. "read_file",
  1430. "write_file",
  1431. "edit_file",
  1432. "glob_search",
  1433. "grep_search",
  1434. "WebFetch",
  1435. "WebSearch",
  1436. "TodoWrite",
  1437. "Skill",
  1438. "ToolSearch",
  1439. "NotebookEdit",
  1440. "Sleep",
  1441. "SendUserMessage",
  1442. "Config",
  1443. "StructuredOutput",
  1444. "REPL",
  1445. "PowerShell",
  1446. ],
  1447. };
  1448. tools.into_iter().map(str::to_string).collect()
  1449. }
  1450. fn agent_permission_policy() -> PermissionPolicy {
  1451. mvp_tool_specs().into_iter().fold(
  1452. PermissionPolicy::new(PermissionMode::DangerFullAccess),
  1453. |policy, spec| policy.with_tool_requirement(spec.name, spec.required_permission),
  1454. )
  1455. }
  1456. fn write_agent_manifest(manifest: &AgentOutput) -> Result<(), String> {
  1457. std::fs::write(
  1458. &manifest.manifest_file,
  1459. serde_json::to_string_pretty(manifest).map_err(|error| error.to_string())?,
  1460. )
  1461. .map_err(|error| error.to_string())
  1462. }
  1463. fn persist_agent_terminal_state(
  1464. manifest: &AgentOutput,
  1465. status: &str,
  1466. result: Option<&str>,
  1467. error: Option<String>,
  1468. ) -> Result<(), String> {
  1469. append_agent_output(
  1470. &manifest.output_file,
  1471. &format_agent_terminal_output(status, result, error.as_deref()),
  1472. )?;
  1473. let mut next_manifest = manifest.clone();
  1474. next_manifest.status = status.to_string();
  1475. next_manifest.completed_at = Some(iso8601_now());
  1476. next_manifest.error = error;
  1477. write_agent_manifest(&next_manifest)
  1478. }
  1479. fn append_agent_output(path: &str, suffix: &str) -> Result<(), String> {
  1480. use std::io::Write as _;
  1481. let mut file = std::fs::OpenOptions::new()
  1482. .append(true)
  1483. .open(path)
  1484. .map_err(|error| error.to_string())?;
  1485. file.write_all(suffix.as_bytes())
  1486. .map_err(|error| error.to_string())
  1487. }
  1488. fn format_agent_terminal_output(status: &str, result: Option<&str>, error: Option<&str>) -> String {
  1489. let mut sections = vec![format!("\n## Result\n\n- status: {status}\n")];
  1490. if let Some(result) = result.filter(|value| !value.trim().is_empty()) {
  1491. sections.push(format!("\n### Final response\n\n{}\n", result.trim()));
  1492. }
  1493. if let Some(error) = error.filter(|value| !value.trim().is_empty()) {
  1494. sections.push(format!("\n### Error\n\n{}\n", error.trim()));
  1495. }
  1496. sections.join("")
  1497. }
  1498. struct AnthropicRuntimeClient {
  1499. runtime: tokio::runtime::Runtime,
  1500. client: AnthropicClient,
  1501. model: String,
  1502. allowed_tools: BTreeSet<String>,
  1503. }
  1504. impl AnthropicRuntimeClient {
  1505. fn new(model: String, allowed_tools: BTreeSet<String>) -> Result<Self, String> {
  1506. let client = AnthropicClient::from_env()
  1507. .map_err(|error| error.to_string())?
  1508. .with_base_url(read_base_url());
  1509. Ok(Self {
  1510. runtime: tokio::runtime::Runtime::new().map_err(|error| error.to_string())?,
  1511. client,
  1512. model,
  1513. allowed_tools,
  1514. })
  1515. }
  1516. }
  1517. impl ApiClient for AnthropicRuntimeClient {
  1518. fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
  1519. let tools = tool_specs_for_allowed_tools(Some(&self.allowed_tools))
  1520. .into_iter()
  1521. .map(|spec| ToolDefinition {
  1522. name: spec.name.to_string(),
  1523. description: Some(spec.description.to_string()),
  1524. input_schema: spec.input_schema,
  1525. })
  1526. .collect::<Vec<_>>();
  1527. let message_request = MessageRequest {
  1528. model: self.model.clone(),
  1529. max_tokens: 32_000,
  1530. messages: convert_messages(&request.messages),
  1531. system: (!request.system_prompt.is_empty()).then(|| request.system_prompt.join("\n\n")),
  1532. tools: (!tools.is_empty()).then_some(tools),
  1533. tool_choice: (!self.allowed_tools.is_empty()).then_some(ToolChoice::Auto),
  1534. stream: true,
  1535. };
  1536. self.runtime.block_on(async {
  1537. let mut stream = self
  1538. .client
  1539. .stream_message(&message_request)
  1540. .await
  1541. .map_err(|error| RuntimeError::new(error.to_string()))?;
  1542. let mut events = Vec::new();
  1543. let mut pending_tool: Option<(String, String, String)> = None;
  1544. let mut saw_stop = false;
  1545. while let Some(event) = stream
  1546. .next_event()
  1547. .await
  1548. .map_err(|error| RuntimeError::new(error.to_string()))?
  1549. {
  1550. match event {
  1551. ApiStreamEvent::MessageStart(start) => {
  1552. for block in start.message.content {
  1553. push_output_block(block, &mut events, &mut pending_tool, true);
  1554. }
  1555. }
  1556. ApiStreamEvent::ContentBlockStart(start) => {
  1557. push_output_block(
  1558. start.content_block,
  1559. &mut events,
  1560. &mut pending_tool,
  1561. true,
  1562. );
  1563. }
  1564. ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
  1565. ContentBlockDelta::TextDelta { text } => {
  1566. if !text.is_empty() {
  1567. events.push(AssistantEvent::TextDelta(text));
  1568. }
  1569. }
  1570. ContentBlockDelta::InputJsonDelta { partial_json } => {
  1571. if let Some((_, _, input)) = &mut pending_tool {
  1572. input.push_str(&partial_json);
  1573. }
  1574. }
  1575. },
  1576. ApiStreamEvent::ContentBlockStop(_) => {
  1577. if let Some((id, name, input)) = pending_tool.take() {
  1578. events.push(AssistantEvent::ToolUse { id, name, input });
  1579. }
  1580. }
  1581. ApiStreamEvent::MessageDelta(delta) => {
  1582. events.push(AssistantEvent::Usage(TokenUsage {
  1583. input_tokens: delta.usage.input_tokens,
  1584. output_tokens: delta.usage.output_tokens,
  1585. cache_creation_input_tokens: 0,
  1586. cache_read_input_tokens: 0,
  1587. }));
  1588. }
  1589. ApiStreamEvent::MessageStop(_) => {
  1590. saw_stop = true;
  1591. events.push(AssistantEvent::MessageStop);
  1592. }
  1593. }
  1594. }
  1595. if !saw_stop
  1596. && events.iter().any(|event| {
  1597. matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty())
  1598. || matches!(event, AssistantEvent::ToolUse { .. })
  1599. })
  1600. {
  1601. events.push(AssistantEvent::MessageStop);
  1602. }
  1603. if events
  1604. .iter()
  1605. .any(|event| matches!(event, AssistantEvent::MessageStop))
  1606. {
  1607. return Ok(events);
  1608. }
  1609. let response = self
  1610. .client
  1611. .send_message(&MessageRequest {
  1612. stream: false,
  1613. ..message_request.clone()
  1614. })
  1615. .await
  1616. .map_err(|error| RuntimeError::new(error.to_string()))?;
  1617. Ok(response_to_events(response))
  1618. })
  1619. }
  1620. }
  1621. struct SubagentToolExecutor {
  1622. allowed_tools: BTreeSet<String>,
  1623. }
  1624. impl SubagentToolExecutor {
  1625. fn new(allowed_tools: BTreeSet<String>) -> Self {
  1626. Self { allowed_tools }
  1627. }
  1628. }
  1629. impl ToolExecutor for SubagentToolExecutor {
  1630. fn execute(&mut self, tool_name: &str, input: &str) -> Result<String, ToolError> {
  1631. if !self.allowed_tools.contains(tool_name) {
  1632. return Err(ToolError::new(format!(
  1633. "tool `{tool_name}` is not enabled for this sub-agent"
  1634. )));
  1635. }
  1636. let value = serde_json::from_str(input)
  1637. .map_err(|error| ToolError::new(format!("invalid tool input JSON: {error}")))?;
  1638. execute_tool(tool_name, &value).map_err(ToolError::new)
  1639. }
  1640. }
  1641. fn tool_specs_for_allowed_tools(allowed_tools: Option<&BTreeSet<String>>) -> Vec<ToolSpec> {
  1642. mvp_tool_specs()
  1643. .into_iter()
  1644. .filter(|spec| allowed_tools.is_none_or(|allowed| allowed.contains(spec.name)))
  1645. .collect()
  1646. }
  1647. fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
  1648. messages
  1649. .iter()
  1650. .filter_map(|message| {
  1651. let role = match message.role {
  1652. MessageRole::System | MessageRole::User | MessageRole::Tool => "user",
  1653. MessageRole::Assistant => "assistant",
  1654. };
  1655. let content = message
  1656. .blocks
  1657. .iter()
  1658. .map(|block| match block {
  1659. ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
  1660. ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
  1661. id: id.clone(),
  1662. name: name.clone(),
  1663. input: serde_json::from_str(input)
  1664. .unwrap_or_else(|_| serde_json::json!({ "raw": input })),
  1665. },
  1666. ContentBlock::ToolResult {
  1667. tool_use_id,
  1668. output,
  1669. is_error,
  1670. ..
  1671. } => InputContentBlock::ToolResult {
  1672. tool_use_id: tool_use_id.clone(),
  1673. content: vec![ToolResultContentBlock::Text {
  1674. text: output.clone(),
  1675. }],
  1676. is_error: *is_error,
  1677. },
  1678. })
  1679. .collect::<Vec<_>>();
  1680. (!content.is_empty()).then(|| InputMessage {
  1681. role: role.to_string(),
  1682. content,
  1683. })
  1684. })
  1685. .collect()
  1686. }
  1687. fn push_output_block(
  1688. block: OutputContentBlock,
  1689. events: &mut Vec<AssistantEvent>,
  1690. pending_tool: &mut Option<(String, String, String)>,
  1691. streaming_tool_input: bool,
  1692. ) {
  1693. match block {
  1694. OutputContentBlock::Text { text } => {
  1695. if !text.is_empty() {
  1696. events.push(AssistantEvent::TextDelta(text));
  1697. }
  1698. }
  1699. OutputContentBlock::ToolUse { id, name, input } => {
  1700. let initial_input = if streaming_tool_input
  1701. && input.is_object()
  1702. && input.as_object().is_some_and(serde_json::Map::is_empty)
  1703. {
  1704. String::new()
  1705. } else {
  1706. input.to_string()
  1707. };
  1708. *pending_tool = Some((id, name, initial_input));
  1709. }
  1710. }
  1711. }
  1712. fn response_to_events(response: MessageResponse) -> Vec<AssistantEvent> {
  1713. let mut events = Vec::new();
  1714. let mut pending_tool = None;
  1715. for block in response.content {
  1716. push_output_block(block, &mut events, &mut pending_tool, false);
  1717. if let Some((id, name, input)) = pending_tool.take() {
  1718. events.push(AssistantEvent::ToolUse { id, name, input });
  1719. }
  1720. }
  1721. events.push(AssistantEvent::Usage(TokenUsage {
  1722. input_tokens: response.usage.input_tokens,
  1723. output_tokens: response.usage.output_tokens,
  1724. cache_creation_input_tokens: response.usage.cache_creation_input_tokens,
  1725. cache_read_input_tokens: response.usage.cache_read_input_tokens,
  1726. }));
  1727. events.push(AssistantEvent::MessageStop);
  1728. events
  1729. }
  1730. fn final_assistant_text(summary: &runtime::TurnSummary) -> String {
  1731. summary
  1732. .assistant_messages
  1733. .last()
  1734. .map(|message| {
  1735. message
  1736. .blocks
  1737. .iter()
  1738. .filter_map(|block| match block {
  1739. ContentBlock::Text { text } => Some(text.as_str()),
  1740. _ => None,
  1741. })
  1742. .collect::<Vec<_>>()
  1743. .join("")
  1744. })
  1745. .unwrap_or_default()
  1746. }
  1747. #[allow(clippy::needless_pass_by_value)]
  1748. fn execute_tool_search(input: ToolSearchInput) -> ToolSearchOutput {
  1749. let deferred = deferred_tool_specs();
  1750. let max_results = input.max_results.unwrap_or(5).max(1);
  1751. let query = input.query.trim().to_string();
  1752. let normalized_query = normalize_tool_search_query(&query);
  1753. let matches = search_tool_specs(&query, max_results, &deferred);
  1754. ToolSearchOutput {
  1755. matches,
  1756. query,
  1757. normalized_query,
  1758. total_deferred_tools: deferred.len(),
  1759. pending_mcp_servers: None,
  1760. }
  1761. }
  1762. fn deferred_tool_specs() -> Vec<ToolSpec> {
  1763. mvp_tool_specs()
  1764. .into_iter()
  1765. .filter(|spec| {
  1766. !matches!(
  1767. spec.name,
  1768. "bash" | "read_file" | "write_file" | "edit_file" | "glob_search" | "grep_search"
  1769. )
  1770. })
  1771. .collect()
  1772. }
  1773. fn search_tool_specs(query: &str, max_results: usize, specs: &[ToolSpec]) -> Vec<String> {
  1774. let lowered = query.to_lowercase();
  1775. if let Some(selection) = lowered.strip_prefix("select:") {
  1776. return selection
  1777. .split(',')
  1778. .map(str::trim)
  1779. .filter(|part| !part.is_empty())
  1780. .filter_map(|wanted| {
  1781. let wanted = canonical_tool_token(wanted);
  1782. specs
  1783. .iter()
  1784. .find(|spec| canonical_tool_token(spec.name) == wanted)
  1785. .map(|spec| spec.name.to_string())
  1786. })
  1787. .take(max_results)
  1788. .collect();
  1789. }
  1790. let mut required = Vec::new();
  1791. let mut optional = Vec::new();
  1792. for term in lowered.split_whitespace() {
  1793. if let Some(rest) = term.strip_prefix('+') {
  1794. if !rest.is_empty() {
  1795. required.push(rest);
  1796. }
  1797. } else {
  1798. optional.push(term);
  1799. }
  1800. }
  1801. let terms = if required.is_empty() {
  1802. optional.clone()
  1803. } else {
  1804. required.iter().chain(optional.iter()).copied().collect()
  1805. };
  1806. let mut scored = specs
  1807. .iter()
  1808. .filter_map(|spec| {
  1809. let name = spec.name.to_lowercase();
  1810. let canonical_name = canonical_tool_token(spec.name);
  1811. let normalized_description = normalize_tool_search_query(spec.description);
  1812. let haystack = format!(
  1813. "{name} {} {canonical_name}",
  1814. spec.description.to_lowercase()
  1815. );
  1816. let normalized_haystack = format!("{canonical_name} {normalized_description}");
  1817. if required.iter().any(|term| !haystack.contains(term)) {
  1818. return None;
  1819. }
  1820. let mut score = 0_i32;
  1821. for term in &terms {
  1822. let canonical_term = canonical_tool_token(term);
  1823. if haystack.contains(term) {
  1824. score += 2;
  1825. }
  1826. if name == *term {
  1827. score += 8;
  1828. }
  1829. if name.contains(term) {
  1830. score += 4;
  1831. }
  1832. if canonical_name == canonical_term {
  1833. score += 12;
  1834. }
  1835. if normalized_haystack.contains(&canonical_term) {
  1836. score += 3;
  1837. }
  1838. }
  1839. if score == 0 && !lowered.is_empty() {
  1840. return None;
  1841. }
  1842. Some((score, spec.name.to_string()))
  1843. })
  1844. .collect::<Vec<_>>();
  1845. scored.sort_by(|left, right| right.0.cmp(&left.0).then_with(|| left.1.cmp(&right.1)));
  1846. scored
  1847. .into_iter()
  1848. .map(|(_, name)| name)
  1849. .take(max_results)
  1850. .collect()
  1851. }
  1852. fn normalize_tool_search_query(query: &str) -> String {
  1853. query
  1854. .trim()
  1855. .split(|ch: char| ch.is_whitespace() || ch == ',')
  1856. .filter(|term| !term.is_empty())
  1857. .map(canonical_tool_token)
  1858. .collect::<Vec<_>>()
  1859. .join(" ")
  1860. }
  1861. fn canonical_tool_token(value: &str) -> String {
  1862. let mut canonical = value
  1863. .chars()
  1864. .filter(char::is_ascii_alphanumeric)
  1865. .flat_map(char::to_lowercase)
  1866. .collect::<String>();
  1867. if let Some(stripped) = canonical.strip_suffix("tool") {
  1868. canonical = stripped.to_string();
  1869. }
  1870. canonical
  1871. }
  1872. fn agent_store_dir() -> Result<std::path::PathBuf, String> {
  1873. if let Ok(path) = std::env::var("CLAWD_AGENT_STORE") {
  1874. return Ok(std::path::PathBuf::from(path));
  1875. }
  1876. let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
  1877. if let Some(workspace_root) = cwd.ancestors().nth(2) {
  1878. return Ok(workspace_root.join(".clawd-agents"));
  1879. }
  1880. Ok(cwd.join(".clawd-agents"))
  1881. }
  1882. fn make_agent_id() -> String {
  1883. let nanos = std::time::SystemTime::now()
  1884. .duration_since(std::time::UNIX_EPOCH)
  1885. .unwrap_or_default()
  1886. .as_nanos();
  1887. format!("agent-{nanos}")
  1888. }
  1889. fn slugify_agent_name(description: &str) -> String {
  1890. let mut out = description
  1891. .chars()
  1892. .map(|ch| {
  1893. if ch.is_ascii_alphanumeric() {
  1894. ch.to_ascii_lowercase()
  1895. } else {
  1896. '-'
  1897. }
  1898. })
  1899. .collect::<String>();
  1900. while out.contains("--") {
  1901. out = out.replace("--", "-");
  1902. }
  1903. out.trim_matches('-').chars().take(32).collect()
  1904. }
  1905. fn normalize_subagent_type(subagent_type: Option<&str>) -> String {
  1906. let trimmed = subagent_type.map(str::trim).unwrap_or_default();
  1907. if trimmed.is_empty() {
  1908. return String::from("general-purpose");
  1909. }
  1910. match canonical_tool_token(trimmed).as_str() {
  1911. "general" | "generalpurpose" | "generalpurposeagent" => String::from("general-purpose"),
  1912. "explore" | "explorer" | "exploreagent" => String::from("Explore"),
  1913. "plan" | "planagent" => String::from("Plan"),
  1914. "verification" | "verificationagent" | "verify" | "verifier" => {
  1915. String::from("Verification")
  1916. }
  1917. "claudecodeguide" | "claudecodeguideagent" | "guide" => String::from("claude-code-guide"),
  1918. "statusline" | "statuslinesetup" => String::from("statusline-setup"),
  1919. _ => trimmed.to_string(),
  1920. }
  1921. }
  1922. fn iso8601_now() -> String {
  1923. std::time::SystemTime::now()
  1924. .duration_since(std::time::UNIX_EPOCH)
  1925. .unwrap_or_default()
  1926. .as_secs()
  1927. .to_string()
  1928. }
  1929. #[allow(clippy::too_many_lines)]
  1930. fn execute_notebook_edit(input: NotebookEditInput) -> Result<NotebookEditOutput, String> {
  1931. let path = std::path::PathBuf::from(&input.notebook_path);
  1932. if path.extension().and_then(|ext| ext.to_str()) != Some("ipynb") {
  1933. return Err(String::from(
  1934. "File must be a Jupyter notebook (.ipynb file).",
  1935. ));
  1936. }
  1937. let original_file = std::fs::read_to_string(&path).map_err(|error| error.to_string())?;
  1938. let mut notebook: serde_json::Value =
  1939. serde_json::from_str(&original_file).map_err(|error| error.to_string())?;
  1940. let language = notebook
  1941. .get("metadata")
  1942. .and_then(|metadata| metadata.get("kernelspec"))
  1943. .and_then(|kernelspec| kernelspec.get("language"))
  1944. .and_then(serde_json::Value::as_str)
  1945. .unwrap_or("python")
  1946. .to_string();
  1947. let cells = notebook
  1948. .get_mut("cells")
  1949. .and_then(serde_json::Value::as_array_mut)
  1950. .ok_or_else(|| String::from("Notebook cells array not found"))?;
  1951. let edit_mode = input.edit_mode.unwrap_or(NotebookEditMode::Replace);
  1952. let target_index = match input.cell_id.as_deref() {
  1953. Some(cell_id) => Some(resolve_cell_index(cells, Some(cell_id), edit_mode)?),
  1954. None if matches!(
  1955. edit_mode,
  1956. NotebookEditMode::Replace | NotebookEditMode::Delete
  1957. ) =>
  1958. {
  1959. Some(resolve_cell_index(cells, None, edit_mode)?)
  1960. }
  1961. None => None,
  1962. };
  1963. let resolved_cell_type = match edit_mode {
  1964. NotebookEditMode::Delete => None,
  1965. NotebookEditMode::Insert => Some(input.cell_type.unwrap_or(NotebookCellType::Code)),
  1966. NotebookEditMode::Replace => Some(input.cell_type.unwrap_or_else(|| {
  1967. target_index
  1968. .and_then(|index| cells.get(index))
  1969. .and_then(cell_kind)
  1970. .unwrap_or(NotebookCellType::Code)
  1971. })),
  1972. };
  1973. let new_source = require_notebook_source(input.new_source, edit_mode)?;
  1974. let cell_id = match edit_mode {
  1975. NotebookEditMode::Insert => {
  1976. let resolved_cell_type = resolved_cell_type.expect("insert cell type");
  1977. let new_id = make_cell_id(cells.len());
  1978. let new_cell = build_notebook_cell(&new_id, resolved_cell_type, &new_source);
  1979. let insert_at = target_index.map_or(cells.len(), |index| index + 1);
  1980. cells.insert(insert_at, new_cell);
  1981. cells
  1982. .get(insert_at)
  1983. .and_then(|cell| cell.get("id"))
  1984. .and_then(serde_json::Value::as_str)
  1985. .map(ToString::to_string)
  1986. }
  1987. NotebookEditMode::Delete => {
  1988. let removed = cells.remove(target_index.expect("delete target index"));
  1989. removed
  1990. .get("id")
  1991. .and_then(serde_json::Value::as_str)
  1992. .map(ToString::to_string)
  1993. }
  1994. NotebookEditMode::Replace => {
  1995. let resolved_cell_type = resolved_cell_type.expect("replace cell type");
  1996. let cell = cells
  1997. .get_mut(target_index.expect("replace target index"))
  1998. .ok_or_else(|| String::from("Cell index out of range"))?;
  1999. cell["source"] = serde_json::Value::Array(source_lines(&new_source));
  2000. cell["cell_type"] = serde_json::Value::String(match resolved_cell_type {
  2001. NotebookCellType::Code => String::from("code"),
  2002. NotebookCellType::Markdown => String::from("markdown"),
  2003. });
  2004. match resolved_cell_type {
  2005. NotebookCellType::Code => {
  2006. if !cell.get("outputs").is_some_and(serde_json::Value::is_array) {
  2007. cell["outputs"] = json!([]);
  2008. }
  2009. if cell.get("execution_count").is_none() {
  2010. cell["execution_count"] = serde_json::Value::Null;
  2011. }
  2012. }
  2013. NotebookCellType::Markdown => {
  2014. if let Some(object) = cell.as_object_mut() {
  2015. object.remove("outputs");
  2016. object.remove("execution_count");
  2017. }
  2018. }
  2019. }
  2020. cell.get("id")
  2021. .and_then(serde_json::Value::as_str)
  2022. .map(ToString::to_string)
  2023. }
  2024. };
  2025. let updated_file =
  2026. serde_json::to_string_pretty(&notebook).map_err(|error| error.to_string())?;
  2027. std::fs::write(&path, &updated_file).map_err(|error| error.to_string())?;
  2028. Ok(NotebookEditOutput {
  2029. new_source,
  2030. cell_id,
  2031. cell_type: resolved_cell_type,
  2032. language,
  2033. edit_mode: format_notebook_edit_mode(edit_mode),
  2034. error: None,
  2035. notebook_path: path.display().to_string(),
  2036. original_file,
  2037. updated_file,
  2038. })
  2039. }
  2040. fn require_notebook_source(
  2041. source: Option<String>,
  2042. edit_mode: NotebookEditMode,
  2043. ) -> Result<String, String> {
  2044. match edit_mode {
  2045. NotebookEditMode::Delete => Ok(source.unwrap_or_default()),
  2046. NotebookEditMode::Insert | NotebookEditMode::Replace => source
  2047. .ok_or_else(|| String::from("new_source is required for insert and replace edits")),
  2048. }
  2049. }
  2050. fn build_notebook_cell(cell_id: &str, cell_type: NotebookCellType, source: &str) -> Value {
  2051. let mut cell = json!({
  2052. "cell_type": match cell_type {
  2053. NotebookCellType::Code => "code",
  2054. NotebookCellType::Markdown => "markdown",
  2055. },
  2056. "id": cell_id,
  2057. "metadata": {},
  2058. "source": source_lines(source),
  2059. });
  2060. if let Some(object) = cell.as_object_mut() {
  2061. match cell_type {
  2062. NotebookCellType::Code => {
  2063. object.insert(String::from("outputs"), json!([]));
  2064. object.insert(String::from("execution_count"), Value::Null);
  2065. }
  2066. NotebookCellType::Markdown => {}
  2067. }
  2068. }
  2069. cell
  2070. }
  2071. fn cell_kind(cell: &serde_json::Value) -> Option<NotebookCellType> {
  2072. cell.get("cell_type")
  2073. .and_then(serde_json::Value::as_str)
  2074. .map(|kind| {
  2075. if kind == "markdown" {
  2076. NotebookCellType::Markdown
  2077. } else {
  2078. NotebookCellType::Code
  2079. }
  2080. })
  2081. }
  2082. #[allow(clippy::needless_pass_by_value)]
  2083. fn execute_sleep(input: SleepInput) -> SleepOutput {
  2084. std::thread::sleep(Duration::from_millis(input.duration_ms));
  2085. SleepOutput {
  2086. duration_ms: input.duration_ms,
  2087. message: format!("Slept for {}ms", input.duration_ms),
  2088. }
  2089. }
  2090. fn execute_brief(input: BriefInput) -> Result<BriefOutput, String> {
  2091. if input.message.trim().is_empty() {
  2092. return Err(String::from("message must not be empty"));
  2093. }
  2094. let attachments = input
  2095. .attachments
  2096. .as_ref()
  2097. .map(|paths| {
  2098. paths
  2099. .iter()
  2100. .map(|path| resolve_attachment(path))
  2101. .collect::<Result<Vec<_>, String>>()
  2102. })
  2103. .transpose()?;
  2104. let message = match input.status {
  2105. BriefStatus::Normal | BriefStatus::Proactive => input.message,
  2106. };
  2107. Ok(BriefOutput {
  2108. message,
  2109. attachments,
  2110. sent_at: iso8601_timestamp(),
  2111. })
  2112. }
  2113. fn resolve_attachment(path: &str) -> Result<ResolvedAttachment, String> {
  2114. let resolved = std::fs::canonicalize(path).map_err(|error| error.to_string())?;
  2115. let metadata = std::fs::metadata(&resolved).map_err(|error| error.to_string())?;
  2116. Ok(ResolvedAttachment {
  2117. path: resolved.display().to_string(),
  2118. size: metadata.len(),
  2119. is_image: is_image_path(&resolved),
  2120. })
  2121. }
  2122. fn is_image_path(path: &Path) -> bool {
  2123. matches!(
  2124. path.extension()
  2125. .and_then(|ext| ext.to_str())
  2126. .map(str::to_ascii_lowercase)
  2127. .as_deref(),
  2128. Some("png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "svg")
  2129. )
  2130. }
  2131. fn execute_config(input: ConfigInput) -> Result<ConfigOutput, String> {
  2132. let setting = input.setting.trim();
  2133. if setting.is_empty() {
  2134. return Err(String::from("setting must not be empty"));
  2135. }
  2136. let Some(spec) = supported_config_setting(setting) else {
  2137. return Ok(ConfigOutput {
  2138. success: false,
  2139. operation: None,
  2140. setting: None,
  2141. value: None,
  2142. previous_value: None,
  2143. new_value: None,
  2144. error: Some(format!("Unknown setting: \"{setting}\"")),
  2145. });
  2146. };
  2147. let path = config_file_for_scope(spec.scope)?;
  2148. let mut document = read_json_object(&path)?;
  2149. if let Some(value) = input.value {
  2150. let normalized = normalize_config_value(spec, value)?;
  2151. let previous_value = get_nested_value(&document, spec.path).cloned();
  2152. set_nested_value(&mut document, spec.path, normalized.clone());
  2153. write_json_object(&path, &document)?;
  2154. Ok(ConfigOutput {
  2155. success: true,
  2156. operation: Some(String::from("set")),
  2157. setting: Some(setting.to_string()),
  2158. value: Some(normalized.clone()),
  2159. previous_value,
  2160. new_value: Some(normalized),
  2161. error: None,
  2162. })
  2163. } else {
  2164. Ok(ConfigOutput {
  2165. success: true,
  2166. operation: Some(String::from("get")),
  2167. setting: Some(setting.to_string()),
  2168. value: get_nested_value(&document, spec.path).cloned(),
  2169. previous_value: None,
  2170. new_value: None,
  2171. error: None,
  2172. })
  2173. }
  2174. }
  2175. fn execute_structured_output(input: StructuredOutputInput) -> StructuredOutputResult {
  2176. StructuredOutputResult {
  2177. data: String::from("Structured output provided successfully"),
  2178. structured_output: input.0,
  2179. }
  2180. }
  2181. fn execute_repl(input: ReplInput) -> Result<ReplOutput, String> {
  2182. if input.code.trim().is_empty() {
  2183. return Err(String::from("code must not be empty"));
  2184. }
  2185. let _ = input.timeout_ms;
  2186. let runtime = resolve_repl_runtime(&input.language)?;
  2187. let started = Instant::now();
  2188. let output = Command::new(runtime.program)
  2189. .args(runtime.args)
  2190. .arg(&input.code)
  2191. .output()
  2192. .map_err(|error| error.to_string())?;
  2193. Ok(ReplOutput {
  2194. language: input.language,
  2195. stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
  2196. stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
  2197. exit_code: output.status.code().unwrap_or(1),
  2198. duration_ms: started.elapsed().as_millis(),
  2199. })
  2200. }
  2201. struct ReplRuntime {
  2202. program: &'static str,
  2203. args: &'static [&'static str],
  2204. }
  2205. fn resolve_repl_runtime(language: &str) -> Result<ReplRuntime, String> {
  2206. match language.trim().to_ascii_lowercase().as_str() {
  2207. "python" | "py" => Ok(ReplRuntime {
  2208. program: detect_first_command(&["python3", "python"])
  2209. .ok_or_else(|| String::from("python runtime not found"))?,
  2210. args: &["-c"],
  2211. }),
  2212. "javascript" | "js" | "node" => Ok(ReplRuntime {
  2213. program: detect_first_command(&["node"])
  2214. .ok_or_else(|| String::from("node runtime not found"))?,
  2215. args: &["-e"],
  2216. }),
  2217. "sh" | "shell" | "bash" => Ok(ReplRuntime {
  2218. program: detect_first_command(&["bash", "sh"])
  2219. .ok_or_else(|| String::from("shell runtime not found"))?,
  2220. args: &["-lc"],
  2221. }),
  2222. other => Err(format!("unsupported REPL language: {other}")),
  2223. }
  2224. }
  2225. fn detect_first_command(commands: &[&'static str]) -> Option<&'static str> {
  2226. commands
  2227. .iter()
  2228. .copied()
  2229. .find(|command| command_exists(command))
  2230. }
  2231. #[derive(Clone, Copy)]
  2232. enum ConfigScope {
  2233. Global,
  2234. Settings,
  2235. }
  2236. #[derive(Clone, Copy)]
  2237. struct ConfigSettingSpec {
  2238. scope: ConfigScope,
  2239. kind: ConfigKind,
  2240. path: &'static [&'static str],
  2241. options: Option<&'static [&'static str]>,
  2242. }
  2243. #[derive(Clone, Copy)]
  2244. enum ConfigKind {
  2245. Boolean,
  2246. String,
  2247. }
  2248. fn supported_config_setting(setting: &str) -> Option<ConfigSettingSpec> {
  2249. Some(match setting {
  2250. "theme" => ConfigSettingSpec {
  2251. scope: ConfigScope::Global,
  2252. kind: ConfigKind::String,
  2253. path: &["theme"],
  2254. options: None,
  2255. },
  2256. "editorMode" => ConfigSettingSpec {
  2257. scope: ConfigScope::Global,
  2258. kind: ConfigKind::String,
  2259. path: &["editorMode"],
  2260. options: Some(&["default", "vim", "emacs"]),
  2261. },
  2262. "verbose" => ConfigSettingSpec {
  2263. scope: ConfigScope::Global,
  2264. kind: ConfigKind::Boolean,
  2265. path: &["verbose"],
  2266. options: None,
  2267. },
  2268. "preferredNotifChannel" => ConfigSettingSpec {
  2269. scope: ConfigScope::Global,
  2270. kind: ConfigKind::String,
  2271. path: &["preferredNotifChannel"],
  2272. options: None,
  2273. },
  2274. "autoCompactEnabled" => ConfigSettingSpec {
  2275. scope: ConfigScope::Global,
  2276. kind: ConfigKind::Boolean,
  2277. path: &["autoCompactEnabled"],
  2278. options: None,
  2279. },
  2280. "autoMemoryEnabled" => ConfigSettingSpec {
  2281. scope: ConfigScope::Settings,
  2282. kind: ConfigKind::Boolean,
  2283. path: &["autoMemoryEnabled"],
  2284. options: None,
  2285. },
  2286. "autoDreamEnabled" => ConfigSettingSpec {
  2287. scope: ConfigScope::Settings,
  2288. kind: ConfigKind::Boolean,
  2289. path: &["autoDreamEnabled"],
  2290. options: None,
  2291. },
  2292. "fileCheckpointingEnabled" => ConfigSettingSpec {
  2293. scope: ConfigScope::Global,
  2294. kind: ConfigKind::Boolean,
  2295. path: &["fileCheckpointingEnabled"],
  2296. options: None,
  2297. },
  2298. "showTurnDuration" => ConfigSettingSpec {
  2299. scope: ConfigScope::Global,
  2300. kind: ConfigKind::Boolean,
  2301. path: &["showTurnDuration"],
  2302. options: None,
  2303. },
  2304. "terminalProgressBarEnabled" => ConfigSettingSpec {
  2305. scope: ConfigScope::Global,
  2306. kind: ConfigKind::Boolean,
  2307. path: &["terminalProgressBarEnabled"],
  2308. options: None,
  2309. },
  2310. "todoFeatureEnabled" => ConfigSettingSpec {
  2311. scope: ConfigScope::Global,
  2312. kind: ConfigKind::Boolean,
  2313. path: &["todoFeatureEnabled"],
  2314. options: None,
  2315. },
  2316. "model" => ConfigSettingSpec {
  2317. scope: ConfigScope::Settings,
  2318. kind: ConfigKind::String,
  2319. path: &["model"],
  2320. options: None,
  2321. },
  2322. "alwaysThinkingEnabled" => ConfigSettingSpec {
  2323. scope: ConfigScope::Settings,
  2324. kind: ConfigKind::Boolean,
  2325. path: &["alwaysThinkingEnabled"],
  2326. options: None,
  2327. },
  2328. "permissions.defaultMode" => ConfigSettingSpec {
  2329. scope: ConfigScope::Settings,
  2330. kind: ConfigKind::String,
  2331. path: &["permissions", "defaultMode"],
  2332. options: Some(&["default", "plan", "acceptEdits", "dontAsk", "auto"]),
  2333. },
  2334. "language" => ConfigSettingSpec {
  2335. scope: ConfigScope::Settings,
  2336. kind: ConfigKind::String,
  2337. path: &["language"],
  2338. options: None,
  2339. },
  2340. "teammateMode" => ConfigSettingSpec {
  2341. scope: ConfigScope::Global,
  2342. kind: ConfigKind::String,
  2343. path: &["teammateMode"],
  2344. options: Some(&["tmux", "in-process", "auto"]),
  2345. },
  2346. _ => return None,
  2347. })
  2348. }
  2349. fn normalize_config_value(spec: ConfigSettingSpec, value: ConfigValue) -> Result<Value, String> {
  2350. let normalized = match (spec.kind, value) {
  2351. (ConfigKind::Boolean, ConfigValue::Bool(value)) => Value::Bool(value),
  2352. (ConfigKind::Boolean, ConfigValue::String(value)) => {
  2353. match value.trim().to_ascii_lowercase().as_str() {
  2354. "true" => Value::Bool(true),
  2355. "false" => Value::Bool(false),
  2356. _ => return Err(String::from("setting requires true or false")),
  2357. }
  2358. }
  2359. (ConfigKind::Boolean, ConfigValue::Number(_)) => {
  2360. return Err(String::from("setting requires true or false"))
  2361. }
  2362. (ConfigKind::String, ConfigValue::String(value)) => Value::String(value),
  2363. (ConfigKind::String, ConfigValue::Bool(value)) => Value::String(value.to_string()),
  2364. (ConfigKind::String, ConfigValue::Number(value)) => json!(value),
  2365. };
  2366. if let Some(options) = spec.options {
  2367. let Some(as_str) = normalized.as_str() else {
  2368. return Err(String::from("setting requires a string value"));
  2369. };
  2370. if !options.iter().any(|option| option == &as_str) {
  2371. return Err(format!(
  2372. "Invalid value \"{as_str}\". Options: {}",
  2373. options.join(", ")
  2374. ));
  2375. }
  2376. }
  2377. Ok(normalized)
  2378. }
  2379. fn config_file_for_scope(scope: ConfigScope) -> Result<PathBuf, String> {
  2380. let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
  2381. Ok(match scope {
  2382. ConfigScope::Global => config_home_dir()?.join("settings.json"),
  2383. ConfigScope::Settings => cwd.join(".claude").join("settings.local.json"),
  2384. })
  2385. }
  2386. fn config_home_dir() -> Result<PathBuf, String> {
  2387. if let Ok(path) = std::env::var("CLAUDE_CONFIG_HOME") {
  2388. return Ok(PathBuf::from(path));
  2389. }
  2390. let home = std::env::var("HOME").map_err(|_| String::from("HOME is not set"))?;
  2391. Ok(PathBuf::from(home).join(".claude"))
  2392. }
  2393. fn read_json_object(path: &Path) -> Result<serde_json::Map<String, Value>, String> {
  2394. match std::fs::read_to_string(path) {
  2395. Ok(contents) => {
  2396. if contents.trim().is_empty() {
  2397. return Ok(serde_json::Map::new());
  2398. }
  2399. serde_json::from_str::<Value>(&contents)
  2400. .map_err(|error| error.to_string())?
  2401. .as_object()
  2402. .cloned()
  2403. .ok_or_else(|| String::from("config file must contain a JSON object"))
  2404. }
  2405. Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(serde_json::Map::new()),
  2406. Err(error) => Err(error.to_string()),
  2407. }
  2408. }
  2409. fn write_json_object(path: &Path, value: &serde_json::Map<String, Value>) -> Result<(), String> {
  2410. if let Some(parent) = path.parent() {
  2411. std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
  2412. }
  2413. std::fs::write(
  2414. path,
  2415. serde_json::to_string_pretty(value).map_err(|error| error.to_string())?,
  2416. )
  2417. .map_err(|error| error.to_string())
  2418. }
  2419. fn get_nested_value<'a>(
  2420. value: &'a serde_json::Map<String, Value>,
  2421. path: &[&str],
  2422. ) -> Option<&'a Value> {
  2423. let (first, rest) = path.split_first()?;
  2424. let mut current = value.get(*first)?;
  2425. for key in rest {
  2426. current = current.as_object()?.get(*key)?;
  2427. }
  2428. Some(current)
  2429. }
  2430. fn set_nested_value(root: &mut serde_json::Map<String, Value>, path: &[&str], new_value: Value) {
  2431. let (first, rest) = path.split_first().expect("config path must not be empty");
  2432. if rest.is_empty() {
  2433. root.insert((*first).to_string(), new_value);
  2434. return;
  2435. }
  2436. let entry = root
  2437. .entry((*first).to_string())
  2438. .or_insert_with(|| Value::Object(serde_json::Map::new()));
  2439. if !entry.is_object() {
  2440. *entry = Value::Object(serde_json::Map::new());
  2441. }
  2442. let map = entry.as_object_mut().expect("object inserted");
  2443. set_nested_value(map, rest, new_value);
  2444. }
  2445. fn iso8601_timestamp() -> String {
  2446. if let Ok(output) = Command::new("date")
  2447. .args(["-u", "+%Y-%m-%dT%H:%M:%SZ"])
  2448. .output()
  2449. {
  2450. if output.status.success() {
  2451. return String::from_utf8_lossy(&output.stdout).trim().to_string();
  2452. }
  2453. }
  2454. iso8601_now()
  2455. }
  2456. #[allow(clippy::needless_pass_by_value)]
  2457. fn execute_powershell(input: PowerShellInput) -> std::io::Result<runtime::BashCommandOutput> {
  2458. let _ = &input.description;
  2459. let shell = detect_powershell_shell()?;
  2460. execute_shell_command(
  2461. shell,
  2462. &input.command,
  2463. input.timeout,
  2464. input.run_in_background,
  2465. )
  2466. }
  2467. fn detect_powershell_shell() -> std::io::Result<&'static str> {
  2468. if command_exists("pwsh") {
  2469. Ok("pwsh")
  2470. } else if command_exists("powershell") {
  2471. Ok("powershell")
  2472. } else {
  2473. Err(std::io::Error::new(
  2474. std::io::ErrorKind::NotFound,
  2475. "PowerShell executable not found (expected `pwsh` or `powershell` in PATH)",
  2476. ))
  2477. }
  2478. }
  2479. fn command_exists(command: &str) -> bool {
  2480. std::process::Command::new("sh")
  2481. .arg("-lc")
  2482. .arg(format!("command -v {command} >/dev/null 2>&1"))
  2483. .status()
  2484. .map(|status| status.success())
  2485. .unwrap_or(false)
  2486. }
  2487. #[allow(clippy::too_many_lines)]
  2488. fn execute_shell_command(
  2489. shell: &str,
  2490. command: &str,
  2491. timeout: Option<u64>,
  2492. run_in_background: Option<bool>,
  2493. ) -> std::io::Result<runtime::BashCommandOutput> {
  2494. if run_in_background.unwrap_or(false) {
  2495. let child = std::process::Command::new(shell)
  2496. .arg("-NoProfile")
  2497. .arg("-NonInteractive")
  2498. .arg("-Command")
  2499. .arg(command)
  2500. .stdin(std::process::Stdio::null())
  2501. .stdout(std::process::Stdio::null())
  2502. .stderr(std::process::Stdio::null())
  2503. .spawn()?;
  2504. return Ok(runtime::BashCommandOutput {
  2505. stdout: String::new(),
  2506. stderr: String::new(),
  2507. raw_output_path: None,
  2508. interrupted: false,
  2509. is_image: None,
  2510. background_task_id: Some(child.id().to_string()),
  2511. backgrounded_by_user: Some(true),
  2512. assistant_auto_backgrounded: Some(false),
  2513. dangerously_disable_sandbox: None,
  2514. return_code_interpretation: None,
  2515. no_output_expected: Some(true),
  2516. structured_content: None,
  2517. persisted_output_path: None,
  2518. persisted_output_size: None,
  2519. sandbox_status: None,
  2520. });
  2521. }
  2522. let mut process = std::process::Command::new(shell);
  2523. process
  2524. .arg("-NoProfile")
  2525. .arg("-NonInteractive")
  2526. .arg("-Command")
  2527. .arg(command);
  2528. process
  2529. .stdout(std::process::Stdio::piped())
  2530. .stderr(std::process::Stdio::piped());
  2531. if let Some(timeout_ms) = timeout {
  2532. let mut child = process.spawn()?;
  2533. let started = Instant::now();
  2534. loop {
  2535. if let Some(status) = child.try_wait()? {
  2536. let output = child.wait_with_output()?;
  2537. return Ok(runtime::BashCommandOutput {
  2538. stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
  2539. stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
  2540. raw_output_path: None,
  2541. interrupted: false,
  2542. is_image: None,
  2543. background_task_id: None,
  2544. backgrounded_by_user: None,
  2545. assistant_auto_backgrounded: None,
  2546. dangerously_disable_sandbox: None,
  2547. return_code_interpretation: status
  2548. .code()
  2549. .filter(|code| *code != 0)
  2550. .map(|code| format!("exit_code:{code}")),
  2551. no_output_expected: Some(output.stdout.is_empty() && output.stderr.is_empty()),
  2552. structured_content: None,
  2553. persisted_output_path: None,
  2554. persisted_output_size: None,
  2555. sandbox_status: None,
  2556. });
  2557. }
  2558. if started.elapsed() >= Duration::from_millis(timeout_ms) {
  2559. let _ = child.kill();
  2560. let output = child.wait_with_output()?;
  2561. let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
  2562. let stderr = if stderr.trim().is_empty() {
  2563. format!("Command exceeded timeout of {timeout_ms} ms")
  2564. } else {
  2565. format!(
  2566. "{}
  2567. Command exceeded timeout of {timeout_ms} ms",
  2568. stderr.trim_end()
  2569. )
  2570. };
  2571. return Ok(runtime::BashCommandOutput {
  2572. stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
  2573. stderr,
  2574. raw_output_path: None,
  2575. interrupted: true,
  2576. is_image: None,
  2577. background_task_id: None,
  2578. backgrounded_by_user: None,
  2579. assistant_auto_backgrounded: None,
  2580. dangerously_disable_sandbox: None,
  2581. return_code_interpretation: Some(String::from("timeout")),
  2582. no_output_expected: Some(false),
  2583. structured_content: None,
  2584. persisted_output_path: None,
  2585. persisted_output_size: None,
  2586. sandbox_status: None,
  2587. });
  2588. }
  2589. std::thread::sleep(Duration::from_millis(10));
  2590. }
  2591. }
  2592. let output = process.output()?;
  2593. Ok(runtime::BashCommandOutput {
  2594. stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
  2595. stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
  2596. raw_output_path: None,
  2597. interrupted: false,
  2598. is_image: None,
  2599. background_task_id: None,
  2600. backgrounded_by_user: None,
  2601. assistant_auto_backgrounded: None,
  2602. dangerously_disable_sandbox: None,
  2603. return_code_interpretation: output
  2604. .status
  2605. .code()
  2606. .filter(|code| *code != 0)
  2607. .map(|code| format!("exit_code:{code}")),
  2608. no_output_expected: Some(output.stdout.is_empty() && output.stderr.is_empty()),
  2609. structured_content: None,
  2610. persisted_output_path: None,
  2611. persisted_output_size: None,
  2612. sandbox_status: None,
  2613. })
  2614. }
  2615. fn resolve_cell_index(
  2616. cells: &[serde_json::Value],
  2617. cell_id: Option<&str>,
  2618. edit_mode: NotebookEditMode,
  2619. ) -> Result<usize, String> {
  2620. if cells.is_empty()
  2621. && matches!(
  2622. edit_mode,
  2623. NotebookEditMode::Replace | NotebookEditMode::Delete
  2624. )
  2625. {
  2626. return Err(String::from("Notebook has no cells to edit"));
  2627. }
  2628. if let Some(cell_id) = cell_id {
  2629. cells
  2630. .iter()
  2631. .position(|cell| cell.get("id").and_then(serde_json::Value::as_str) == Some(cell_id))
  2632. .ok_or_else(|| format!("Cell id not found: {cell_id}"))
  2633. } else {
  2634. Ok(cells.len().saturating_sub(1))
  2635. }
  2636. }
  2637. fn source_lines(source: &str) -> Vec<serde_json::Value> {
  2638. if source.is_empty() {
  2639. return vec![serde_json::Value::String(String::new())];
  2640. }
  2641. source
  2642. .split_inclusive('\n')
  2643. .map(|line| serde_json::Value::String(line.to_string()))
  2644. .collect()
  2645. }
  2646. fn format_notebook_edit_mode(mode: NotebookEditMode) -> String {
  2647. match mode {
  2648. NotebookEditMode::Replace => String::from("replace"),
  2649. NotebookEditMode::Insert => String::from("insert"),
  2650. NotebookEditMode::Delete => String::from("delete"),
  2651. }
  2652. }
  2653. fn make_cell_id(index: usize) -> String {
  2654. format!("cell-{}", index + 1)
  2655. }
  2656. fn parse_skill_description(contents: &str) -> Option<String> {
  2657. for line in contents.lines() {
  2658. if let Some(value) = line.strip_prefix("description:") {
  2659. let trimmed = value.trim();
  2660. if !trimmed.is_empty() {
  2661. return Some(trimmed.to_string());
  2662. }
  2663. }
  2664. }
  2665. None
  2666. }
  2667. #[cfg(test)]
  2668. mod tests {
  2669. use std::collections::BTreeSet;
  2670. use std::fs;
  2671. use std::io::{Read, Write};
  2672. use std::net::{SocketAddr, TcpListener};
  2673. use std::path::PathBuf;
  2674. use std::sync::{Arc, Mutex, OnceLock};
  2675. use std::thread;
  2676. use std::time::Duration;
  2677. use super::{
  2678. agent_permission_policy, allowed_tools_for_subagent, execute_agent_with_spawn,
  2679. execute_tool, final_assistant_text, mvp_tool_specs, persist_agent_terminal_state,
  2680. AgentInput, AgentJob, SubagentToolExecutor,
  2681. };
  2682. use runtime::{ApiRequest, AssistantEvent, ConversationRuntime, RuntimeError, Session};
  2683. use serde_json::json;
  2684. fn env_lock() -> &'static Mutex<()> {
  2685. static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
  2686. LOCK.get_or_init(|| Mutex::new(()))
  2687. }
  2688. fn temp_path(name: &str) -> PathBuf {
  2689. let unique = std::time::SystemTime::now()
  2690. .duration_since(std::time::UNIX_EPOCH)
  2691. .expect("time")
  2692. .as_nanos();
  2693. std::env::temp_dir().join(format!("clawd-tools-{unique}-{name}"))
  2694. }
  2695. #[test]
  2696. fn exposes_mvp_tools() {
  2697. let names = mvp_tool_specs()
  2698. .into_iter()
  2699. .map(|spec| spec.name)
  2700. .collect::<Vec<_>>();
  2701. assert!(names.contains(&"bash"));
  2702. assert!(names.contains(&"read_file"));
  2703. assert!(names.contains(&"WebFetch"));
  2704. assert!(names.contains(&"WebSearch"));
  2705. assert!(names.contains(&"TodoWrite"));
  2706. assert!(names.contains(&"Skill"));
  2707. assert!(names.contains(&"Agent"));
  2708. assert!(names.contains(&"ToolSearch"));
  2709. assert!(names.contains(&"NotebookEdit"));
  2710. assert!(names.contains(&"Sleep"));
  2711. assert!(names.contains(&"SendUserMessage"));
  2712. assert!(names.contains(&"Config"));
  2713. assert!(names.contains(&"StructuredOutput"));
  2714. assert!(names.contains(&"REPL"));
  2715. assert!(names.contains(&"PowerShell"));
  2716. }
  2717. #[test]
  2718. fn rejects_unknown_tool_names() {
  2719. let error = execute_tool("nope", &json!({})).expect_err("tool should be rejected");
  2720. assert!(error.contains("unsupported tool"));
  2721. }
  2722. #[test]
  2723. fn web_fetch_returns_prompt_aware_summary() {
  2724. let server = TestServer::spawn(Arc::new(|request_line: &str| {
  2725. assert!(request_line.starts_with("GET /page "));
  2726. HttpResponse::html(
  2727. 200,
  2728. "OK",
  2729. "<html><head><title>Ignored</title></head><body><h1>Test Page</h1><p>Hello <b>world</b> from local server.</p></body></html>",
  2730. )
  2731. }));
  2732. let result = execute_tool(
  2733. "WebFetch",
  2734. &json!({
  2735. "url": format!("http://{}/page", server.addr()),
  2736. "prompt": "Summarize this page"
  2737. }),
  2738. )
  2739. .expect("WebFetch should succeed");
  2740. let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
  2741. assert_eq!(output["code"], 200);
  2742. let summary = output["result"].as_str().expect("result string");
  2743. assert!(summary.contains("Fetched"));
  2744. assert!(summary.contains("Test Page"));
  2745. assert!(summary.contains("Hello world from local server"));
  2746. let titled = execute_tool(
  2747. "WebFetch",
  2748. &json!({
  2749. "url": format!("http://{}/page", server.addr()),
  2750. "prompt": "What is the page title?"
  2751. }),
  2752. )
  2753. .expect("WebFetch title query should succeed");
  2754. let titled_output: serde_json::Value = serde_json::from_str(&titled).expect("valid json");
  2755. let titled_summary = titled_output["result"].as_str().expect("result string");
  2756. assert!(titled_summary.contains("Title: Ignored"));
  2757. }
  2758. #[test]
  2759. fn web_fetch_supports_plain_text_and_rejects_invalid_url() {
  2760. let server = TestServer::spawn(Arc::new(|request_line: &str| {
  2761. assert!(request_line.starts_with("GET /plain "));
  2762. HttpResponse::text(200, "OK", "plain text response")
  2763. }));
  2764. let result = execute_tool(
  2765. "WebFetch",
  2766. &json!({
  2767. "url": format!("http://{}/plain", server.addr()),
  2768. "prompt": "Show me the content"
  2769. }),
  2770. )
  2771. .expect("WebFetch should succeed for text content");
  2772. let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
  2773. assert_eq!(output["url"], format!("http://{}/plain", server.addr()));
  2774. assert!(output["result"]
  2775. .as_str()
  2776. .expect("result")
  2777. .contains("plain text response"));
  2778. let error = execute_tool(
  2779. "WebFetch",
  2780. &json!({
  2781. "url": "not a url",
  2782. "prompt": "Summarize"
  2783. }),
  2784. )
  2785. .expect_err("invalid URL should fail");
  2786. assert!(error.contains("relative URL without a base") || error.contains("invalid"));
  2787. }
  2788. #[test]
  2789. fn web_search_extracts_and_filters_results() {
  2790. let server = TestServer::spawn(Arc::new(|request_line: &str| {
  2791. assert!(request_line.contains("GET /search?q=rust+web+search "));
  2792. HttpResponse::html(
  2793. 200,
  2794. "OK",
  2795. r#"
  2796. <html><body>
  2797. <a class="result__a" href="https://docs.rs/reqwest">Reqwest docs</a>
  2798. <a class="result__a" href="https://example.com/blocked">Blocked result</a>
  2799. </body></html>
  2800. "#,
  2801. )
  2802. }));
  2803. std::env::set_var(
  2804. "CLAWD_WEB_SEARCH_BASE_URL",
  2805. format!("http://{}/search", server.addr()),
  2806. );
  2807. let result = execute_tool(
  2808. "WebSearch",
  2809. &json!({
  2810. "query": "rust web search",
  2811. "allowed_domains": ["https://DOCS.rs/"],
  2812. "blocked_domains": ["HTTPS://EXAMPLE.COM"]
  2813. }),
  2814. )
  2815. .expect("WebSearch should succeed");
  2816. std::env::remove_var("CLAWD_WEB_SEARCH_BASE_URL");
  2817. let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
  2818. assert_eq!(output["query"], "rust web search");
  2819. let results = output["results"].as_array().expect("results array");
  2820. let search_result = results
  2821. .iter()
  2822. .find(|item| item.get("content").is_some())
  2823. .expect("search result block present");
  2824. let content = search_result["content"].as_array().expect("content array");
  2825. assert_eq!(content.len(), 1);
  2826. assert_eq!(content[0]["title"], "Reqwest docs");
  2827. assert_eq!(content[0]["url"], "https://docs.rs/reqwest");
  2828. }
  2829. #[test]
  2830. fn web_search_handles_generic_links_and_invalid_base_url() {
  2831. let _guard = env_lock()
  2832. .lock()
  2833. .unwrap_or_else(std::sync::PoisonError::into_inner);
  2834. let server = TestServer::spawn(Arc::new(|request_line: &str| {
  2835. assert!(request_line.contains("GET /fallback?q=generic+links "));
  2836. HttpResponse::html(
  2837. 200,
  2838. "OK",
  2839. r#"
  2840. <html><body>
  2841. <a href="https://example.com/one">Example One</a>
  2842. <a href="https://example.com/one">Duplicate Example One</a>
  2843. <a href="https://docs.rs/tokio">Tokio Docs</a>
  2844. </body></html>
  2845. "#,
  2846. )
  2847. }));
  2848. std::env::set_var(
  2849. "CLAWD_WEB_SEARCH_BASE_URL",
  2850. format!("http://{}/fallback", server.addr()),
  2851. );
  2852. let result = execute_tool(
  2853. "WebSearch",
  2854. &json!({
  2855. "query": "generic links"
  2856. }),
  2857. )
  2858. .expect("WebSearch fallback parsing should succeed");
  2859. std::env::remove_var("CLAWD_WEB_SEARCH_BASE_URL");
  2860. let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
  2861. let results = output["results"].as_array().expect("results array");
  2862. let search_result = results
  2863. .iter()
  2864. .find(|item| item.get("content").is_some())
  2865. .expect("search result block present");
  2866. let content = search_result["content"].as_array().expect("content array");
  2867. assert_eq!(content.len(), 2);
  2868. assert_eq!(content[0]["url"], "https://example.com/one");
  2869. assert_eq!(content[1]["url"], "https://docs.rs/tokio");
  2870. std::env::set_var("CLAWD_WEB_SEARCH_BASE_URL", "://bad-base-url");
  2871. let error = execute_tool("WebSearch", &json!({ "query": "generic links" }))
  2872. .expect_err("invalid base URL should fail");
  2873. std::env::remove_var("CLAWD_WEB_SEARCH_BASE_URL");
  2874. assert!(error.contains("relative URL without a base") || error.contains("empty host"));
  2875. }
  2876. #[test]
  2877. fn todo_write_persists_and_returns_previous_state() {
  2878. let _guard = env_lock()
  2879. .lock()
  2880. .unwrap_or_else(std::sync::PoisonError::into_inner);
  2881. let path = temp_path("todos.json");
  2882. std::env::set_var("CLAWD_TODO_STORE", &path);
  2883. let first = execute_tool(
  2884. "TodoWrite",
  2885. &json!({
  2886. "todos": [
  2887. {"content": "Add tool", "activeForm": "Adding tool", "status": "in_progress"},
  2888. {"content": "Run tests", "activeForm": "Running tests", "status": "pending"}
  2889. ]
  2890. }),
  2891. )
  2892. .expect("TodoWrite should succeed");
  2893. let first_output: serde_json::Value = serde_json::from_str(&first).expect("valid json");
  2894. assert_eq!(first_output["oldTodos"].as_array().expect("array").len(), 0);
  2895. let second = execute_tool(
  2896. "TodoWrite",
  2897. &json!({
  2898. "todos": [
  2899. {"content": "Add tool", "activeForm": "Adding tool", "status": "completed"},
  2900. {"content": "Run tests", "activeForm": "Running tests", "status": "completed"},
  2901. {"content": "Verify", "activeForm": "Verifying", "status": "completed"}
  2902. ]
  2903. }),
  2904. )
  2905. .expect("TodoWrite should succeed");
  2906. std::env::remove_var("CLAWD_TODO_STORE");
  2907. let _ = std::fs::remove_file(path);
  2908. let second_output: serde_json::Value = serde_json::from_str(&second).expect("valid json");
  2909. assert_eq!(
  2910. second_output["oldTodos"].as_array().expect("array").len(),
  2911. 2
  2912. );
  2913. assert_eq!(
  2914. second_output["newTodos"].as_array().expect("array").len(),
  2915. 3
  2916. );
  2917. assert!(second_output["verificationNudgeNeeded"].is_null());
  2918. }
  2919. #[test]
  2920. fn todo_write_rejects_invalid_payloads_and_sets_verification_nudge() {
  2921. let _guard = env_lock()
  2922. .lock()
  2923. .unwrap_or_else(std::sync::PoisonError::into_inner);
  2924. let path = temp_path("todos-errors.json");
  2925. std::env::set_var("CLAWD_TODO_STORE", &path);
  2926. let empty = execute_tool("TodoWrite", &json!({ "todos": [] }))
  2927. .expect_err("empty todos should fail");
  2928. assert!(empty.contains("todos must not be empty"));
  2929. let too_many_active = execute_tool(
  2930. "TodoWrite",
  2931. &json!({
  2932. "todos": [
  2933. {"content": "One", "activeForm": "Doing one", "status": "in_progress"},
  2934. {"content": "Two", "activeForm": "Doing two", "status": "in_progress"}
  2935. ]
  2936. }),
  2937. )
  2938. .expect_err("multiple in-progress todos should fail");
  2939. assert!(too_many_active.contains("zero or one todo items may be in_progress"));
  2940. let blank_content = execute_tool(
  2941. "TodoWrite",
  2942. &json!({
  2943. "todos": [
  2944. {"content": " ", "activeForm": "Doing it", "status": "pending"}
  2945. ]
  2946. }),
  2947. )
  2948. .expect_err("blank content should fail");
  2949. assert!(blank_content.contains("todo content must not be empty"));
  2950. let nudge = execute_tool(
  2951. "TodoWrite",
  2952. &json!({
  2953. "todos": [
  2954. {"content": "Write tests", "activeForm": "Writing tests", "status": "completed"},
  2955. {"content": "Fix errors", "activeForm": "Fixing errors", "status": "completed"},
  2956. {"content": "Ship branch", "activeForm": "Shipping branch", "status": "completed"}
  2957. ]
  2958. }),
  2959. )
  2960. .expect("completed todos should succeed");
  2961. std::env::remove_var("CLAWD_TODO_STORE");
  2962. let _ = fs::remove_file(path);
  2963. let output: serde_json::Value = serde_json::from_str(&nudge).expect("valid json");
  2964. assert_eq!(output["verificationNudgeNeeded"], true);
  2965. }
  2966. #[test]
  2967. fn skill_loads_local_skill_prompt() {
  2968. let result = execute_tool(
  2969. "Skill",
  2970. &json!({
  2971. "skill": "help",
  2972. "args": "overview"
  2973. }),
  2974. )
  2975. .expect("Skill should succeed");
  2976. let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
  2977. assert_eq!(output["skill"], "help");
  2978. assert!(output["path"]
  2979. .as_str()
  2980. .expect("path")
  2981. .ends_with("/help/SKILL.md"));
  2982. assert!(output["prompt"]
  2983. .as_str()
  2984. .expect("prompt")
  2985. .contains("Guide on using oh-my-codex plugin"));
  2986. let dollar_result = execute_tool(
  2987. "Skill",
  2988. &json!({
  2989. "skill": "$help"
  2990. }),
  2991. )
  2992. .expect("Skill should accept $skill invocation form");
  2993. let dollar_output: serde_json::Value =
  2994. serde_json::from_str(&dollar_result).expect("valid json");
  2995. assert_eq!(dollar_output["skill"], "$help");
  2996. assert!(dollar_output["path"]
  2997. .as_str()
  2998. .expect("path")
  2999. .ends_with("/help/SKILL.md"));
  3000. }
  3001. #[test]
  3002. fn tool_search_supports_keyword_and_select_queries() {
  3003. let keyword = execute_tool(
  3004. "ToolSearch",
  3005. &json!({"query": "web current", "max_results": 3}),
  3006. )
  3007. .expect("ToolSearch should succeed");
  3008. let keyword_output: serde_json::Value = serde_json::from_str(&keyword).expect("valid json");
  3009. let matches = keyword_output["matches"].as_array().expect("matches");
  3010. assert!(matches.iter().any(|value| value == "WebSearch"));
  3011. let selected = execute_tool("ToolSearch", &json!({"query": "select:Agent,Skill"}))
  3012. .expect("ToolSearch should succeed");
  3013. let selected_output: serde_json::Value =
  3014. serde_json::from_str(&selected).expect("valid json");
  3015. assert_eq!(selected_output["matches"][0], "Agent");
  3016. assert_eq!(selected_output["matches"][1], "Skill");
  3017. let aliased = execute_tool("ToolSearch", &json!({"query": "AgentTool"}))
  3018. .expect("ToolSearch should support tool aliases");
  3019. let aliased_output: serde_json::Value = serde_json::from_str(&aliased).expect("valid json");
  3020. assert_eq!(aliased_output["matches"][0], "Agent");
  3021. assert_eq!(aliased_output["normalized_query"], "agent");
  3022. let selected_with_alias =
  3023. execute_tool("ToolSearch", &json!({"query": "select:AgentTool,Skill"}))
  3024. .expect("ToolSearch alias select should succeed");
  3025. let selected_with_alias_output: serde_json::Value =
  3026. serde_json::from_str(&selected_with_alias).expect("valid json");
  3027. assert_eq!(selected_with_alias_output["matches"][0], "Agent");
  3028. assert_eq!(selected_with_alias_output["matches"][1], "Skill");
  3029. }
  3030. #[test]
  3031. fn agent_persists_handoff_metadata() {
  3032. let _guard = env_lock()
  3033. .lock()
  3034. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3035. let dir = temp_path("agent-store");
  3036. std::env::set_var("CLAWD_AGENT_STORE", &dir);
  3037. let captured = Arc::new(Mutex::new(None::<AgentJob>));
  3038. let captured_for_spawn = Arc::clone(&captured);
  3039. let manifest = execute_agent_with_spawn(
  3040. AgentInput {
  3041. description: "Audit the branch".to_string(),
  3042. prompt: "Check tests and outstanding work.".to_string(),
  3043. subagent_type: Some("Explore".to_string()),
  3044. name: Some("ship-audit".to_string()),
  3045. model: None,
  3046. },
  3047. move |job| {
  3048. *captured_for_spawn
  3049. .lock()
  3050. .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(job);
  3051. Ok(())
  3052. },
  3053. )
  3054. .expect("Agent should succeed");
  3055. std::env::remove_var("CLAWD_AGENT_STORE");
  3056. assert_eq!(manifest.name, "ship-audit");
  3057. assert_eq!(manifest.subagent_type.as_deref(), Some("Explore"));
  3058. assert_eq!(manifest.status, "running");
  3059. assert!(!manifest.created_at.is_empty());
  3060. assert!(manifest.started_at.is_some());
  3061. assert!(manifest.completed_at.is_none());
  3062. let contents = std::fs::read_to_string(&manifest.output_file).expect("agent file exists");
  3063. let manifest_contents =
  3064. std::fs::read_to_string(&manifest.manifest_file).expect("manifest file exists");
  3065. assert!(contents.contains("Audit the branch"));
  3066. assert!(contents.contains("Check tests and outstanding work."));
  3067. assert!(manifest_contents.contains("\"subagentType\": \"Explore\""));
  3068. assert!(manifest_contents.contains("\"status\": \"running\""));
  3069. let captured_job = captured
  3070. .lock()
  3071. .unwrap_or_else(std::sync::PoisonError::into_inner)
  3072. .clone()
  3073. .expect("spawn job should be captured");
  3074. assert_eq!(captured_job.prompt, "Check tests and outstanding work.");
  3075. assert!(captured_job.allowed_tools.contains("read_file"));
  3076. assert!(!captured_job.allowed_tools.contains("Agent"));
  3077. let normalized = execute_tool(
  3078. "Agent",
  3079. &json!({
  3080. "description": "Verify the branch",
  3081. "prompt": "Check tests.",
  3082. "subagent_type": "explorer"
  3083. }),
  3084. )
  3085. .expect("Agent should normalize built-in aliases");
  3086. let normalized_output: serde_json::Value =
  3087. serde_json::from_str(&normalized).expect("valid json");
  3088. assert_eq!(normalized_output["subagentType"], "Explore");
  3089. let named = execute_tool(
  3090. "Agent",
  3091. &json!({
  3092. "description": "Review the branch",
  3093. "prompt": "Inspect diff.",
  3094. "name": "Ship Audit!!!"
  3095. }),
  3096. )
  3097. .expect("Agent should normalize explicit names");
  3098. let named_output: serde_json::Value = serde_json::from_str(&named).expect("valid json");
  3099. assert_eq!(named_output["name"], "ship-audit");
  3100. let _ = std::fs::remove_dir_all(dir);
  3101. }
  3102. #[test]
  3103. fn agent_fake_runner_can_persist_completion_and_failure() {
  3104. let _guard = env_lock()
  3105. .lock()
  3106. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3107. let dir = temp_path("agent-runner");
  3108. std::env::set_var("CLAWD_AGENT_STORE", &dir);
  3109. let completed = execute_agent_with_spawn(
  3110. AgentInput {
  3111. description: "Complete the task".to_string(),
  3112. prompt: "Do the work".to_string(),
  3113. subagent_type: Some("Explore".to_string()),
  3114. name: Some("complete-task".to_string()),
  3115. model: Some("claude-sonnet-4-6".to_string()),
  3116. },
  3117. |job| {
  3118. persist_agent_terminal_state(
  3119. &job.manifest,
  3120. "completed",
  3121. Some("Finished successfully"),
  3122. None,
  3123. )
  3124. },
  3125. )
  3126. .expect("completed agent should succeed");
  3127. let completed_manifest = std::fs::read_to_string(&completed.manifest_file)
  3128. .expect("completed manifest should exist");
  3129. let completed_output =
  3130. std::fs::read_to_string(&completed.output_file).expect("completed output should exist");
  3131. assert!(completed_manifest.contains("\"status\": \"completed\""));
  3132. assert!(completed_output.contains("Finished successfully"));
  3133. let failed = execute_agent_with_spawn(
  3134. AgentInput {
  3135. description: "Fail the task".to_string(),
  3136. prompt: "Do the failing work".to_string(),
  3137. subagent_type: Some("Verification".to_string()),
  3138. name: Some("fail-task".to_string()),
  3139. model: None,
  3140. },
  3141. |job| {
  3142. persist_agent_terminal_state(
  3143. &job.manifest,
  3144. "failed",
  3145. None,
  3146. Some(String::from("simulated failure")),
  3147. )
  3148. },
  3149. )
  3150. .expect("failed agent should still spawn");
  3151. let failed_manifest =
  3152. std::fs::read_to_string(&failed.manifest_file).expect("failed manifest should exist");
  3153. let failed_output =
  3154. std::fs::read_to_string(&failed.output_file).expect("failed output should exist");
  3155. assert!(failed_manifest.contains("\"status\": \"failed\""));
  3156. assert!(failed_manifest.contains("simulated failure"));
  3157. assert!(failed_output.contains("simulated failure"));
  3158. let spawn_error = execute_agent_with_spawn(
  3159. AgentInput {
  3160. description: "Spawn error task".to_string(),
  3161. prompt: "Never starts".to_string(),
  3162. subagent_type: None,
  3163. name: Some("spawn-error".to_string()),
  3164. model: None,
  3165. },
  3166. |_| Err(String::from("thread creation failed")),
  3167. )
  3168. .expect_err("spawn errors should surface");
  3169. assert!(spawn_error.contains("failed to spawn sub-agent"));
  3170. let spawn_error_manifest = std::fs::read_dir(&dir)
  3171. .expect("agent dir should exist")
  3172. .filter_map(Result::ok)
  3173. .map(|entry| entry.path())
  3174. .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("json"))
  3175. .find_map(|path| {
  3176. let contents = std::fs::read_to_string(&path).ok()?;
  3177. contents
  3178. .contains("\"name\": \"spawn-error\"")
  3179. .then_some(contents)
  3180. })
  3181. .expect("failed manifest should still be written");
  3182. assert!(spawn_error_manifest.contains("\"status\": \"failed\""));
  3183. assert!(spawn_error_manifest.contains("thread creation failed"));
  3184. std::env::remove_var("CLAWD_AGENT_STORE");
  3185. let _ = std::fs::remove_dir_all(dir);
  3186. }
  3187. #[test]
  3188. fn agent_tool_subset_mapping_is_expected() {
  3189. let general = allowed_tools_for_subagent("general-purpose");
  3190. assert!(general.contains("bash"));
  3191. assert!(general.contains("write_file"));
  3192. assert!(!general.contains("Agent"));
  3193. let explore = allowed_tools_for_subagent("Explore");
  3194. assert!(explore.contains("read_file"));
  3195. assert!(explore.contains("grep_search"));
  3196. assert!(!explore.contains("bash"));
  3197. let plan = allowed_tools_for_subagent("Plan");
  3198. assert!(plan.contains("TodoWrite"));
  3199. assert!(plan.contains("StructuredOutput"));
  3200. assert!(!plan.contains("Agent"));
  3201. let verification = allowed_tools_for_subagent("Verification");
  3202. assert!(verification.contains("bash"));
  3203. assert!(verification.contains("PowerShell"));
  3204. assert!(!verification.contains("write_file"));
  3205. }
  3206. #[derive(Debug)]
  3207. struct MockSubagentApiClient {
  3208. calls: usize,
  3209. input_path: String,
  3210. }
  3211. impl runtime::ApiClient for MockSubagentApiClient {
  3212. fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
  3213. self.calls += 1;
  3214. match self.calls {
  3215. 1 => {
  3216. assert_eq!(request.messages.len(), 1);
  3217. Ok(vec![
  3218. AssistantEvent::ToolUse {
  3219. id: "tool-1".to_string(),
  3220. name: "read_file".to_string(),
  3221. input: json!({ "path": self.input_path }).to_string(),
  3222. },
  3223. AssistantEvent::MessageStop,
  3224. ])
  3225. }
  3226. 2 => {
  3227. assert!(request.messages.len() >= 3);
  3228. Ok(vec![
  3229. AssistantEvent::TextDelta("Scope: completed mock review".to_string()),
  3230. AssistantEvent::MessageStop,
  3231. ])
  3232. }
  3233. _ => panic!("unexpected mock stream call"),
  3234. }
  3235. }
  3236. }
  3237. #[test]
  3238. fn subagent_runtime_executes_tool_loop_with_isolated_session() {
  3239. let _guard = env_lock()
  3240. .lock()
  3241. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3242. let path = temp_path("subagent-input.txt");
  3243. std::fs::write(&path, "hello from child").expect("write input file");
  3244. let mut runtime = ConversationRuntime::new(
  3245. Session::new(),
  3246. MockSubagentApiClient {
  3247. calls: 0,
  3248. input_path: path.display().to_string(),
  3249. },
  3250. SubagentToolExecutor::new(BTreeSet::from([String::from("read_file")])),
  3251. agent_permission_policy(),
  3252. vec![String::from("system prompt")],
  3253. );
  3254. let summary = runtime
  3255. .run_turn("Inspect the delegated file", None)
  3256. .expect("subagent loop should succeed");
  3257. assert_eq!(
  3258. final_assistant_text(&summary),
  3259. "Scope: completed mock review"
  3260. );
  3261. assert!(runtime
  3262. .session()
  3263. .messages
  3264. .iter()
  3265. .flat_map(|message| message.blocks.iter())
  3266. .any(|block| matches!(
  3267. block,
  3268. runtime::ContentBlock::ToolResult { output, .. }
  3269. if output.contains("hello from child")
  3270. )));
  3271. let _ = std::fs::remove_file(path);
  3272. }
  3273. #[test]
  3274. fn agent_rejects_blank_required_fields() {
  3275. let missing_description = execute_tool(
  3276. "Agent",
  3277. &json!({
  3278. "description": " ",
  3279. "prompt": "Inspect"
  3280. }),
  3281. )
  3282. .expect_err("blank description should fail");
  3283. assert!(missing_description.contains("description must not be empty"));
  3284. let missing_prompt = execute_tool(
  3285. "Agent",
  3286. &json!({
  3287. "description": "Inspect branch",
  3288. "prompt": " "
  3289. }),
  3290. )
  3291. .expect_err("blank prompt should fail");
  3292. assert!(missing_prompt.contains("prompt must not be empty"));
  3293. }
  3294. #[test]
  3295. fn notebook_edit_replaces_inserts_and_deletes_cells() {
  3296. let path = temp_path("notebook.ipynb");
  3297. std::fs::write(
  3298. &path,
  3299. r#"{
  3300. "cells": [
  3301. {"cell_type": "code", "id": "cell-a", "metadata": {}, "source": ["print(1)\n"], "outputs": [], "execution_count": null}
  3302. ],
  3303. "metadata": {"kernelspec": {"language": "python"}},
  3304. "nbformat": 4,
  3305. "nbformat_minor": 5
  3306. }"#,
  3307. )
  3308. .expect("write notebook");
  3309. let replaced = execute_tool(
  3310. "NotebookEdit",
  3311. &json!({
  3312. "notebook_path": path.display().to_string(),
  3313. "cell_id": "cell-a",
  3314. "new_source": "print(2)\n",
  3315. "edit_mode": "replace"
  3316. }),
  3317. )
  3318. .expect("NotebookEdit replace should succeed");
  3319. let replaced_output: serde_json::Value = serde_json::from_str(&replaced).expect("json");
  3320. assert_eq!(replaced_output["cell_id"], "cell-a");
  3321. assert_eq!(replaced_output["cell_type"], "code");
  3322. let inserted = execute_tool(
  3323. "NotebookEdit",
  3324. &json!({
  3325. "notebook_path": path.display().to_string(),
  3326. "cell_id": "cell-a",
  3327. "new_source": "# heading\n",
  3328. "cell_type": "markdown",
  3329. "edit_mode": "insert"
  3330. }),
  3331. )
  3332. .expect("NotebookEdit insert should succeed");
  3333. let inserted_output: serde_json::Value = serde_json::from_str(&inserted).expect("json");
  3334. assert_eq!(inserted_output["cell_type"], "markdown");
  3335. let appended = execute_tool(
  3336. "NotebookEdit",
  3337. &json!({
  3338. "notebook_path": path.display().to_string(),
  3339. "new_source": "print(3)\n",
  3340. "edit_mode": "insert"
  3341. }),
  3342. )
  3343. .expect("NotebookEdit append should succeed");
  3344. let appended_output: serde_json::Value = serde_json::from_str(&appended).expect("json");
  3345. assert_eq!(appended_output["cell_type"], "code");
  3346. let deleted = execute_tool(
  3347. "NotebookEdit",
  3348. &json!({
  3349. "notebook_path": path.display().to_string(),
  3350. "cell_id": "cell-a",
  3351. "edit_mode": "delete"
  3352. }),
  3353. )
  3354. .expect("NotebookEdit delete should succeed without new_source");
  3355. let deleted_output: serde_json::Value = serde_json::from_str(&deleted).expect("json");
  3356. assert!(deleted_output["cell_type"].is_null());
  3357. assert_eq!(deleted_output["new_source"], "");
  3358. let final_notebook: serde_json::Value =
  3359. serde_json::from_str(&std::fs::read_to_string(&path).expect("read notebook"))
  3360. .expect("valid notebook json");
  3361. let cells = final_notebook["cells"].as_array().expect("cells array");
  3362. assert_eq!(cells.len(), 2);
  3363. assert_eq!(cells[0]["cell_type"], "markdown");
  3364. assert!(cells[0].get("outputs").is_none());
  3365. assert_eq!(cells[1]["cell_type"], "code");
  3366. assert_eq!(cells[1]["source"][0], "print(3)\n");
  3367. let _ = std::fs::remove_file(path);
  3368. }
  3369. #[test]
  3370. fn notebook_edit_rejects_invalid_inputs() {
  3371. let text_path = temp_path("notebook.txt");
  3372. fs::write(&text_path, "not a notebook").expect("write text file");
  3373. let wrong_extension = execute_tool(
  3374. "NotebookEdit",
  3375. &json!({
  3376. "notebook_path": text_path.display().to_string(),
  3377. "new_source": "print(1)\n"
  3378. }),
  3379. )
  3380. .expect_err("non-ipynb file should fail");
  3381. assert!(wrong_extension.contains("Jupyter notebook"));
  3382. let _ = fs::remove_file(&text_path);
  3383. let empty_notebook = temp_path("empty.ipynb");
  3384. fs::write(
  3385. &empty_notebook,
  3386. r#"{"cells":[],"metadata":{"kernelspec":{"language":"python"}},"nbformat":4,"nbformat_minor":5}"#,
  3387. )
  3388. .expect("write empty notebook");
  3389. let missing_source = execute_tool(
  3390. "NotebookEdit",
  3391. &json!({
  3392. "notebook_path": empty_notebook.display().to_string(),
  3393. "edit_mode": "insert"
  3394. }),
  3395. )
  3396. .expect_err("insert without source should fail");
  3397. assert!(missing_source.contains("new_source is required"));
  3398. let missing_cell = execute_tool(
  3399. "NotebookEdit",
  3400. &json!({
  3401. "notebook_path": empty_notebook.display().to_string(),
  3402. "edit_mode": "delete"
  3403. }),
  3404. )
  3405. .expect_err("delete on empty notebook should fail");
  3406. assert!(missing_cell.contains("Notebook has no cells to edit"));
  3407. let _ = fs::remove_file(empty_notebook);
  3408. }
  3409. #[test]
  3410. fn bash_tool_reports_success_exit_failure_timeout_and_background() {
  3411. let success = execute_tool("bash", &json!({ "command": "printf 'hello'" }))
  3412. .expect("bash should succeed");
  3413. let success_output: serde_json::Value = serde_json::from_str(&success).expect("json");
  3414. assert_eq!(success_output["stdout"], "hello");
  3415. assert_eq!(success_output["interrupted"], false);
  3416. let failure = execute_tool("bash", &json!({ "command": "printf 'oops' >&2; exit 7" }))
  3417. .expect("bash failure should still return structured output");
  3418. let failure_output: serde_json::Value = serde_json::from_str(&failure).expect("json");
  3419. assert_eq!(failure_output["returnCodeInterpretation"], "exit_code:7");
  3420. assert!(failure_output["stderr"]
  3421. .as_str()
  3422. .expect("stderr")
  3423. .contains("oops"));
  3424. let timeout = execute_tool("bash", &json!({ "command": "sleep 1", "timeout": 10 }))
  3425. .expect("bash timeout should return output");
  3426. let timeout_output: serde_json::Value = serde_json::from_str(&timeout).expect("json");
  3427. assert_eq!(timeout_output["interrupted"], true);
  3428. assert_eq!(timeout_output["returnCodeInterpretation"], "timeout");
  3429. assert!(timeout_output["stderr"]
  3430. .as_str()
  3431. .expect("stderr")
  3432. .contains("Command exceeded timeout"));
  3433. let background = execute_tool(
  3434. "bash",
  3435. &json!({ "command": "sleep 1", "run_in_background": true }),
  3436. )
  3437. .expect("bash background should succeed");
  3438. let background_output: serde_json::Value = serde_json::from_str(&background).expect("json");
  3439. assert!(background_output["backgroundTaskId"].as_str().is_some());
  3440. assert_eq!(background_output["noOutputExpected"], true);
  3441. }
  3442. #[test]
  3443. fn file_tools_cover_read_write_and_edit_behaviors() {
  3444. let _guard = env_lock()
  3445. .lock()
  3446. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3447. let root = temp_path("fs-suite");
  3448. fs::create_dir_all(&root).expect("create root");
  3449. let original_dir = std::env::current_dir().expect("cwd");
  3450. std::env::set_current_dir(&root).expect("set cwd");
  3451. let write_create = execute_tool(
  3452. "write_file",
  3453. &json!({ "path": "nested/demo.txt", "content": "alpha\nbeta\nalpha\n" }),
  3454. )
  3455. .expect("write create should succeed");
  3456. let write_create_output: serde_json::Value =
  3457. serde_json::from_str(&write_create).expect("json");
  3458. assert_eq!(write_create_output["type"], "create");
  3459. assert!(root.join("nested/demo.txt").exists());
  3460. let write_update = execute_tool(
  3461. "write_file",
  3462. &json!({ "path": "nested/demo.txt", "content": "alpha\nbeta\ngamma\n" }),
  3463. )
  3464. .expect("write update should succeed");
  3465. let write_update_output: serde_json::Value =
  3466. serde_json::from_str(&write_update).expect("json");
  3467. assert_eq!(write_update_output["type"], "update");
  3468. assert_eq!(write_update_output["originalFile"], "alpha\nbeta\nalpha\n");
  3469. let read_full = execute_tool("read_file", &json!({ "path": "nested/demo.txt" }))
  3470. .expect("read full should succeed");
  3471. let read_full_output: serde_json::Value = serde_json::from_str(&read_full).expect("json");
  3472. assert_eq!(read_full_output["file"]["content"], "alpha\nbeta\ngamma");
  3473. assert_eq!(read_full_output["file"]["startLine"], 1);
  3474. let read_slice = execute_tool(
  3475. "read_file",
  3476. &json!({ "path": "nested/demo.txt", "offset": 1, "limit": 1 }),
  3477. )
  3478. .expect("read slice should succeed");
  3479. let read_slice_output: serde_json::Value = serde_json::from_str(&read_slice).expect("json");
  3480. assert_eq!(read_slice_output["file"]["content"], "beta");
  3481. assert_eq!(read_slice_output["file"]["startLine"], 2);
  3482. let read_past_end = execute_tool(
  3483. "read_file",
  3484. &json!({ "path": "nested/demo.txt", "offset": 50 }),
  3485. )
  3486. .expect("read past EOF should succeed");
  3487. let read_past_end_output: serde_json::Value =
  3488. serde_json::from_str(&read_past_end).expect("json");
  3489. assert_eq!(read_past_end_output["file"]["content"], "");
  3490. assert_eq!(read_past_end_output["file"]["startLine"], 4);
  3491. let read_error = execute_tool("read_file", &json!({ "path": "missing.txt" }))
  3492. .expect_err("missing file should fail");
  3493. assert!(!read_error.is_empty());
  3494. let edit_once = execute_tool(
  3495. "edit_file",
  3496. &json!({ "path": "nested/demo.txt", "old_string": "alpha", "new_string": "omega" }),
  3497. )
  3498. .expect("single edit should succeed");
  3499. let edit_once_output: serde_json::Value = serde_json::from_str(&edit_once).expect("json");
  3500. assert_eq!(edit_once_output["replaceAll"], false);
  3501. assert_eq!(
  3502. fs::read_to_string(root.join("nested/demo.txt")).expect("read file"),
  3503. "omega\nbeta\ngamma\n"
  3504. );
  3505. execute_tool(
  3506. "write_file",
  3507. &json!({ "path": "nested/demo.txt", "content": "alpha\nbeta\nalpha\n" }),
  3508. )
  3509. .expect("reset file");
  3510. let edit_all = execute_tool(
  3511. "edit_file",
  3512. &json!({
  3513. "path": "nested/demo.txt",
  3514. "old_string": "alpha",
  3515. "new_string": "omega",
  3516. "replace_all": true
  3517. }),
  3518. )
  3519. .expect("replace all should succeed");
  3520. let edit_all_output: serde_json::Value = serde_json::from_str(&edit_all).expect("json");
  3521. assert_eq!(edit_all_output["replaceAll"], true);
  3522. assert_eq!(
  3523. fs::read_to_string(root.join("nested/demo.txt")).expect("read file"),
  3524. "omega\nbeta\nomega\n"
  3525. );
  3526. let edit_same = execute_tool(
  3527. "edit_file",
  3528. &json!({ "path": "nested/demo.txt", "old_string": "omega", "new_string": "omega" }),
  3529. )
  3530. .expect_err("identical old/new should fail");
  3531. assert!(edit_same.contains("must differ"));
  3532. let edit_missing = execute_tool(
  3533. "edit_file",
  3534. &json!({ "path": "nested/demo.txt", "old_string": "missing", "new_string": "omega" }),
  3535. )
  3536. .expect_err("missing substring should fail");
  3537. assert!(edit_missing.contains("old_string not found"));
  3538. std::env::set_current_dir(&original_dir).expect("restore cwd");
  3539. let _ = fs::remove_dir_all(root);
  3540. }
  3541. #[test]
  3542. fn glob_and_grep_tools_cover_success_and_errors() {
  3543. let _guard = env_lock()
  3544. .lock()
  3545. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3546. let root = temp_path("search-suite");
  3547. fs::create_dir_all(root.join("nested")).expect("create root");
  3548. let original_dir = std::env::current_dir().expect("cwd");
  3549. std::env::set_current_dir(&root).expect("set cwd");
  3550. fs::write(
  3551. root.join("nested/lib.rs"),
  3552. "fn main() {}\nlet alpha = 1;\nlet alpha = 2;\n",
  3553. )
  3554. .expect("write rust file");
  3555. fs::write(root.join("nested/notes.txt"), "alpha\nbeta\n").expect("write txt file");
  3556. let globbed = execute_tool("glob_search", &json!({ "pattern": "nested/*.rs" }))
  3557. .expect("glob should succeed");
  3558. let globbed_output: serde_json::Value = serde_json::from_str(&globbed).expect("json");
  3559. assert_eq!(globbed_output["numFiles"], 1);
  3560. assert!(globbed_output["filenames"][0]
  3561. .as_str()
  3562. .expect("filename")
  3563. .ends_with("nested/lib.rs"));
  3564. let glob_error = execute_tool("glob_search", &json!({ "pattern": "[" }))
  3565. .expect_err("invalid glob should fail");
  3566. assert!(!glob_error.is_empty());
  3567. let grep_content = execute_tool(
  3568. "grep_search",
  3569. &json!({
  3570. "pattern": "alpha",
  3571. "path": "nested",
  3572. "glob": "*.rs",
  3573. "output_mode": "content",
  3574. "-n": true,
  3575. "head_limit": 1,
  3576. "offset": 1
  3577. }),
  3578. )
  3579. .expect("grep content should succeed");
  3580. let grep_content_output: serde_json::Value =
  3581. serde_json::from_str(&grep_content).expect("json");
  3582. assert_eq!(grep_content_output["numFiles"], 0);
  3583. assert!(grep_content_output["appliedLimit"].is_null());
  3584. assert_eq!(grep_content_output["appliedOffset"], 1);
  3585. assert!(grep_content_output["content"]
  3586. .as_str()
  3587. .expect("content")
  3588. .contains("let alpha = 2;"));
  3589. let grep_count = execute_tool(
  3590. "grep_search",
  3591. &json!({ "pattern": "alpha", "path": "nested", "output_mode": "count" }),
  3592. )
  3593. .expect("grep count should succeed");
  3594. let grep_count_output: serde_json::Value = serde_json::from_str(&grep_count).expect("json");
  3595. assert_eq!(grep_count_output["numMatches"], 3);
  3596. let grep_error = execute_tool(
  3597. "grep_search",
  3598. &json!({ "pattern": "(alpha", "path": "nested" }),
  3599. )
  3600. .expect_err("invalid regex should fail");
  3601. assert!(!grep_error.is_empty());
  3602. std::env::set_current_dir(&original_dir).expect("restore cwd");
  3603. let _ = fs::remove_dir_all(root);
  3604. }
  3605. #[test]
  3606. fn sleep_waits_and_reports_duration() {
  3607. let started = std::time::Instant::now();
  3608. let result =
  3609. execute_tool("Sleep", &json!({"duration_ms": 20})).expect("Sleep should succeed");
  3610. let elapsed = started.elapsed();
  3611. let output: serde_json::Value = serde_json::from_str(&result).expect("json");
  3612. assert_eq!(output["duration_ms"], 20);
  3613. assert!(output["message"]
  3614. .as_str()
  3615. .expect("message")
  3616. .contains("Slept for 20ms"));
  3617. assert!(elapsed >= Duration::from_millis(15));
  3618. }
  3619. #[test]
  3620. fn brief_returns_sent_message_and_attachment_metadata() {
  3621. let attachment = std::env::temp_dir().join(format!(
  3622. "clawd-brief-{}.png",
  3623. std::time::SystemTime::now()
  3624. .duration_since(std::time::UNIX_EPOCH)
  3625. .expect("time")
  3626. .as_nanos()
  3627. ));
  3628. std::fs::write(&attachment, b"png-data").expect("write attachment");
  3629. let result = execute_tool(
  3630. "SendUserMessage",
  3631. &json!({
  3632. "message": "hello user",
  3633. "attachments": [attachment.display().to_string()],
  3634. "status": "normal"
  3635. }),
  3636. )
  3637. .expect("SendUserMessage should succeed");
  3638. let output: serde_json::Value = serde_json::from_str(&result).expect("json");
  3639. assert_eq!(output["message"], "hello user");
  3640. assert!(output["sentAt"].as_str().is_some());
  3641. assert_eq!(output["attachments"][0]["isImage"], true);
  3642. let _ = std::fs::remove_file(attachment);
  3643. }
  3644. #[test]
  3645. fn config_reads_and_writes_supported_values() {
  3646. let _guard = env_lock()
  3647. .lock()
  3648. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3649. let root = std::env::temp_dir().join(format!(
  3650. "clawd-config-{}",
  3651. std::time::SystemTime::now()
  3652. .duration_since(std::time::UNIX_EPOCH)
  3653. .expect("time")
  3654. .as_nanos()
  3655. ));
  3656. let home = root.join("home");
  3657. let cwd = root.join("cwd");
  3658. std::fs::create_dir_all(home.join(".claude")).expect("home dir");
  3659. std::fs::create_dir_all(cwd.join(".claude")).expect("cwd dir");
  3660. std::fs::write(
  3661. home.join(".claude").join("settings.json"),
  3662. r#"{"verbose":false}"#,
  3663. )
  3664. .expect("write global settings");
  3665. let original_home = std::env::var("HOME").ok();
  3666. let original_claude_home = std::env::var("CLAUDE_CONFIG_HOME").ok();
  3667. let original_dir = std::env::current_dir().expect("cwd");
  3668. std::env::set_var("HOME", &home);
  3669. std::env::remove_var("CLAUDE_CONFIG_HOME");
  3670. std::env::set_current_dir(&cwd).expect("set cwd");
  3671. let get = execute_tool("Config", &json!({"setting": "verbose"})).expect("get config");
  3672. let get_output: serde_json::Value = serde_json::from_str(&get).expect("json");
  3673. assert_eq!(get_output["value"], false);
  3674. let set = execute_tool(
  3675. "Config",
  3676. &json!({"setting": "permissions.defaultMode", "value": "plan"}),
  3677. )
  3678. .expect("set config");
  3679. let set_output: serde_json::Value = serde_json::from_str(&set).expect("json");
  3680. assert_eq!(set_output["operation"], "set");
  3681. assert_eq!(set_output["newValue"], "plan");
  3682. let invalid = execute_tool(
  3683. "Config",
  3684. &json!({"setting": "permissions.defaultMode", "value": "bogus"}),
  3685. )
  3686. .expect_err("invalid config value should error");
  3687. assert!(invalid.contains("Invalid value"));
  3688. let unknown =
  3689. execute_tool("Config", &json!({"setting": "nope"})).expect("unknown setting result");
  3690. let unknown_output: serde_json::Value = serde_json::from_str(&unknown).expect("json");
  3691. assert_eq!(unknown_output["success"], false);
  3692. std::env::set_current_dir(&original_dir).expect("restore cwd");
  3693. match original_home {
  3694. Some(value) => std::env::set_var("HOME", value),
  3695. None => std::env::remove_var("HOME"),
  3696. }
  3697. match original_claude_home {
  3698. Some(value) => std::env::set_var("CLAUDE_CONFIG_HOME", value),
  3699. None => std::env::remove_var("CLAUDE_CONFIG_HOME"),
  3700. }
  3701. let _ = std::fs::remove_dir_all(root);
  3702. }
  3703. #[test]
  3704. fn structured_output_echoes_input_payload() {
  3705. let result = execute_tool("StructuredOutput", &json!({"ok": true, "items": [1, 2, 3]}))
  3706. .expect("StructuredOutput should succeed");
  3707. let output: serde_json::Value = serde_json::from_str(&result).expect("json");
  3708. assert_eq!(output["data"], "Structured output provided successfully");
  3709. assert_eq!(output["structured_output"]["ok"], true);
  3710. assert_eq!(output["structured_output"]["items"][1], 2);
  3711. }
  3712. #[test]
  3713. fn repl_executes_python_code() {
  3714. let result = execute_tool(
  3715. "REPL",
  3716. &json!({"language": "python", "code": "print(1 + 1)", "timeout_ms": 500}),
  3717. )
  3718. .expect("REPL should succeed");
  3719. let output: serde_json::Value = serde_json::from_str(&result).expect("json");
  3720. assert_eq!(output["language"], "python");
  3721. assert_eq!(output["exitCode"], 0);
  3722. assert!(output["stdout"].as_str().expect("stdout").contains('2'));
  3723. }
  3724. #[test]
  3725. fn powershell_runs_via_stub_shell() {
  3726. let _guard = env_lock()
  3727. .lock()
  3728. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3729. let dir = std::env::temp_dir().join(format!(
  3730. "clawd-pwsh-bin-{}",
  3731. std::time::SystemTime::now()
  3732. .duration_since(std::time::UNIX_EPOCH)
  3733. .expect("time")
  3734. .as_nanos()
  3735. ));
  3736. std::fs::create_dir_all(&dir).expect("create dir");
  3737. let script = dir.join("pwsh");
  3738. std::fs::write(
  3739. &script,
  3740. r#"#!/bin/sh
  3741. while [ "$1" != "-Command" ] && [ $# -gt 0 ]; do shift; done
  3742. shift
  3743. printf 'pwsh:%s' "$1"
  3744. "#,
  3745. )
  3746. .expect("write script");
  3747. std::process::Command::new("/bin/chmod")
  3748. .arg("+x")
  3749. .arg(&script)
  3750. .status()
  3751. .expect("chmod");
  3752. let original_path = std::env::var("PATH").unwrap_or_default();
  3753. std::env::set_var("PATH", format!("{}:{}", dir.display(), original_path));
  3754. let result = execute_tool(
  3755. "PowerShell",
  3756. &json!({"command": "Write-Output hello", "timeout": 1000}),
  3757. )
  3758. .expect("PowerShell should succeed");
  3759. let background = execute_tool(
  3760. "PowerShell",
  3761. &json!({"command": "Write-Output hello", "run_in_background": true}),
  3762. )
  3763. .expect("PowerShell background should succeed");
  3764. std::env::set_var("PATH", original_path);
  3765. let _ = std::fs::remove_dir_all(dir);
  3766. let output: serde_json::Value = serde_json::from_str(&result).expect("json");
  3767. assert_eq!(output["stdout"], "pwsh:Write-Output hello");
  3768. assert!(output["stderr"].as_str().expect("stderr").is_empty());
  3769. let background_output: serde_json::Value = serde_json::from_str(&background).expect("json");
  3770. assert!(background_output["backgroundTaskId"].as_str().is_some());
  3771. assert_eq!(background_output["backgroundedByUser"], true);
  3772. assert_eq!(background_output["assistantAutoBackgrounded"], false);
  3773. }
  3774. #[test]
  3775. fn powershell_errors_when_shell_is_missing() {
  3776. let _guard = env_lock()
  3777. .lock()
  3778. .unwrap_or_else(std::sync::PoisonError::into_inner);
  3779. let original_path = std::env::var("PATH").unwrap_or_default();
  3780. let empty_dir = std::env::temp_dir().join(format!(
  3781. "clawd-empty-bin-{}",
  3782. std::time::SystemTime::now()
  3783. .duration_since(std::time::UNIX_EPOCH)
  3784. .expect("time")
  3785. .as_nanos()
  3786. ));
  3787. std::fs::create_dir_all(&empty_dir).expect("create empty dir");
  3788. std::env::set_var("PATH", empty_dir.display().to_string());
  3789. let err = execute_tool("PowerShell", &json!({"command": "Write-Output hello"}))
  3790. .expect_err("PowerShell should fail when shell is missing");
  3791. std::env::set_var("PATH", original_path);
  3792. let _ = std::fs::remove_dir_all(empty_dir);
  3793. assert!(err.contains("PowerShell executable not found"));
  3794. }
  3795. struct TestServer {
  3796. addr: SocketAddr,
  3797. shutdown: Option<std::sync::mpsc::Sender<()>>,
  3798. handle: Option<thread::JoinHandle<()>>,
  3799. }
  3800. impl TestServer {
  3801. fn spawn(handler: Arc<dyn Fn(&str) -> HttpResponse + Send + Sync + 'static>) -> Self {
  3802. let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
  3803. listener
  3804. .set_nonblocking(true)
  3805. .expect("set nonblocking listener");
  3806. let addr = listener.local_addr().expect("local addr");
  3807. let (tx, rx) = std::sync::mpsc::channel::<()>();
  3808. let handle = thread::spawn(move || loop {
  3809. if rx.try_recv().is_ok() {
  3810. break;
  3811. }
  3812. match listener.accept() {
  3813. Ok((mut stream, _)) => {
  3814. let mut buffer = [0_u8; 4096];
  3815. let size = stream.read(&mut buffer).expect("read request");
  3816. let request = String::from_utf8_lossy(&buffer[..size]).into_owned();
  3817. let request_line = request.lines().next().unwrap_or_default().to_string();
  3818. let response = handler(&request_line);
  3819. stream
  3820. .write_all(response.to_bytes().as_slice())
  3821. .expect("write response");
  3822. }
  3823. Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
  3824. thread::sleep(Duration::from_millis(10));
  3825. }
  3826. Err(error) => panic!("server accept failed: {error}"),
  3827. }
  3828. });
  3829. Self {
  3830. addr,
  3831. shutdown: Some(tx),
  3832. handle: Some(handle),
  3833. }
  3834. }
  3835. fn addr(&self) -> SocketAddr {
  3836. self.addr
  3837. }
  3838. }
  3839. impl Drop for TestServer {
  3840. fn drop(&mut self) {
  3841. if let Some(tx) = self.shutdown.take() {
  3842. let _ = tx.send(());
  3843. }
  3844. if let Some(handle) = self.handle.take() {
  3845. handle.join().expect("join test server");
  3846. }
  3847. }
  3848. }
  3849. struct HttpResponse {
  3850. status: u16,
  3851. reason: &'static str,
  3852. content_type: &'static str,
  3853. body: String,
  3854. }
  3855. impl HttpResponse {
  3856. fn html(status: u16, reason: &'static str, body: &str) -> Self {
  3857. Self {
  3858. status,
  3859. reason,
  3860. content_type: "text/html; charset=utf-8",
  3861. body: body.to_string(),
  3862. }
  3863. }
  3864. fn text(status: u16, reason: &'static str, body: &str) -> Self {
  3865. Self {
  3866. status,
  3867. reason,
  3868. content_type: "text/plain; charset=utf-8",
  3869. body: body.to_string(),
  3870. }
  3871. }
  3872. fn to_bytes(&self) -> Vec<u8> {
  3873. format!(
  3874. "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
  3875. self.status,
  3876. self.reason,
  3877. self.content_type,
  3878. self.body.len(),
  3879. self.body
  3880. )
  3881. .into_bytes()
  3882. }
  3883. }
  3884. }