dispach 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +131 -31
  2. package/dist/App-b1yrwrcq.js +11 -0
  3. package/dist/{App-dxqm39zx.js.map → App-b1yrwrcq.js.map} +1 -1
  4. package/dist/{ConfigEditor-7v5nebvy.js → ConfigEditor-n8hdw6r7.js} +4 -4
  5. package/dist/{ConfigEditor-7v5nebvy.js.map → ConfigEditor-n8hdw6r7.js.map} +1 -1
  6. package/dist/{KeyProbe-vjhmdpx6.js → KeyProbe-9jjeze5r.js} +3 -3
  7. package/dist/{KeyProbe-vjhmdpx6.js.map → KeyProbe-9jjeze5r.js.map} +1 -1
  8. package/dist/{Picker-jxaesaxy.js → Picker-hfeh1g6m.js} +3 -3
  9. package/dist/{Picker-jxaesaxy.js.map → Picker-hfeh1g6m.js.map} +1 -1
  10. package/dist/{SessionPicker-z2t0p4b5.js → SessionPicker-zyqkg4dn.js} +3 -3
  11. package/dist/{SessionPicker-z2t0p4b5.js.map → SessionPicker-zyqkg4dn.js.map} +1 -1
  12. package/dist/{SkillBrowser-yyf2gy0q.js → SkillBrowser-3qdp8080.js} +3 -3
  13. package/dist/{SkillBrowser-yyf2gy0q.js.map → SkillBrowser-3qdp8080.js.map} +1 -1
  14. package/dist/WizardApp-vzpbydy3.js +5 -0
  15. package/dist/{WizardApp-12ndxgqv.js.map → WizardApp-vzpbydy3.js.map} +1 -1
  16. package/dist/client.js +10 -10
  17. package/dist/client.js.map +5 -5
  18. package/dist/{config-yz0nz51b.js → config-g7za9x13.js} +13 -13
  19. package/dist/{config-yz0nz51b.js.map → config-g7za9x13.js.map} +1 -1
  20. package/dist/credential-npr6z8c8.js +19 -0
  21. package/dist/{credential-wgt4gvcz.js.map → credential-npr6z8c8.js.map} +2 -2
  22. package/dist/index-02dn6m2j.js +7 -0
  23. package/dist/{index-h2yds678.js.map → index-02dn6m2j.js.map} +1 -1
  24. package/dist/index-0d93hyfc.js +6 -0
  25. package/dist/{index-rqbtm761.js.map → index-0d93hyfc.js.map} +1 -1
  26. package/dist/index-1c5113t4.js +66 -0
  27. package/dist/index-1c5113t4.js.map +12 -0
  28. package/dist/{index-3nwfz9jq.js → index-258d8bzg.js} +10 -10
  29. package/dist/{index-3nwfz9jq.js.map → index-258d8bzg.js.map} +1 -1
  30. package/dist/{index-9d011p3q.js → index-3g3ny01d.js} +4 -4
  31. package/dist/{index-9d011p3q.js.map → index-3g3ny01d.js.map} +1 -1
  32. package/dist/{index-8bmhd2hj.js → index-4cf6v9nb.js} +4 -4
  33. package/dist/{index-8bmhd2hj.js.map → index-4cf6v9nb.js.map} +1 -1
  34. package/dist/{index-bwckzbf8.js → index-4z7axw4r.js} +4 -4
  35. package/dist/{index-bwckzbf8.js.map → index-4z7axw4r.js.map} +1 -1
  36. package/dist/{index-xgqzk5cq.js → index-6p999cx4.js} +6 -6
  37. package/dist/{index-xgqzk5cq.js.map → index-6p999cx4.js.map} +1 -1
  38. package/dist/index-6q4wf8e3.js +6 -0
  39. package/dist/{index-jym27m75.js.map → index-6q4wf8e3.js.map} +1 -1
  40. package/dist/{index-cx3vz7sf.js → index-9r0wyj6w.js} +4 -4
  41. package/dist/{index-cx3vz7sf.js.map → index-9r0wyj6w.js.map} +1 -1
  42. package/dist/{index-j97vttdt.js → index-ammv5st7.js} +6 -6
  43. package/dist/{index-j97vttdt.js.map → index-ammv5st7.js.map} +1 -1
  44. package/dist/{index-qc2vrq9z.js → index-cqqb6gaq.js} +5 -5
  45. package/dist/{index-qc2vrq9z.js.map → index-cqqb6gaq.js.map} +1 -1
  46. package/dist/{index-jk0def33.js → index-d4x6yvqh.js} +4 -4
  47. package/dist/{index-jk0def33.js.map → index-d4x6yvqh.js.map} +1 -1
  48. package/dist/index-fecm8xe7.js +77 -0
  49. package/dist/index-fecm8xe7.js.map +12 -0
  50. package/dist/{index-e8n70sgj.js → index-fex44816.js} +4 -4
  51. package/dist/{index-e8n70sgj.js.map → index-fex44816.js.map} +1 -1
  52. package/dist/{index-gbnc99j8.js → index-ff514z3y.js} +9 -9
  53. package/dist/{index-gbnc99j8.js.map → index-ff514z3y.js.map} +1 -1
  54. package/dist/{index-t1xvacym.js → index-gme2egyq.js} +4 -4
  55. package/dist/{index-t1xvacym.js.map → index-gme2egyq.js.map} +1 -1
  56. package/dist/{index-mrtb5y08.js → index-gz9x25tz.js} +4 -4
  57. package/dist/{index-mrtb5y08.js.map → index-gz9x25tz.js.map} +1 -1
  58. package/dist/{index-9nsfs0vy.js → index-h9mw7b9d.js} +4 -4
  59. package/dist/{index-9nsfs0vy.js.map → index-h9mw7b9d.js.map} +1 -1
  60. package/dist/{index-6b7qvh1x.js → index-hwpvhaza.js} +4 -4
  61. package/dist/{index-6b7qvh1x.js.map → index-hwpvhaza.js.map} +1 -1
  62. package/dist/{index-6z0yr17z.js → index-j55s3ehk.js} +7 -7
  63. package/dist/{index-6z0yr17z.js.map → index-j55s3ehk.js.map} +1 -1
  64. package/dist/{index-mgdgx22q.js → index-j7gyr5nx.js} +6 -6
  65. package/dist/{index-mgdgx22q.js.map → index-j7gyr5nx.js.map} +1 -1
  66. package/dist/{index-7da4fqcr.js → index-mtn0g9vc.js} +5 -5
  67. package/dist/{index-7da4fqcr.js.map → index-mtn0g9vc.js.map} +1 -1
  68. package/dist/{index-rqzg861g.js → index-qdbq8crg.js} +4 -4
  69. package/dist/{index-rqzg861g.js.map → index-qdbq8crg.js.map} +1 -1
  70. package/dist/{index-xqyms08r.js → index-s9mbq7h6.js} +4 -4
  71. package/dist/{index-xqyms08r.js.map → index-s9mbq7h6.js.map} +1 -1
  72. package/dist/{index-9f9pp2ef.js → index-tf71ap9v.js} +4 -4
  73. package/dist/{index-9f9pp2ef.js.map → index-tf71ap9v.js.map} +1 -1
  74. package/dist/index-ttwyrdjs.js +427 -0
  75. package/dist/index-ttwyrdjs.js.map +11 -0
  76. package/dist/{index-2cvtz0fy.js → index-tv4yv7d2.js} +228 -228
  77. package/dist/{index-2cvtz0fy.js.map → index-tv4yv7d2.js.map} +9 -9
  78. package/dist/{index-fvhg0xyd.js → index-ty24n0jh.js} +79 -79
  79. package/dist/{index-fvhg0xyd.js.map → index-ty24n0jh.js.map} +1 -1
  80. package/dist/index-v8e92nfw.js +6 -0
  81. package/dist/{index-b8zwg8a3.js.map → index-v8e92nfw.js.map} +1 -1
  82. package/dist/index-vgc3y3rm.js +6 -0
  83. package/dist/{index-my5cjx00.js.map → index-vgc3y3rm.js.map} +1 -1
  84. package/dist/index-whaw4b18.js +6 -0
  85. package/dist/index-whaw4b18.js.map +10 -0
  86. package/dist/index.js +202 -198
  87. package/dist/index.js.map +6 -6
  88. package/dist/lib/bootstrap.d.ts +13 -0
  89. package/dist/lib/bootstrap.d.ts.map +1 -1
  90. package/dist/lib/commands.d.ts.map +1 -1
  91. package/dist/lib/init-flow.d.ts +17 -4
  92. package/dist/lib/init-flow.d.ts.map +1 -1
  93. package/dist/lib/provision.d.ts.map +1 -1
  94. package/dist/serve.d.ts.map +1 -1
  95. package/dist/{web-w7r68df1.js → web-vkb16r62.js} +5 -5
  96. package/dist/{web-w7r68df1.js.map → web-vkb16r62.js.map} +1 -1
  97. package/dist/wire.js +10 -10
  98. package/dist/wire.js.map +4 -4
  99. package/package.json +2 -2
  100. package/dist/App-dxqm39zx.js +0 -11
  101. package/dist/WizardApp-12ndxgqv.js +0 -5
  102. package/dist/credential-wgt4gvcz.js +0 -19
  103. package/dist/index-9pj1ws0p.js +0 -77
  104. package/dist/index-9pj1ws0p.js.map +0 -12
  105. package/dist/index-b5wwtxzk.js +0 -66
  106. package/dist/index-b5wwtxzk.js.map +0 -12
  107. package/dist/index-b8zwg8a3.js +0 -6
  108. package/dist/index-bry9bzt3.js +0 -427
  109. package/dist/index-bry9bzt3.js.map +0 -11
  110. package/dist/index-h2yds678.js +0 -7
  111. package/dist/index-jym27m75.js +0 -6
  112. package/dist/index-my5cjx00.js +0 -6
  113. package/dist/index-rqbtm761.js +0 -6
  114. package/dist/index-yr25dnf5.js +0 -6
  115. package/dist/index-yr25dnf5.js.map +0 -10
@@ -1,51 +1,51 @@
1
1
  #!/usr/bin/env node
2
- import{e,E,t,v,_e,$e,K,Ct,H,br,x,A,Re,kr,Ie,Ke,xr,p}from"./index-2cvtz0fy.js";import{Q,j,y,f,Se,Xr,Jr,Qr,Un,cr}from"./index-b5wwtxzk.js";import{yn,wn}from"./index-jk0def33.js";import{ro,oo,vt}from"./index-t1xvacym.js";import{he,b,J,ue,Y,ie}from"./index-xgqzk5cq.js";import{ee,B}from"./index-7da4fqcr.js";import{Zn,tn}from"./index-bry9bzt3.js";import{pe}from"./index-xqyms08r.js";import{l,m,d,c}from"./index-mgdgx22q.js";import{we,n,s}from"./index-my5cjx00.js";import{cpSync as sc,existsSync as te,mkdirSync as Nr,readdirSync as He,readFileSync as ic,rmSync as oc,statSync as Lr,writeFileSync as ac}from"node:fs";import{basename as Cr,isAbsolute as Mr,join as G,relative as cc,resolve as Et}from"node:path";import{existsSync as Hr,readFileSync as Wr,writeFileSync as Rt}from"node:fs";import{join as Gr}from"node:path";var qr=".origins.json",At=1;function We(r){return Gr(r,qr)}function ge(r){let i=We(r);if(!Hr(i))return{};try{return JSON.parse(Wr(i,"utf8")).origins??{}}catch{return{}}}function xt(r,i){let o={...ge(r),...i};Rt(We(r),`${JSON.stringify({version:At,origins:o},null,4)}
3
- `)}function On(r,i){let o=ge(r);if(o[i]===void 0)return;let a=Object.fromEntries(Object.entries(o).filter(([u])=>u!==i));Rt(We(r),`${JSON.stringify({version:At,origins:a},null,4)}
4
- `)}class Z extends Error{status;retryable;retryAfterMs;detail;constructor(r){super(r.message);this.name="TelegramApiError",this.status=r.status,this.retryable=r.retryable,this.retryAfterMs=r.retryAfterMs,this.detail=r.detail}}var Vr="https://api.telegram.org";class qe{#e;#t;#s;constructor(r){this.#e=r.token,this.#t=r.fetch??((i,o)=>fetch(i,o)),this.#s=(r.baseUrl??Vr).replace(/\/+$/,"")}async call(r,i,o){let a;try{a=await this.#t(`${this.#s}/bot${this.#e}/${r}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i??{}),...o===void 0?{}:{signal:o}})}catch(h){throw new Z({message:`Telegram ${r} did not complete: ${h instanceof Error?h.message:String(h)}`,status:0,retryable:!0,detail:{code:"telegram_unreachable",message:`Could not reach the Telegram Bot API for ${r}.`,hint:"Check network access from this host. api.telegram.org is blocked in some networks and from some cloud regions; a webhook deployment behind a proxy still needs outbound access for sendMessage."}})}let u=await a.json().catch(()=>({}));if(a.ok&&u.ok&&u.result!==void 0)return u.result;throw Yr(r,a.status,u)}getMe(r){return this.call("getMe",{},r)}getUpdates(r,i){return this.call("getUpdates",{offset:r.offset,timeout:r.timeout,limit:r.limit??100,allowed_updates:["message"]},i)}sendMessage(r,i){return this.call("sendMessage",{chat_id:r.chatId,text:r.text,...r.threadId===void 0?{}:{message_thread_id:r.threadId}},i)}sendChatAction(r){return this.call("sendChatAction",{chat_id:r.chatId,action:"typing",...r.threadId===void 0?{}:{message_thread_id:r.threadId}})}setWebhook(r,i){return this.call("setWebhook",{url:r.url,allowed_updates:["message"],...r.secretToken===void 0?{}:{secret_token:r.secretToken},...r.dropPending===void 0?{}:{drop_pending_updates:r.dropPending}},i)}deleteWebhook(r){return this.call("deleteWebhook",{},r)}}function Yr(r,i,o){let a=o.description??`HTTP ${i}`,u=o.error_code??i,h=o.parameters?.retry_after;if(u===429)return new Z({message:`Telegram rate-limited ${r}: ${a}`,status:u,retryable:!0,...h===void 0?{}:{retryAfterMs:h*1000},detail:{code:"telegram_rate_limited",message:`Telegram rate-limited ${r}.`,hint:h===void 0?"The outbox will back off and retry. Sustained rate limiting on one chat usually means replies are being split into many chunks — check the reply length.":`Telegram asked for ${h}s. The outbox honours that verbatim rather than applying its own backoff.`}});if(u===401)return new Z({message:`Telegram rejected the bot token on ${r}: ${a}`,status:u,retryable:!1,detail:{code:"telegram_unauthorized",message:"The Telegram bot token was rejected.",hint:"Check the variable named by the channel's tokenEnv. A token is revoked whenever /revoke is sent to @BotFather, and a regenerated token invalidates the old one immediately."}});if(u===409)return new Z({message:`Telegram reports a conflicting ${r}: ${a}`,status:u,retryable:!0,detail:{code:"telegram_conflict",message:"Another instance of this bot is already receiving updates.",hint:"Telegram allows one getUpdates consumer per bot token. Stop the other process — another terminal, a container that did not exit — or, if a webhook was registered earlier, this channel's own start clears it. Retried, so it recovers on its own once the other side stops."}});if(u===400&&/too long/i.test(a))return new Z({message:`Telegram refused ${r}: ${a}`,status:u,retryable:!1,detail:{code:"telegram_message_too_long",message:"A chunk exceeded Telegram's message limit.",hint:"This is a chunking bug, not a configuration problem: the transport declares maxMessageChars and core splits to it. Report the reply length — the splitter reserves room for a code-fence reopen, so the effective limit is slightly under 4096."}});let g=u===400||u===403;return new Z({message:`Telegram refused ${r}: ${a}`,status:u,retryable:!g,detail:{code:g?"telegram_refused":"telegram_error",message:`Telegram refused ${r}: ${a}`,hint:g?"Telegram reports this as a client error, so it is not retried. The usual causes are a chat the bot was removed from, a user who blocked it, or a chat id from a different bot — a chat id is not portable between bots.":"Treated as transient and retried with backoff. A 5xx from Telegram is usually brief."}})}var Zr=4096,es=30,Ot=[1000,2000,5000,15000,30000],ts=350;class Nt{id;type="telegram";limits={maxMessageChars:Zr,idempotentSend:!1,minSendIntervalMs:ts};#e;#t;#s;#i;#o;#r=0;#n=!1;#a;#c;constructor(r){this.id=r.id,this.#e=r.api??new qe({token:r.token}),this.#t=r.mode,this.#s=r.webhookUrl,this.#i=r.secretToken}async start(r){if(this.#n)return;if(this.#n=!0,this.#o=r,this.#a=new AbortController,this.#t==="webhook"){let i=this.#s;if(i===void 0||i===""){r.status("error","no webhookUrl"),r.error({code:"telegram_webhook_url_missing",message:`Channel "${this.id}" is in webhook mode but declares no webhookUrl.`,hint:"Set webhookUrl to the public HTTPS address this runtime is reachable at, ending in /v1/channels/<channelId>/webhook/<agentId>. Telegram will not deliver to plain HTTP, and a missing registration looks identical to a bot nobody is messaging.",field:`channels[${this.id}].webhookUrl`});return}try{await this.#e.setWebhook({url:i,...this.#i===void 0?{}:{secretToken:this.#i}}),r.status("connected",`webhook at ${i}`)}catch(o){r.status("error",o instanceof Error?o.message:String(o)),r.error(Ge(o,`registering the webhook for channel "${this.id}"`))}return}this.#c=this.#d(r,this.#a.signal)}async stop(){if(!this.#n)return;this.#n=!1,this.#a?.abort(),await this.#c?.catch(()=>{}),this.#c=void 0,this.#o?.status("disconnected"),this.#o=void 0}async send(r,i){let o=It(r.thread);try{let a=await this.#e.sendMessage({chatId:r.recipient,text:r.text,...o===void 0?{}:{threadId:o}},i);return{ok:!0,providerMessageId:String(a.message_id)}}catch(a){if(a instanceof Z)return{ok:!1,retryable:a.retryable,error:a.detail,...a.retryAfterMs===void 0?{}:{retryAfterMs:a.retryAfterMs}};return{ok:!1,retryable:!0,error:{code:"telegram_send_failed",message:a instanceof Error?a.message:String(a),hint:"An unclassified failure from the Telegram transport. Retried, because a failure nobody recognised is not a failure known to be permanent."}}}}async typing(r,i){let o=It(i);await this.#e.sendChatAction({chatId:r,...o===void 0?{}:{threadId:o}})}async webhook(r){if(this.#i!==void 0){let a=r.headers["x-telegram-bot-api-secret-token"]??"";if(!rs(a,this.#i))return{status:401,detail:"bad secret token"}}let i=this.#o;if(i===void 0)return{status:503,detail:"channel not started"};let o=r.body;if(o===void 0||typeof o!=="object")return{status:400,detail:"not an update"};return this.#l(i,o),{status:200}}async#d(r,i){let o=0,a=!1;try{await this.#e.deleteWebhook(i)}catch{}try{let u=await this.#e.getMe(i);a=!0,r.status("connected",u.username===void 0?"long-poll":`@${u.username}, long-poll`)}catch(u){if(i.aborted)return;r.status("error",u instanceof Error?u.message:String(u)),r.error(Ge(u,`checking the bot token for channel "${this.id}"`))}while(this.#n&&!i.aborted)try{let u=await this.#e.getUpdates({offset:this.#r,timeout:es},i);if(o>0)o=0,a=!0,r.status("connected","polling resumed");else if(!a)a=!0,r.status("connected","long-poll");for(let h of u)this.#r=Math.max(this.#r,h.update_id+1),this.#l(r,h)}catch(u){if(i.aborted)return;let h=Ot[Math.min(o,Ot.length-1)]??1000;if(o+=1,o===1||o%8===0)r.status("error",u instanceof Error?u.message:String(u)),r.error(Ge(u,`polling channel "${this.id}"`));await ss(h,i)}}#l(r,i){let o=i.message;if(o===void 0)return;let a=o.text??o.caption??"";if(a.trim()==="")return;if(o.from?.is_bot===!0)return;r.receive(ns(o,a))}}function ns(r,i){let o=r.from?.username,a=[r.from?.first_name,r.from?.last_name].filter(Boolean).join(" ");return{providerMessageId:`${r.chat.id}:${r.message_id}`,peerId:String(r.chat.id),...o===void 0?{}:{senderHandle:`@${o}`},...a===""?{}:{senderName:a},...r.message_thread_id===void 0?{}:{thread:String(r.message_thread_id)},text:i,receivedAt:new Date(r.date*1000).toISOString()}}function It(r){if(r===void 0)return;let i=Number.parseInt(r,10);return Number.isFinite(i)?i:void 0}function Ge(r,i){if(r instanceof Z)return r.detail;return{code:"telegram_channel_error",message:`${i} failed: ${r instanceof Error?r.message:String(r)}`,hint:"The channel keeps retrying and the rest of the runtime is unaffected. If this repeats, check network access to api.telegram.org and the token named by tokenEnv."}}function rs(r,i){if(r.length!==i.length)return!1;let o=0;for(let a=0;a<r.length;a+=1)o|=r.charCodeAt(a)^i.charCodeAt(a);return o===0}function ss(r,i){return new Promise((o)=>{let a=setTimeout(o,r);i.addEventListener("abort",()=>{clearTimeout(a),o()},{once:!0})})}var Ve=(r)=>{let i=r.config,o=ye(i,"tokenEnv")??"TELEGRAM_BOT_TOKEN",a=r.env[o];if(a===void 0||a==="")throw new y({code:"telegram_token_missing",message:`Channel "${r.id}" needs ${o}, which is not set.`,hint:`Export ${o}, or add it to the .env beside the manifest. Get a token from @BotFather with /newbot. This fails at load rather than at the first poll, because an unset variable is a configuration mistake and does not need a network round trip to discover.`,field:`channels[${r.id}].tokenEnv`});let u=ye(i,"mode")??"longpoll";if(u!=="longpoll"&&u!=="webhook")throw new y({code:"telegram_mode_invalid",message:`Channel "${r.id}" declares mode "${u}".`,hint:"mode is longpoll or webhook. Long-poll needs no inbound connectivity and is the right default for a laptop or a private network; webhook needs a public HTTPS URL and is lower latency.",field:`channels[${r.id}].mode`});let h=ye(i,"secretTokenEnv"),g=h===void 0?void 0:r.env[h];if(h!==void 0&&(g===void 0||g===""))throw new y({code:"telegram_secret_missing",message:`Channel "${r.id}" names secretTokenEnv ${h}, which is not set.`,hint:`Export ${h} with any random string, or remove secretTokenEnv. Naming a variable and leaving it empty would start a webhook that verifies nothing, which is worse than one that never claimed to.`,field:`channels[${r.id}].secretTokenEnv`});let w=ye(i,"apiBaseUrl"),k=ye(i,"webhookUrl");return new Nt({id:r.id,token:a,mode:u,...k===void 0?{}:{webhookUrl:k},...g===void 0||g===""?{}:{secretToken:g},...w===void 0?{}:{api:new qe({token:a,baseUrl:w})}})};function ye(r,i){let o=r[i];return typeof o==="string"&&o!==""?o:void 0}var is="0.1.0",Lt={name:"telegram",version:is,dispachApi:"^0.1",permissions:[{kind:"network",hosts:["api.telegram.org"]},{kind:"env",vars:["TELEGRAM_BOT_TOKEN"]}],setup(r){r.defineChannel("telegram",Ve)}};import{mkdirSync as os,readFileSync as as,renameSync as cs,writeFileSync as ds}from"node:fs";import{dirname as ls,isAbsolute as us,join as Mt,resolve as hs}from"node:path";import{mkdirSync as Bs,readFileSync as nn,renameSync as Hs,writeFileSync as Ws}from"node:fs";import{dirname as Gs,isAbsolute as qs,join as Wt,resolve as Js}from"node:path";var xe=1,Pt="tools.cache.json";function Oe(r){return us(r)?Mt(r,Q.stateDir,Pt):Mt(hs(r),Q.stateDir,Pt)}function fs(r){return typeof r==="object"&&r!==null&&typeof r.slug==="string"}function Ut(r){let i={version:xe,provider:"composio",fetchedAt:"",baseUrl:"",tools:{}},o;try{o=as(Oe(r),"utf8")}catch{return i}try{let a=JSON.parse(o);if(typeof a!=="object"||a===null)return i;let u=a;if(u.version!==xe)return i;let h={};for(let[g,w]of Object.entries(u.tools??{}))if(fs(w))h[g]=w;return{version:xe,provider:"composio",fetchedAt:typeof u.fetchedAt==="string"?u.fetchedAt:"",baseUrl:typeof u.baseUrl==="string"?u.baseUrl:"",tools:h}}catch{return i}}function ms(r,i,o,a){let u=Oe(r);os(ls(u),{recursive:!0});let h={version:xe,provider:"composio",fetchedAt:a().toISOString(),baseUrl:o,tools:i},g=`${u}.${process.pid}.tmp`;return ds(g,`${JSON.stringify(h,null,2)}
5
- `,"utf8"),cs(g,u),u}function Ft(r){return new y({code:"composio_key_missing",message:`The Composio provider needs an API key, and ${r} is not set.`,hint:`Set ${r} in the environment, or in a .env beside the manifest. Change which variable is read with tools.providers.composio.apiKeyEnv — the manifest holds the variable's name, never the key itself.`,field:"tools.providers.composio.apiKeyEnv"})}function Xe(r,i,o){return new y({code:"composio_schema_unsupported",message:`The Composio tool "${r}" declares "${o}" at ${i}, which this runtime's schema subset cannot express.`,hint:"Refused rather than dropped: that keyword decides which argument documents are valid, so ignoring it would hand the model a schema the endpoint disagrees with. Unpin this tool, or pin a sibling action with a flatter schema. Value constraints such as minimum and format are not affected — those are carried in the field's description.",field:"tools.pinned"})}function ps(r,i){return new y({code:"composio_cache_miss",message:`${r.length===1?"A pinned Composio tool is":`${r.length} pinned Composio tools are`} not in the resolution cache: ${r.join(", ")}.`,hint:`Boot resolves tools from ${i} and makes no network call, because nothing may touch the network before runtime.ready. Run \`${Q.slug} tools <manifest> --warm\` once to populate it, then start again.`,field:"tools.pinned"})}function le(r,i){return new f({code:"composio_request_failed",message:`Composio answered ${r}: ${i}`,hint:r===401||r===403?"The API key was rejected. Check the value of the variable named by tools.providers.composio.apiKeyEnv — a key that works in the dashboard can still be scoped to a different project.":r===404?"The tool slug does not exist at this API version. Slugs are case-sensitive and shaped like GMAIL_SEND_EMAIL; check it against the toolkit listing.":"Transient at this status. The runtime retries the refresh after readiness and keeps serving the cached catalogue meanwhile, so an agent already running is unaffected."})}function gs(r,i,o){return new f({code:"composio_execute_failed",message:`Composio could not run "${r}" (${i}): ${o}`,hint:"This is the tool's own failure, not a routing one — the arguments reached Composio and it refused them. A value constraint is the usual cause: this runtime carries minimum, format and pattern in the field description for the model to read, but does not enforce them locally, so an out-of-range value arrives here rather than as a repairable field error."})}function ys(r,i){return new f({code:"composio_not_connected",message:`"${r}" needs a connected ${i} account and none was found.`,hint:`Connect ${i} for this user in Composio, then set tools.providers.composio.userId to the same identifier. The tool resolves at load whether or not an account exists, because resolution reads a schema and execution needs the account — so this surfaces on first use rather than at boot.`})}function Dt(r){return new f({code:"composio_session_key_missing",message:`Searching your apps needs a Composio key, and ${r} is not set.`,hint:`Put the key in the .env beside this agent's manifest as ${r}=…, then restart. Get one from the Composio dashboard — the free tier is enough to connect an account and search the catalogue.`})}function Kt(r){return new f({code:"composio_no_match",message:`No tool matched "${r}".`,hint:'Describe the action and its object in plain English — "send an email", "create a calendar event", "post a message to a channel" — rather than naming a product or a tool slug. Composio matches on the use case, not on its own names.'})}var ws="https://backend.composio.dev/api/v3";function Bt(r){return/\/v3$/.test(r)?r.replace(/\/v3$/,"/v3.1"):r}var bs=100;function fe(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}async function ke(r){let i;try{i=await r.json()}catch{return r.statusText===""?"no detail in the response body":r.statusText}let o=fe(fe(i)?.error),a=typeof o?.message==="string"?o.message:void 0,u=typeof o?.suggested_fix==="string"?o.suggested_fix:void 0;if(a===void 0)return r.statusText===""?"no detail":r.statusText;return u===void 0||u===""?a:`${a} — ${u}`}class Jt{#e;#t;#s;constructor(r){this.#e=r.apiKey,this.#t=(r.baseUrl??ws).replace(/\/+$/,""),this.#s=r.fetch??((i,o)=>globalThis.fetch(i,o))}#i(r,i){return this.#s(`${this.#t}${r}`,{method:"GET",headers:{"x-api-key":this.#e,accept:"application/json"},...i===void 0?{}:{signal:i}})}async#o(r,i){let o=await this.#i(r,i);if(!o.ok)throw le(o.status,await ke(o));return o.json()}async tool(r,i){let o=await this.#i(`/tools/${encodeURIComponent(r)}`,i);if(o.status===404)return;if(!o.ok)throw le(o.status,await ke(o));let a=fe(await o.json());return typeof a?.slug==="string"?a:void 0}async slugs(r){let i=[],o;for(let a=0;a<400;a+=1){let u=new URLSearchParams({limit:String(bs)});if(o!==void 0)u.set("cursor",o);let h=await this.#o(`/tools?${u.toString()}`,r);for(let w of h.items??[])if(typeof w.slug==="string")i.push(w.slug);let g=h.next_cursor;if(g===null||g===void 0||g===""||g===o)break;o=g}return i}async execute(r,i,o,a){let u=await this.#r(`${this.#t}/tools/execute/${encodeURIComponent(r)}`,{user_id:o,arguments:i},a);if(!u.ok)throw le(u.status,await ke(u));let h=fe(await u.json())??{},g=h.successful!==!1,w=typeof h.error==="string"&&h.error!==""?h.error:void 0;return{ok:g,data:h.data??h,...w===void 0?{}:{error:w}}}#r(r,i,o){return this.#s(r,{method:"POST",headers:{"x-api-key":this.#e,"content-type":"application/json",accept:"application/json"},body:JSON.stringify(i),...o===void 0?{}:{signal:o}})}async createSession(r,i){let o=await this.#r(`${Bt(this.#t)}/tool_router/session`,{user_id:r},i);if(!o.ok)throw le(o.status,await ke(o));let a=fe(await o.json())??{},u=a.session_id;if(typeof u!=="string"||u==="")throw le(o.status,"no session_id in the response body");return a}async executeMeta(r,i,o,a){let u=await this.#r(`${Bt(this.#t)}/tool_router/session/${encodeURIComponent(r)}/execute_meta`,{slug:i,arguments:o},a);if(u.status===404)return{notFound:!0};if(!u.ok)throw le(u.status,await ke(u));let h=fe(await u.json())??{},g=typeof h.error==="string"&&h.error!==""?h.error:void 0;return{ok:h.successful===void 0?g===void 0:h.successful!==!1,data:h.data??h,...g===void 0?{}:{error:g}}}}var Vt=["anyOf","oneOf","allOf","not","$ref"],vs=["format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minLength","maxLength","pattern","minItems","maxItems"],ks=new Set(["string","number","integer","boolean","array","object"]);function Ce(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}function $s(r){let i=[];for(let o of vs){let a=r[o];if(a===void 0||a===null)continue;if(typeof a==="object")continue;i.push(`${o} ${String(a)}`)}return i.join(", ")}function Ss(r){let i=typeof r.description==="string"?r.description.trim():"",o=$s(r);if(i===""&&o==="")return;if(o==="")return i;return i===""?o:`${i} (${o})`}function Yt(r,i,o){for(let S of Vt)if(r[S]!==void 0)throw Xe(i,o,S);let a=r.type;if(Array.isArray(a))throw Xe(i,o,"type: []");let u=typeof a==="string"&&ks.has(a)?a:"string",h=Ss(r),g=Array.isArray(r.enum)?r.enum.filter((S)=>typeof S==="string"||typeof S==="number"||typeof S==="boolean"):void 0,w=u==="array"?Ce(r.items):void 0,k=u==="object"?Ce(r.properties):void 0;return{type:u,...h===void 0?{}:{description:h},...g===void 0||g.length===0?{}:{enum:g},...w===void 0?{}:{items:Yt(w,i,`${o}[]`)},...k===void 0?{}:{properties:zt(k,i,o),required:Xt(r.required)},...r.default===void 0||r.default===null?{}:{default:r.default}}}function Xt(r){return Array.isArray(r)?r.filter((i)=>typeof i==="string"):[]}function zt(r,i,o){let a={};for(let[u,h]of Object.entries(r)){let g=Ce(h);if(g===void 0)continue;a[u]=Yt(g,i,o===""?u:`${o}.${u}`)}return a}function _s(r){let i=r.input_parameters;if(i===void 0)return{type:"object",properties:{}};for(let h of Vt)if(i[h]!==void 0)throw Xe(r.slug,"input_parameters",h);let o=Ce(i.properties)??{},a=Xt(i.required),u=zt(o,r.slug,"");return{type:"object",properties:u,...a.length===0?{}:{required:a.filter((h)=>(h in u))}}}function ze(r){let i=new Set(r.tags??[]);if(i.has("destructiveHint"))return!0;return!i.has("readOnlyHint")}function Zt(r){let i=new Set(r.tags??[]);return!i.has("readOnlyHint")&&!i.has("destructiveHint")}function Es(r){let i=r.replace(/\s+/g," ").trim(),o=i.search(/\.\s|\.$/);return o===-1?i:i.slice(0,o+1)}function Ts(r){let i=(r.description??r.human_description??"").trim(),o=i===""?`The ${r.slug} tool.`:Es(i),a=r.toolkit?.slug;return{slug:r.slug,provider:"composio",summary:o,whenToUse:i===""?`the task needs ${r.slug}`:i,mutating:ze(r),tags:[...a===void 0?[]:[a],...ze(r)?["write"]:["read"]],parameters:_s(r)}}var Rs=8,Ht=100,Ne="composio_search",Le="composio_connect",nt="composio_workbench",As=[Ne,Le,nt];function re(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}function Ze(r){return Array.isArray(r)?r:[]}function ne(r){return typeof r==="string"&&r!==""?r:void 0}function xs(r){let i=r.replace(/\s+/g," ").trim();return i.length<=Ht?i:`${i.slice(0,Ht-1)}…`}var Qt={slug:Ne,provider:"composio",summary:"Finds tools for connecting to an outside app — email, calendar, chat, issue trackers.",whenToUse:"the person wants this agent to reach one of their other accounts and no pinned tool does it. Describe the action and its object in plain English, like 'send an email' or 'create a "+"calendar event' — never a product name alone and never a tool slug. This finds the tools and "+"records their definitions; it does not run them and does not enable them.",whenNotToUse:"a pinned tool already does the job, or the person asked to read a web page — that is "+"web_fetch. This searches an app catalogue, never the web.",mutating:!1,trust:"untrusted",tags:["composio","read"],parameters:{type:"object",properties:{use_case:{type:"string",description:"What the person wants done, as an action and its object: 'send an email', 'list upcoming calendar events', 'create an issue'. Plain English, one task."}},required:["use_case"]}};function Os(r){let i=[];for(let o of Ze(r.results)){let a=re(o);if(a===void 0)continue;for(let u of[a.primary_tool_slugs,a.related_tool_slugs])for(let h of Ze(u))if(typeof h==="string"&&!i.includes(h))i.push(h)}return i.slice(0,Rs)}function Is(r,i){let o=[];for(let a of r){let u=i[a];if(u===void 0)continue;let h=u.description??u.human_description??"";o.push({slug:a,summary:h===""?"no description supplied":xs(h),toolkit:u.toolkit?.slug??"",mutating:ze(u),assumed:Zt(u)})}return o}function Cs(r){let i=[];for(let o of Ze(r.toolkit_connection_statuses)){let a=re(o),u=ne(a?.toolkit);if(u===void 0)continue;i.push({toolkit:u,connected:a?.has_active_connection===!0})}return i}function Ns(r,i,o){let a=[`Tools that can "${r}":`,""];for(let g of i)a.push(` ${g.mutating?"write":"read "} ${g.slug}`),a.push(` ${g.summary}`);if(i.some((g)=>g.assumed))a.push(""),a.push("Some of those are marked write because they say nothing either way, not because they are known to change things. Composio leaves a third of its catalogue unannotated and the safe reading is the one taken here.");let u=o.filter((g)=>!g.connected).map((g)=>g.toolkit),h=o.filter((g)=>g.connected).map((g)=>g.toolkit);if(a.push(""),h.length>0)a.push(`Already connected: ${h.join(", ")}.`);if(u.length>0)a.push(`Not connected yet: ${u.join(", ")}. Call composio_connect for each before these tools can run.`);return a.push(""),a.push("These are not enabled yet. To enable them, add the slugs you need to tools.pinned with "+"config_set — their definitions are already saved, so no other setup is needed — and then "+"tell the person to restart the agent, because the tool list is fixed for a session. Pin only what the task needs."),a.join(`
6
- `)}function Ls(r){return{spec:Qt,handler:async(i,o)=>{let a=String(i.use_case??"").trim(),u=await r.call("COMPOSIO_SEARCH_TOOLS",{queries:[{use_case:a}],session:{generate_id:!0}},o.signal);if(!u.ok)return`The search failed: ${u.error??"no detail supplied"}`;let h=re(u.data)??{},g=Os(h);if(g.length===0)throw Kt(a);let w=await r.fetchSchemas(g,o.signal),k=Is(g,w);if(k.length===0)throw Kt(a);return Ns(a,k,Cs(h))}}}var en={slug:Le,provider:"composio",summary:"Starts linking one of the person's accounts, and returns the link they must open.",whenToUse:"a tool needs an account that is not connected yet. Takes a toolkit name like 'gmail' or "+"'slack'. It returns a web address the person has to open themselves — this agent cannot "+"complete the sign-in, so pass the address on and wait for them to say it is done.",whenNotToUse:"the account already shows as connected, or the person has not asked for that app. This starts a sign-in flow against their real account.",mutating:!0,trust:"untrusted",policyArg:"toolkit",tags:["composio","write"],parameters:{type:"object",properties:{toolkit:{type:"string",description:"The app to connect, lowercase and by itself: gmail, slack, notion, googlecalendar. Not a tool slug and not a sentence."}},required:["toolkit"]}};function tt(r,i=0){if(i>6)return;if(typeof r==="string")return/^https?:\/\/\S+$/.test(r.trim())?r.trim():void 0;for(let o of Array.isArray(r)?r:Object.values(re(r)??{})){let a=tt(o,i+1);if(a!==void 0)return a}return}function js(r,i){let o=re(re(i.results)?.[r]),a=ne(o?.status)?.toLowerCase(),u=ne(o?.redirect_url)??tt(i.results)??tt(i);if(a==="active")return`${r} is already connected — nothing to do. Its tools work as soon as they are pinned.`;if(u===void 0)return`Composio returned no sign-in link for ${r}${a===void 0?"":` (status: ${a})`}. ${ne(i.message)??"No detail was supplied."}`;return[`To connect ${r}, the person needs to open this and sign in:`,"",` ${u}`,"","Give them that address and stop — this agent cannot complete a sign-in on their behalf, and "+"the connection is not usable until they have. When they say it is done, the account stays connected for future sessions with no further sign-in."].join(`
7
- `)}function Ms(r){return{spec:en,handler:async(i,o)=>{let a=String(i.toolkit??"").trim().toLowerCase(),u=await r.call("COMPOSIO_MANAGE_CONNECTIONS",{toolkits:[a]},o.signal);if(!u.ok)return`Could not start the connection for ${a}: ${u.error??"no detail supplied"}`;return js(a,re(u.data)??{})}}}var Ps={slug:nt,provider:"composio",summary:"Runs Python in a Composio-hosted sandbox, for reshaping large tool output.",whenToUse:"a tool returned more data than is worth reading in full and it needs filtering, counting or reshaping first. The sandbox keeps its files and variables for the rest of the task.",whenNotToUse:"the work belongs on this machine — that is exec, which the permission rules can actually "+"constrain. This runs somewhere else, under no rule written here.",mutating:!0,trust:"untrusted",tags:["composio","write"],parameters:{type:"object",properties:{code:{type:"string",description:"Python to run in the sandbox. Print what should come back."}},required:["code"]}},Us="code_to_execute";function Fs(r){let i=re(r);if(i===void 0)return typeof r==="string"?r:JSON.stringify(r,null,2);let o=[],a=ne(i.stdout),u=ne(i.stderr),h=ne(i.error),g=ne(i.results);if(a!==void 0)o.push(a.trimEnd());if(g!==void 0)o.push(g.trimEnd());if(u!==void 0)o.push(`stderr:
2
+ import{e,E,t,k,Ae,Re,U,Dt,H,Er,x,R,Oe,_r,Ne,He,Ar,m}from"./index-tv4yv7d2.js";import{Q,z,y,f,xe,no,Zt,Vt,De,pr}from"./index-1c5113t4.js";import{xn,En}from"./index-d4x6yvqh.js";import{lo,co,Et}from"./index-gme2egyq.js";import{pe,b,J,ue,Z,ie}from"./index-6p999cx4.js";import{ee,K}from"./index-mtn0g9vc.js";import{ge}from"./index-s9mbq7h6.js";import{Jn,dn}from"./index-ttwyrdjs.js";import{l,p,d,c}from"./index-j7gyr5nx.js";import{ve,n,s}from"./index-vgc3y3rm.js";import{cpSync as sc,existsSync as te,mkdirSync as jr,readdirSync as We,readFileSync as ic,rmSync as oc,statSync as Mr,writeFileSync as ac}from"node:fs";import{basename as Lr,isAbsolute as Pr,join as B,relative as cc,resolve as Tt}from"node:path";import{existsSync as Br,readFileSync as Jr,writeFileSync as At}from"node:fs";import{join as Vr}from"node:path";var Yr=".origins.json",xt=1;function Ge(r){return Vr(r,Yr)}function me(r){let i=Ge(r);if(!Br(i))return{};try{return JSON.parse(Jr(i,"utf8")).origins??{}}catch{return{}}}function Ot(r,i){let o={...me(r),...i};At(Ge(r),`${JSON.stringify({version:xt,origins:o},null,4)}
3
+ `)}function Ln(r,i){let o=me(r);if(o[i]===void 0)return;let a=Object.fromEntries(Object.entries(o).filter(([u])=>u!==i));At(Ge(r),`${JSON.stringify({version:xt,origins:a},null,4)}
4
+ `)}class V extends Error{status;retryable;retryAfterMs;detail;constructor(r){super(r.message);this.name="TelegramApiError",this.status=r.status,this.retryable=r.retryable,this.retryAfterMs=r.retryAfterMs,this.detail=r.detail}}var Xr="https://api.telegram.org";class Je{#e;#t;#s;constructor(r){this.#e=r.token,this.#t=r.fetch??((i,o)=>fetch(i,o)),this.#s=(r.baseUrl??Xr).replace(/\/+$/,"")}async call(r,i,o){let a;try{a=await this.#t(`${this.#s}/bot${this.#e}/${r}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i??{}),...o===void 0?{}:{signal:o}})}catch(h){throw new V({message:`Telegram ${r} did not complete: ${h instanceof Error?h.message:String(h)}`,status:0,retryable:!0,detail:{code:"telegram_unreachable",message:`Could not reach the Telegram Bot API for ${r}.`,hint:"Check network access from this host. api.telegram.org is blocked in some networks and from some cloud regions; a webhook deployment behind a proxy still needs outbound access for sendMessage."}})}let u=await a.json().catch(()=>({}));if(a.ok&&u.ok&&u.result!==void 0)return u.result;throw zr(r,a.status,u)}getMe(r){return this.call("getMe",{},r)}getUpdates(r,i){return this.call("getUpdates",{offset:r.offset,timeout:r.timeout,limit:r.limit??100,allowed_updates:["message"]},i)}sendMessage(r,i){return this.call("sendMessage",{chat_id:r.chatId,text:r.text,...r.threadId===void 0?{}:{message_thread_id:r.threadId}},i)}sendChatAction(r){return this.call("sendChatAction",{chat_id:r.chatId,action:"typing",...r.threadId===void 0?{}:{message_thread_id:r.threadId}})}setWebhook(r,i){return this.call("setWebhook",{url:r.url,allowed_updates:["message"],...r.secretToken===void 0?{}:{secret_token:r.secretToken},...r.dropPending===void 0?{}:{drop_pending_updates:r.dropPending}},i)}deleteWebhook(r){return this.call("deleteWebhook",{},r)}}function zr(r,i,o){let a=o.description??`HTTP ${i}`,u=o.error_code??i,h=o.parameters?.retry_after;if(u===429)return new V({message:`Telegram rate-limited ${r}: ${a}`,status:u,retryable:!0,...h===void 0?{}:{retryAfterMs:h*1000},detail:{code:"telegram_rate_limited",message:`Telegram rate-limited ${r}.`,hint:h===void 0?"The outbox will back off and retry. Sustained rate limiting on one chat usually means replies are being split into many chunks — check the reply length.":`Telegram asked for ${h}s. The outbox honours that verbatim rather than applying its own backoff.`}});if(u===401)return new V({message:`Telegram rejected the bot token on ${r}: ${a}`,status:u,retryable:!1,detail:{code:"telegram_unauthorized",message:"The Telegram bot token was rejected.",hint:"Check the variable named by the channel's tokenEnv. A token is revoked whenever /revoke is sent to @BotFather, and a regenerated token invalidates the old one immediately."}});if(u===409)return new V({message:`Telegram reports a conflicting ${r}: ${a}`,status:u,retryable:!0,detail:{code:"telegram_conflict",message:"Another instance of this bot is already receiving updates.",hint:"Telegram allows one getUpdates consumer per bot token. Stop the other process — another terminal, a container that did not exit — or, if a webhook was registered earlier, this channel's own start clears it. Retried, so it recovers on its own once the other side stops."}});if(u===400&&/too long/i.test(a))return new V({message:`Telegram refused ${r}: ${a}`,status:u,retryable:!1,detail:{code:"telegram_message_too_long",message:"A chunk exceeded Telegram's message limit.",hint:"This is a chunking bug, not a configuration problem: the transport declares maxMessageChars and core splits to it. Report the reply length — the splitter reserves room for a code-fence reopen, so the effective limit is slightly under 4096."}});let g=u===400||u===403;return new V({message:`Telegram refused ${r}: ${a}`,status:u,retryable:!g,detail:{code:g?"telegram_refused":"telegram_error",message:`Telegram refused ${r}: ${a}`,hint:g?"Telegram reports this as a client error, so it is not retried. The usual causes are a chat the bot was removed from, a user who blocked it, or a chat id from a different bot — a chat id is not portable between bots.":"Treated as transient and retried with backoff. A 5xx from Telegram is usually brief."}})}var Zr=4096,Qr=30,It=[1000,2000,5000,15000,30000],es=350;class Nt{id;type="telegram";limits={maxMessageChars:Zr,idempotentSend:!1,minSendIntervalMs:es};#e;#t;#s;#i;#o;#r=0;#n=!1;#a;#c;constructor(r){this.id=r.id,this.#e=r.api??new Je({token:r.token}),this.#t=r.mode,this.#s=r.webhookUrl,this.#i=r.secretToken}async start(r){if(this.#n)return;if(this.#n=!0,this.#o=r,this.#a=new AbortController,this.#t==="webhook"){let i=this.#s;if(i===void 0||i===""){r.status("error","no webhookUrl"),r.error({code:"telegram_webhook_url_missing",message:`Channel "${this.id}" is in webhook mode but declares no webhookUrl.`,hint:"Set webhookUrl to the public HTTPS address this runtime is reachable at, ending in /v1/channels/<channelId>/webhook/<agentId>. Telegram will not deliver to plain HTTP, and a missing registration looks identical to a bot nobody is messaging.",field:`channels[${this.id}].webhookUrl`});return}try{await this.#e.setWebhook({url:i,...this.#i===void 0?{}:{secretToken:this.#i}}),r.status("connected",`webhook at ${i}`)}catch(o){r.status("error",o instanceof Error?o.message:String(o)),r.error(qe(o,`registering the webhook for channel "${this.id}"`))}return}this.#c=this.#d(r,this.#a.signal)}async stop(){if(!this.#n)return;this.#n=!1,this.#a?.abort(),await this.#c?.catch(()=>{}),this.#c=void 0,this.#o?.status("disconnected"),this.#o=void 0}async send(r,i){let o=Ct(r.thread);try{let a=await this.#e.sendMessage({chatId:r.recipient,text:r.text,...o===void 0?{}:{threadId:o}},i);return{ok:!0,providerMessageId:String(a.message_id)}}catch(a){if(a instanceof V)return{ok:!1,retryable:a.retryable,error:a.detail,...a.retryAfterMs===void 0?{}:{retryAfterMs:a.retryAfterMs}};return{ok:!1,retryable:!0,error:{code:"telegram_send_failed",message:a instanceof Error?a.message:String(a),hint:"An unclassified failure from the Telegram transport. Retried, because a failure nobody recognised is not a failure known to be permanent."}}}}async typing(r,i){let o=Ct(i);await this.#e.sendChatAction({chatId:r,...o===void 0?{}:{threadId:o}})}async webhook(r){if(this.#i!==void 0){let a=r.headers["x-telegram-bot-api-secret-token"]??"";if(!ns(a,this.#i))return{status:401,detail:"bad secret token"}}let i=this.#o;if(i===void 0)return{status:503,detail:"channel not started"};let o=r.body;if(o===void 0||typeof o!=="object")return{status:400,detail:"not an update"};return this.#l(i,o),{status:200}}async#d(r,i){let o=0,a=!1;try{await this.#e.deleteWebhook(i)}catch{}try{let u=await this.#e.getMe(i);a=!0,r.status("connected",u.username===void 0?"long-poll":`@${u.username}, long-poll`)}catch(u){if(i.aborted)return;r.status("error",u instanceof Error?u.message:String(u)),r.error(qe(u,`checking the bot token for channel "${this.id}"`))}while(this.#n&&!i.aborted)try{let u=await this.#e.getUpdates({offset:this.#r,timeout:Qr},i);if(o>0)o=0,a=!0,r.status("connected","polling resumed");else if(!a)a=!0,r.status("connected","long-poll");for(let h of u)this.#r=Math.max(this.#r,h.update_id+1),this.#l(r,h)}catch(u){if(i.aborted)return;let h=It[Math.min(o,It.length-1)]??1000;if(o+=1,o===1||o%8===0)r.status("error",u instanceof Error?u.message:String(u)),r.error(qe(u,`polling channel "${this.id}"`));await rs(h,i)}}#l(r,i){let o=i.message;if(o===void 0)return;let a=o.text??o.caption??"";if(a.trim()==="")return;if(o.from?.is_bot===!0)return;r.receive(ts(o,a))}}function ts(r,i){let o=r.from?.username,a=[r.from?.first_name,r.from?.last_name].filter(Boolean).join(" ");return{providerMessageId:`${r.chat.id}:${r.message_id}`,peerId:String(r.chat.id),...o===void 0?{}:{senderHandle:`@${o}`},...a===""?{}:{senderName:a},...r.message_thread_id===void 0?{}:{thread:String(r.message_thread_id)},text:i,receivedAt:new Date(r.date*1000).toISOString()}}function Ct(r){if(r===void 0)return;let i=Number.parseInt(r,10);return Number.isFinite(i)?i:void 0}function qe(r,i){if(r instanceof V)return r.detail;return{code:"telegram_channel_error",message:`${i} failed: ${r instanceof Error?r.message:String(r)}`,hint:"The channel keeps retrying and the rest of the runtime is unaffected. If this repeats, check network access to api.telegram.org and the token named by tokenEnv."}}function ns(r,i){if(r.length!==i.length)return!1;let o=0;for(let a=0;a<r.length;a+=1)o|=r.charCodeAt(a)^i.charCodeAt(a);return o===0}function rs(r,i){return new Promise((o)=>{let a=setTimeout(o,r);i.addEventListener("abort",()=>{clearTimeout(a),o()},{once:!0})})}var Ve=(r)=>{let i=r.config,o=ye(i,"tokenEnv")??"TELEGRAM_BOT_TOKEN",a=r.env[o];if(a===void 0||a==="")throw new y({code:"telegram_token_missing",message:`Channel "${r.id}" needs ${o}, which is not set.`,hint:`Export ${o}, or add it to the .env beside the manifest. Get a token from @BotFather with /newbot. This fails at load rather than at the first poll, because an unset variable is a configuration mistake and does not need a network round trip to discover.`,field:`channels[${r.id}].tokenEnv`});let u=ye(i,"mode")??"longpoll";if(u!=="longpoll"&&u!=="webhook")throw new y({code:"telegram_mode_invalid",message:`Channel "${r.id}" declares mode "${u}".`,hint:"mode is longpoll or webhook. Long-poll needs no inbound connectivity and is the right default for a laptop or a private network; webhook needs a public HTTPS URL and is lower latency.",field:`channels[${r.id}].mode`});let h=ye(i,"secretTokenEnv"),g=h===void 0?void 0:r.env[h];if(h!==void 0&&(g===void 0||g===""))throw new y({code:"telegram_secret_missing",message:`Channel "${r.id}" names secretTokenEnv ${h}, which is not set.`,hint:`Export ${h} with any random string, or remove secretTokenEnv. Naming a variable and leaving it empty would start a webhook that verifies nothing, which is worse than one that never claimed to.`,field:`channels[${r.id}].secretTokenEnv`});let w=ye(i,"apiBaseUrl"),v=ye(i,"webhookUrl");return new Nt({id:r.id,token:a,mode:u,...v===void 0?{}:{webhookUrl:v},...g===void 0||g===""?{}:{secretToken:g},...w===void 0?{}:{api:new Je({token:a,baseUrl:w})}})};function ye(r,i){let o=r[i];return typeof o==="string"&&o!==""?o:void 0}var ss="0.1.0",Lt={name:"telegram",version:ss,dispachApi:"^0.1",permissions:[{kind:"network",hosts:["api.telegram.org"]},{kind:"env",vars:["TELEGRAM_BOT_TOKEN"]}],setup(r){r.defineChannel("telegram",Ve)}};import{mkdirSync as is,readFileSync as os,renameSync as as,writeFileSync as cs}from"node:fs";import{dirname as ds,isAbsolute as ls,join as jt,resolve as us}from"node:path";import{mkdirSync as Ks,readFileSync as sn,renameSync as Bs,writeFileSync as Hs}from"node:fs";import{dirname as Ws,isAbsolute as Gs,join as Gt,resolve as qs}from"node:path";var Ee=1,Mt="tools.cache.json";function Te(r){return ls(r)?jt(r,Q.stateDir,Mt):jt(us(r),Q.stateDir,Mt)}function hs(r){return typeof r==="object"&&r!==null&&typeof r.slug==="string"}function Pt(r){let i={version:Ee,provider:"composio",fetchedAt:"",baseUrl:"",tools:{}},o;try{o=os(Te(r),"utf8")}catch{return i}try{let a=JSON.parse(o);if(typeof a!=="object"||a===null)return i;let u=a;if(u.version!==Ee)return i;let h={};for(let[g,w]of Object.entries(u.tools??{}))if(hs(w))h[g]=w;return{version:Ee,provider:"composio",fetchedAt:typeof u.fetchedAt==="string"?u.fetchedAt:"",baseUrl:typeof u.baseUrl==="string"?u.baseUrl:"",tools:h}}catch{return i}}function fs(r,i,o,a){let u=Te(r);is(ds(u),{recursive:!0});let h={version:Ee,provider:"composio",fetchedAt:a().toISOString(),baseUrl:o,tools:i},g=`${u}.${process.pid}.tmp`;return cs(g,`${JSON.stringify(h,null,2)}
5
+ `,"utf8"),as(g,u),u}function Ut(r){return new y({code:"composio_key_missing",message:`The Composio provider needs an API key, and ${r} is not set.`,hint:`Set ${r} in the environment, or in a .env beside the manifest. Change which variable is read with tools.providers.composio.apiKeyEnv — the manifest holds the variable's name, never the key itself.`,field:"tools.providers.composio.apiKeyEnv"})}function Xe(r,i,o){return new y({code:"composio_schema_unsupported",message:`The Composio tool "${r}" declares "${o}" at ${i}, which this runtime's schema subset cannot express.`,hint:"Refused rather than dropped: that keyword decides which argument documents are valid, so ignoring it would hand the model a schema the endpoint disagrees with. Unpin this tool, or pin a sibling action with a flatter schema. Value constraints such as minimum and format are not affected — those are carried in the field's description.",field:"tools.pinned"})}function ms(r,i){return new y({code:"composio_cache_miss",message:`${r.length===1?"A pinned Composio tool is":`${r.length} pinned Composio tools are`} not in the resolution cache: ${r.join(", ")}.`,hint:`Boot resolves tools from ${i} and makes no network call, because nothing may touch the network before runtime.ready. Run \`${Q.slug} tools <manifest> --warm\` once to populate it, then start again.`,field:"tools.pinned"})}function le(r,i){return new f({code:"composio_request_failed",message:`Composio answered ${r}: ${i}`,hint:r===401||r===403?"The API key was rejected. Check the value of the variable named by tools.providers.composio.apiKeyEnv — a key that works in the dashboard can still be scoped to a different project.":r===404?"The tool slug does not exist at this API version. Slugs are case-sensitive and shaped like GMAIL_SEND_EMAIL; check it against the toolkit listing.":"Transient at this status. The runtime retries the refresh after readiness and keeps serving the cached catalogue meanwhile, so an agent already running is unaffected."})}function ps(r,i,o){return new f({code:"composio_execute_failed",message:`Composio could not run "${r}" (${i}): ${o}`,hint:"This is the tool's own failure, not a routing one — the arguments reached Composio and it refused them. A value constraint is the usual cause: this runtime carries minimum, format and pattern in the field description for the model to read, but does not enforce them locally, so an out-of-range value arrives here rather than as a repairable field error."})}function gs(r,i){return new f({code:"composio_not_connected",message:`"${r}" needs a connected ${i} account and none was found.`,hint:`Connect ${i} for this user in Composio, then set tools.providers.composio.userId to the same identifier. The tool resolves at load whether or not an account exists, because resolution reads a schema and execution needs the account — so this surfaces on first use rather than at boot.`})}function Ft(r){return new f({code:"composio_session_key_missing",message:`Searching your apps needs a Composio key, and ${r} is not set.`,hint:`Put the key in the .env beside this agent's manifest as ${r}=…, then restart. Get one from the Composio dashboard — the free tier is enough to connect an account and search the catalogue.`})}function Kt(r){return new f({code:"composio_no_match",message:`No tool matched "${r}".`,hint:'Describe the action and its object in plain English — "send an email", "create a calendar event", "post a message to a channel" — rather than naming a product or a tool slug. Composio matches on the use case, not on its own names.'})}var ys="https://backend.composio.dev/api/v3";function Bt(r){return/\/v3$/.test(r)?r.replace(/\/v3$/,"/v3.1"):r}var ws=100;function he(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}async function we(r){let i;try{i=await r.json()}catch{return r.statusText===""?"no detail in the response body":r.statusText}let o=he(he(i)?.error),a=typeof o?.message==="string"?o.message:void 0,u=typeof o?.suggested_fix==="string"?o.suggested_fix:void 0;if(a===void 0)return r.statusText===""?"no detail":r.statusText;return u===void 0||u===""?a:`${a} — ${u}`}class Yt{#e;#t;#s;constructor(r){this.#e=r.apiKey,this.#t=(r.baseUrl??ys).replace(/\/+$/,""),this.#s=r.fetch??((i,o)=>globalThis.fetch(i,o))}#i(r,i){return this.#s(`${this.#t}${r}`,{method:"GET",headers:{"x-api-key":this.#e,accept:"application/json"},...i===void 0?{}:{signal:i}})}async#o(r,i){let o=await this.#i(r,i);if(!o.ok)throw le(o.status,await we(o));return o.json()}async tool(r,i){let o=await this.#i(`/tools/${encodeURIComponent(r)}`,i);if(o.status===404)return;if(!o.ok)throw le(o.status,await we(o));let a=he(await o.json());return typeof a?.slug==="string"?a:void 0}async slugs(r){let i=[],o;for(let a=0;a<400;a+=1){let u=new URLSearchParams({limit:String(ws)});if(o!==void 0)u.set("cursor",o);let h=await this.#o(`/tools?${u.toString()}`,r);for(let w of h.items??[])if(typeof w.slug==="string")i.push(w.slug);let g=h.next_cursor;if(g===null||g===void 0||g===""||g===o)break;o=g}return i}async execute(r,i,o,a){let u=await this.#r(`${this.#t}/tools/execute/${encodeURIComponent(r)}`,{user_id:o,arguments:i},a);if(!u.ok)throw le(u.status,await we(u));let h=he(await u.json())??{},g=h.successful!==!1,w=typeof h.error==="string"&&h.error!==""?h.error:void 0;return{ok:g,data:h.data??h,...w===void 0?{}:{error:w}}}#r(r,i,o){return this.#s(r,{method:"POST",headers:{"x-api-key":this.#e,"content-type":"application/json",accept:"application/json"},body:JSON.stringify(i),...o===void 0?{}:{signal:o}})}async createSession(r,i){let o=await this.#r(`${Bt(this.#t)}/tool_router/session`,{user_id:r},i);if(!o.ok)throw le(o.status,await we(o));let a=he(await o.json())??{},u=a.session_id;if(typeof u!=="string"||u==="")throw le(o.status,"no session_id in the response body");return a}async executeMeta(r,i,o,a){let u=await this.#r(`${Bt(this.#t)}/tool_router/session/${encodeURIComponent(r)}/execute_meta`,{slug:i,arguments:o},a);if(u.status===404)return{notFound:!0};if(!u.ok)throw le(u.status,await we(u));let h=he(await u.json())??{},g=typeof h.error==="string"&&h.error!==""?h.error:void 0;return{ok:h.successful===void 0?g===void 0:h.successful!==!1,data:h.data??h,...g===void 0?{}:{error:g}}}}var Xt=["anyOf","oneOf","allOf","not","$ref"],bs=["format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minLength","maxLength","pattern","minItems","maxItems"],vs=new Set(["string","number","integer","boolean","array","object"]);function Ie(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}function ks(r){let i=[];for(let o of bs){let a=r[o];if(a===void 0||a===null)continue;if(typeof a==="object")continue;i.push(`${o} ${String(a)}`)}return i.join(", ")}function $s(r){let i=typeof r.description==="string"?r.description.trim():"",o=ks(r);if(i===""&&o==="")return;if(o==="")return i;return i===""?o:`${i} (${o})`}function zt(r,i,o){for(let S of Xt)if(r[S]!==void 0)throw Xe(i,o,S);let a=r.type;if(Array.isArray(a))throw Xe(i,o,"type: []");let u=typeof a==="string"&&vs.has(a)?a:"string",h=$s(r),g=Array.isArray(r.enum)?r.enum.filter((S)=>typeof S==="string"||typeof S==="number"||typeof S==="boolean"):void 0,w=u==="array"?Ie(r.items):void 0,v=u==="object"?Ie(r.properties):void 0;return{type:u,...h===void 0?{}:{description:h},...g===void 0||g.length===0?{}:{enum:g},...w===void 0?{}:{items:zt(w,i,`${o}[]`)},...v===void 0?{}:{properties:en(v,i,o),required:Qt(r.required)},...r.default===void 0||r.default===null?{}:{default:r.default}}}function Qt(r){return Array.isArray(r)?r.filter((i)=>typeof i==="string"):[]}function en(r,i,o){let a={};for(let[u,h]of Object.entries(r)){let g=Ie(h);if(g===void 0)continue;a[u]=zt(g,i,o===""?u:`${o}.${u}`)}return a}function Ss(r){let i=r.input_parameters;if(i===void 0)return{type:"object",properties:{}};for(let h of Xt)if(i[h]!==void 0)throw Xe(r.slug,"input_parameters",h);let o=Ie(i.properties)??{},a=Qt(i.required),u=en(o,r.slug,"");return{type:"object",properties:u,...a.length===0?{}:{required:a.filter((h)=>(h in u))}}}function ze(r){let i=new Set(r.tags??[]);if(i.has("destructiveHint"))return!0;return!i.has("readOnlyHint")}function tn(r){let i=new Set(r.tags??[]);return!i.has("readOnlyHint")&&!i.has("destructiveHint")}function _s(r){let i=r.replace(/\s+/g," ").trim(),o=i.search(/\.\s|\.$/);return o===-1?i:i.slice(0,o+1)}function Es(r){let i=(r.description??r.human_description??"").trim(),o=i===""?`The ${r.slug} tool.`:_s(i),a=r.toolkit?.slug;return{slug:r.slug,provider:"composio",summary:o,whenToUse:i===""?`the task needs ${r.slug}`:i,mutating:ze(r),tags:[...a===void 0?[]:[a],...ze(r)?["write"]:["read"]],parameters:Ss(r)}}var Ts=8,Wt=100,Ce="composio_search",Le="composio_connect",rt="composio_workbench",Rs=[Ce,Le,rt];function re(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}function Ze(r){return Array.isArray(r)?r:[]}function ne(r){return typeof r==="string"&&r!==""?r:void 0}function As(r){let i=r.replace(/\s+/g," ").trim();return i.length<=Wt?i:`${i.slice(0,Wt-1)}…`}var nn={slug:Ce,provider:"composio",summary:"Finds tools for connecting to an outside app — email, calendar, chat, issue trackers.",whenToUse:"the person wants this agent to reach one of their other accounts and no pinned tool does it. Describe the action and its object in plain English, like 'send an email' or 'create a "+"calendar event' — never a product name alone and never a tool slug. This finds the tools and "+"records their definitions; it does not run them and does not enable them.",whenNotToUse:"a pinned tool already does the job, or the person asked to read a web page — that is "+"web_fetch. This searches an app catalogue, never the web.",mutating:!1,trust:"untrusted",tags:["composio","read"],parameters:{type:"object",properties:{use_case:{type:"string",description:"What the person wants done, as an action and its object: 'send an email', 'list upcoming calendar events', 'create an issue'. Plain English, one task."}},required:["use_case"]}};function xs(r){let i=[];for(let o of Ze(r.results)){let a=re(o);if(a===void 0)continue;for(let u of[a.primary_tool_slugs,a.related_tool_slugs])for(let h of Ze(u))if(typeof h==="string"&&!i.includes(h))i.push(h)}return i.slice(0,Ts)}function Os(r,i){let o=[];for(let a of r){let u=i[a];if(u===void 0)continue;let h=u.description??u.human_description??"";o.push({slug:a,summary:h===""?"no description supplied":As(h),toolkit:u.toolkit?.slug??"",mutating:ze(u),assumed:tn(u)})}return o}function Is(r){let i=[];for(let o of Ze(r.toolkit_connection_statuses)){let a=re(o),u=ne(a?.toolkit);if(u===void 0)continue;i.push({toolkit:u,connected:a?.has_active_connection===!0})}return i}function Cs(r,i,o){let a=[`Tools that can "${r}":`,""];for(let g of i)a.push(` ${g.mutating?"write":"read "} ${g.slug}`),a.push(` ${g.summary}`);if(i.some((g)=>g.assumed))a.push(""),a.push("Some of those are marked write because they say nothing either way, not because they are known to change things. Composio leaves a third of its catalogue unannotated and the safe reading is the one taken here.");let u=o.filter((g)=>!g.connected).map((g)=>g.toolkit),h=o.filter((g)=>g.connected).map((g)=>g.toolkit);if(a.push(""),h.length>0)a.push(`Already connected: ${h.join(", ")}.`);if(u.length>0)a.push(`Not connected yet: ${u.join(", ")}. Call composio_connect for each before these tools can run.`);return a.push(""),a.push("These are not enabled yet. To enable them, add the slugs you need to tools.pinned with "+"config_set — their definitions are already saved, so no other setup is needed — and then "+"tell the person to restart the agent, because the tool list is fixed for a session. Pin only what the task needs."),a.join(`
6
+ `)}function Ns(r){return{spec:nn,handler:async(i,o)=>{let a=String(i.use_case??"").trim(),u=await r.call("COMPOSIO_SEARCH_TOOLS",{queries:[{use_case:a}],session:{generate_id:!0}},o.signal);if(!u.ok)return`The search failed: ${u.error??"no detail supplied"}`;let h=re(u.data)??{},g=xs(h);if(g.length===0)throw Kt(a);let w=await r.fetchSchemas(g,o.signal),v=Os(g,w);if(v.length===0)throw Kt(a);return Cs(a,v,Is(h))}}}var rn={slug:Le,provider:"composio",summary:"Starts linking one of the person's accounts, and returns the link they must open.",whenToUse:"a tool needs an account that is not connected yet. Takes a toolkit name like 'gmail' or "+"'slack'. It returns a web address the person has to open themselves — this agent cannot "+"complete the sign-in, so pass the address on and wait for them to say it is done.",whenNotToUse:"the account already shows as connected, or the person has not asked for that app. This starts a sign-in flow against their real account.",mutating:!0,trust:"untrusted",policyArg:"toolkit",tags:["composio","write"],parameters:{type:"object",properties:{toolkit:{type:"string",description:"The app to connect, lowercase and by itself: gmail, slack, notion, googlecalendar. Not a tool slug and not a sentence."}},required:["toolkit"]}};function Qe(r,i=0){if(i>6)return;if(typeof r==="string")return/^https?:\/\/\S+$/.test(r.trim())?r.trim():void 0;for(let o of Array.isArray(r)?r:Object.values(re(r)??{})){let a=Qe(o,i+1);if(a!==void 0)return a}return}function Ls(r,i){let o=re(re(i.results)?.[r]),a=ne(o?.status)?.toLowerCase(),u=ne(o?.redirect_url)??Qe(i.results)??Qe(i);if(a==="active")return`${r} is already connected — nothing to do. Its tools work as soon as they are pinned.`;if(u===void 0)return`Composio returned no sign-in link for ${r}${a===void 0?"":` (status: ${a})`}. ${ne(i.message)??"No detail was supplied."}`;return[`To connect ${r}, the person needs to open this and sign in:`,"",` ${u}`,"","Give them that address and stop — this agent cannot complete a sign-in on their behalf, and "+"the connection is not usable until they have. When they say it is done, the account stays connected for future sessions with no further sign-in."].join(`
7
+ `)}function js(r){return{spec:rn,handler:async(i,o)=>{let a=String(i.toolkit??"").trim().toLowerCase(),u=await r.call("COMPOSIO_MANAGE_CONNECTIONS",{toolkits:[a]},o.signal);if(!u.ok)return`Could not start the connection for ${a}: ${u.error??"no detail supplied"}`;return Ls(a,re(u.data)??{})}}}var Ms={slug:rt,provider:"composio",summary:"Runs Python in a Composio-hosted sandbox, for reshaping large tool output.",whenToUse:"a tool returned more data than is worth reading in full and it needs filtering, counting or reshaping first. The sandbox keeps its files and variables for the rest of the task.",whenNotToUse:"the work belongs on this machine — that is exec, which the permission rules can actually "+"constrain. This runs somewhere else, under no rule written here.",mutating:!0,trust:"untrusted",tags:["composio","write"],parameters:{type:"object",properties:{code:{type:"string",description:"Python to run in the sandbox. Print what should come back."}},required:["code"]}},Ps="code_to_execute";function Us(r){let i=re(r);if(i===void 0)return typeof r==="string"?r:JSON.stringify(r,null,2);let o=[],a=ne(i.stdout),u=ne(i.stderr),h=ne(i.error),g=ne(i.results);if(a!==void 0)o.push(a.trimEnd());if(g!==void 0)o.push(g.trimEnd());if(u!==void 0)o.push(`stderr:
8
8
  ${u.trimEnd()}`);if(h!==void 0)o.push(`error:
9
9
  ${h.trimEnd()}`);return o.length===0?"The code ran and printed nothing.":o.join(`
10
- `)}function Ds(r){return{spec:Ps,handler:async(i,o)=>{let a=await r.call("COMPOSIO_REMOTE_WORKBENCH",{[Us]:String(i.code??"")},o.signal);if(!a.ok)return`The workbench failed: ${a.error??"no detail supplied"}`;return Fs(a.data)}}}function Ks(r){return{[Ne]:Ls(r),[Le]:Ms(r),[nt]:Ds(r)}}var Gt="composio.session.json";function rn(r){return qs(r)?Wt(r,Q.stateDir,Gt):Wt(Js(r),Q.stateDir,Gt)}function Vs(r,i){let o;try{o=nn(rn(r),"utf8")}catch{return}try{let u=JSON.parse(o)?.sessions;if(typeof u!=="object"||u===null)return;let h=u[i];return typeof h==="string"&&h!==""?h:void 0}catch{return}}function Ys(r,i,o){let a=rn(r);Bs(Gs(a),{recursive:!0});let u={};try{let k=JSON.parse(nn(a,"utf8"))?.sessions;if(typeof k==="object"&&k!==null){for(let[S,T]of Object.entries(k))if(typeof T==="string")u[S]=T}}catch{u={}}let h={sessions:{...u,[i]:o}},g=`${a}.${process.pid}.tmp`;return Ws(g,`${JSON.stringify(h,null,2)}
11
- `,"utf8"),Hs(g,a),a}var Xs="COMPOSIO_API_KEY";class sn{id="composio";#e;#t;#s;#i;#o;#r;#n;#a;#c=[];#d;constructor(r){this.#e=r.dir,this.#t=r.userId??"default",this.#s=r.now??(()=>new Date),this.#r=r.apiKeyEnv??Xs;let i=r.env[this.#r];this.#i=r.baseUrl??"https://backend.composio.dev/api/v3",this.#o=i===void 0||i===""?void 0:new Jt({apiKey:i,baseUrl:this.#i,...r.fetch===void 0?{}:{fetch:r.fetch}});let o=Ut(this.#e);this.#n=o.tools,this.#a=o.fetchedAt}async resolve(r){let i=[],o=[],a=Ks(this.#u());for(let u of r){let h=a[u];if(h!==void 0){i.push(h);continue}let g=this.#n[u];if(g===void 0)continue;if(Zt(g))o.push(u);i.push(this.#h(Ts(g)))}return this.#c=o,i}async list(){return[...As,...Object.keys(this.#n)]}async available(){return[{slug:Ne,summary:Qt.summary},{slug:Le,summary:en.summary}]}uncached(r){return r.filter((i)=>this.#n[i]===void 0)}explainUnresolved(r){if(Object.keys(this.#n).length>0||r.length===0)return;return ps(r,Oe(this.#e))}describe(){return{cached:Object.keys(this.#n).length,fetchedAt:this.#a,cachePath:Oe(this.#e),assumedMutating:this.#c}}async refresh(r,i){let o=this.#o;if(o===void 0)throw Ft(this.#r);let a={},u=[],h=[];for(let w of r){let k=await o.tool(w,i);if(k===void 0){u.push(w);continue}a[w]=k;let S=this.#n[w];if(S===void 0||JSON.stringify(S)!==JSON.stringify(k))h.push(w)}this.#n={...this.#n,...a};let g=ms(this.#e,this.#n,this.#i,this.#s);return this.#a=Ut(this.#e).fetchedAt,{fetched:Object.keys(a).length,missing:u,changed:h,cachePath:g}}async#l(r,i=!1){let o=this.#o;if(o===void 0)throw Dt(this.#r);if(!i){let u=this.#d??Vs(this.#e,this.#t);if(u!==void 0)return this.#d=u,u}let a=await o.createSession(this.#t,r);return this.#d=a.session_id,Ys(this.#e,this.#t,a.session_id),a.session_id}#u(){return{call:async(r,i,o)=>{let a=this.#o;if(a===void 0)throw Dt(this.#r);let u=await this.#l(o),h=await a.executeMeta(u,r,i,o);if("notFound"in h){u=await this.#l(o,!0);let g=await a.executeMeta(u,r,i,o);if("notFound"in g)return{ok:!1,data:{},error:"the session could not be opened"};h=g}return h},fetchSchemas:async(r,i)=>{await this.refresh(r,i);let o={};for(let a of r){let u=this.#n[a];if(u!==void 0)o[a]=u}return o}}}#h(r){return{spec:r,handler:async(i,o)=>{let a=this.#o;if(a===void 0)throw Ft(this.#r);let u=await a.execute(r.slug,i,this.#t,o.signal);if(!u.ok){let h=u.error??"no detail supplied";if(/connected account|not connected|no connection/i.test(h)){let g=r.tags[0]??"the toolkit";throw ys(r.slug,g)}throw gs(r.slug,200,h)}return typeof u.data==="string"?u.data:JSON.stringify(u.data,null,2)}}}}var qt=["apiKeyEnv","userId","baseUrl"];function Ye(r,i){let o=r[i];if(o===void 0)return;if(typeof o!=="string"||o==="")throw new y({code:"composio_config_invalid",message:`tools.providers.composio.${i} must be a non-empty string.`,hint:`Got ${o===null?"null":typeof o}. ${i==="apiKeyEnv"?"This is the *name* of an environment variable, never the key itself — a manifest holding a literal key fails validation.":"Remove the key to use the default."}`,field:`tools.providers.composio.${i}`});return o}function rt(r){let i=Object.keys(r.config).filter((h)=>!qt.includes(h));if(i.length>0)throw new y({code:"composio_config_unknown",message:`tools.providers.composio has ${i.length===1?"a key":"keys"} the Composio provider does not read: ${i.join(", ")}.`,hint:`Accepted keys are ${qt.join(", ")}. Refused rather than ignored, because a setting that looks applied and is not is worse than a rejected manifest.`,field:"tools.providers.composio"});let o=Ye(r.config,"apiKeyEnv"),a=Ye(r.config,"userId"),u=Ye(r.config,"baseUrl");return new sn({dir:r.dir,env:r.env,...o===void 0?{}:{apiKeyEnv:o},...a===void 0?{}:{userId:a},...u===void 0?{}:{baseUrl:u}})}var zs="0.1.0",on={name:"composio",version:zs,dispachApi:"^0.1",permissions:[{kind:"network",hosts:["backend.composio.dev"]},{kind:"env",vars:["COMPOSIO_API_KEY"]},{kind:"fs",paths:["<state>/composio"],mode:"write"}],setup(r){r.defineToolProvider("composio",rt)}};import{readFile as Zs}from"node:fs/promises";import{join as Qs}from"node:path";import{tmpdir as pi}from"node:os";import{join as gi}from"node:path";import{mkdir as Ei,realpath as Ti,rm as ln,stat as Ri}from"node:fs/promises";import{isAbsolute as Ai,resolve as at}from"node:path";import{open as xn}from"node:fs/promises";import{existsSync as Li}from"node:fs";import{homedir as hn}from"node:os";import{isAbsolute as Nn,relative as ji,resolve as Ee,sep as Mi}from"node:path";import{spawn as Hi}from"node:child_process";import{open as Wi,readFile as Gi}from"node:fs/promises";import{mkdir as po,readFile as Fn,stat as Dn,writeFile as Kn}from"node:fs/promises";import{dirname as go,isAbsolute as yo,resolve as pn}from"node:path";import{isAbsolute as wo,relative as bo,resolve as vo,sep as Bn}from"node:path";import{readFile as Lo}from"node:fs/promises";import{readdir as jo}from"node:fs/promises";import{join as Mo,relative as Po,sep as vn}from"node:path";import{statSync as qo}from"node:fs";import{mkdir as Jo,rm as En}from"node:fs/promises";import{delimiter as Vo,join as ot}from"node:path";function ei(){return new f({code:"exec_command_empty",message:"exec was called with no command.",hint:"Put the whole shell command in the command field, exactly as it would be typed at a prompt — for example `ls -la` or `npm test`."})}function ti(r,i){return new y({code:"exec_workdir_missing",message:`The directory to run in does not exist: ${r}`,hint:i?"This is where a previous exec call left the shell, and it has since been removed or renamed. The remembered directory has been cleared, so the next call starts from the agent's own directory; pass workdir to choose a different one.":"workdir must name a directory that already exists. A relative path is resolved against the directory the last exec call ended in, the way a shell would.",field:"workdir"})}function ni(r,i){return new f({code:"exec_pty_unavailable",message:`A terminal was requested and this machine cannot provide one: ${i}`,hint:`pty: true allocates a terminal with the system \`script\` command, which is missing or unusable on this ${r} host. Refused rather than quietly falling back to a pipe: the fallback would run the command with no terminal while the observation claimed otherwise, and a program that checks isatty() would take the other branch with nothing reporting it. Re-run with pty omitted if the command does not need one.`,field:"pty"})}function an(r,i){return new f({code:"exec_spawn_failed",message:`The shell could not be started for: ${r}`,hint:`The operating system refused before the command ran, so nothing was executed: ${i}. This is a failure of the host rather than of the command — check that /bin/sh exists and that the directory is readable.`})}function ri(){return new f({code:"file_path_empty",message:"A file tool was called with no path.",hint:"Give the path field a value — either absolute, or relative to the current working directory, which is wherever the last exec call left it."})}function Tn(r){return new f({code:"file_missing",message:`There is no file at ${r}.`,hint:"Check the path against what glob returns rather than guessing at it. A relative path is resolved against the current working directory, which starts at the agent's own directory and moves when a shell command changes it.",field:"path"})}function si(r,i,o){return new f({code:"file_too_large",message:`${r} is ${i} bytes, over the ${o}-byte limit for reading.`,hint:"Use grep to find the part that matters and read around it with offset and limit, rather than pulling the whole file into the conversation.",field:"path"})}function ii(r,i){return new f({code:"file_is_binary",message:`${r} is not a text file (${i} bytes).`,hint:"Refused rather than decoded: a binary rendered as text is thousands of meaningless tokens and no information. If something about the file is needed — its type, its size, what it contains — a shell command that inspects it will answer better.",field:"path"})}function oi(r,i){return new f({code:"file_protected",message:`${r} cannot be written: ${i}.`,hint:"This is a standing rule and no permission setting overrides it — a rule that authorised writing to the agent's own definition would be a rule authorising its own replacement. Say what change was wanted and let the person make it themselves.",field:"path"})}function ai(r,i){let o=i.length>120?`${i.slice(0,120)}…`:i;return new f({code:"file_edit_no_match",message:`That text does not appear in ${r}: ${JSON.stringify(o)}`,hint:"The match is exact, including indentation and line breaks. Read the file and copy the text out of it rather than reconstructing it from memory — nothing was changed, so the file is still as it was.",field:"find"})}function ci(r,i){return new f({code:"file_edit_ambiguous",message:`That text appears ${i} times in ${r}, so it does not identify one place.`,hint:"Nothing was changed: picking one of several matches would be a guess, and a wrong guess reports success while editing the wrong line. Include a surrounding line or two to make it unique, or pass all: true if every occurrence should change.",field:"find"})}function di(r,i){return new f({code:"grep_pattern_invalid",message:`That is not a valid regular expression: ${r}`,hint:`${i}. Refused rather than searched literally — a literalised pattern finds nothing and returns an empty result, which reads as "it is not there" instead of "the pattern was wrong". Escape any regex character meant literally, such as a dot or a bracket.`,field:"pattern"})}function li(r,i){return new f({code:"file_outside_root",message:`${r} is outside the directories this agent may change.`,hint:`Writable: ${i.join(", ")}. Everything else is read-only by default — an agent that has misunderstood a request cannot damage anything while misunderstanding it. To work somewhere else, the person you work for adds it to tools.providerConfig.writeRoots in agent.yaml; nothing said in a conversation can add one. Reading outside these directories is allowed and unaffected.`,field:"path"})}function Rn(r,i){return new f({code:"config_read_failed",message:`This agent's configuration could not be read from ${r}.`,hint:`${i}. The agent is running, so the file existed at boot — it has been moved or its permissions have changed since.`})}function ui(r,i){return new f({code:"config_path_unknown",message:`"${r}" is not a setting config_set will change.`,hint:`Settable: ${i.join(", ")}. Deliberately a list rather than anything the schema accepts: a tool that can write any field can write the ones that decide what it is allowed to do, and the list is where that judgement lives. Call config_read with no path to see each one explained.`,field:"path"})}function hi(r,i){return new f({code:"config_value_unreadable",message:`That value could not be read: ${JSON.stringify(r)}`,hint:`${i}. Write it the way it would appear in the file — a bare word, a number, or a list as ["a", "b"]. Refused rather than guessed at, because guessing is how tools.pinned becomes a list of single characters.`,field:"value"})}function fi(r,i,o){return new f({code:"config_invalid",message:`Setting ${r} to ${JSON.stringify(i)} would produce a configuration that does not load: ${o}`,hint:"Nothing was written, so the agent is unchanged and still starts. An invalid manifest is not a failure that shows up now — it is one that shows up at the next boot, by which time the change looks like it succeeded.",field:"value"})}function cn(r,i){return new f({code:"config_refused",message:`${r} cannot be changed from inside a conversation: ${i}.`,hint:"No permission rule overrides this, and asking again will not change it. Every other setting can be changed — including enabling a tool or adding a permission rule, which is what this tool is for. Name the exact line you would have added and let the person put it in themselves.",field:"path"})}function mi(r){return new f({code:"exec_too_many_background",message:`${r.length} commands are already running in the background, which is the limit.`,hint:`Wait for one to finish, or stop one yourself. Already running: ${r.map((i)=>i.length>60?`${i.slice(0,57)}...`:i).join("; ")}. A command that outruns its timeout is left running rather than discarded, so a loop that starts one per attempt reaches this quickly — which is the point of the limit.`})}var X="system";function lt(){return gi(pi(),`${Q.slug}-${X}`)}var yi=Un.filter((r)=>r.agentListed);function dn(r,i){let o=r.toLowerCase(),a="who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line",u="where the API listens, and what authenticates it, is not yours to decide — the same reason writeRoots is refused. Enabling it on 127.0.0.1 is settable; binding anywhere reachable is a person's call",h="widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(o.split(".").includes("writeroots"))return"widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(o.startsWith("tools.providers")&&se(i,"writeroots"))return"widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(o.split(".").includes("allowfrom"))return"who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line";if(o==="channels"&&se(i,"allowfrom"))return"who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line";if(o==="server.host"||o==="server.tokenenv")return"where the API listens, and what authenticates it, is not yours to decide — the same reason writeRoots is refused. Enabling it on 127.0.0.1 is settable; binding anywhere reachable is a person's call";if(o==="server"&&(se(i,"host")||se(i,"tokenenv")))return"where the API listens, and what authenticates it, is not yours to decide — the same reason writeRoots is refused. Enabling it on 127.0.0.1 is settable; binding anywhere reachable is a person's call";if(o==="tools.policy.deny")return"removing or replacing the deny rules is the one edit whose only purpose is to remove a restriction someone deliberately set";if(i!==void 0&&o==="tools.untrusted.onmutate"&&String(i).toLowerCase()==="allow")return'setting the write gate to "allow" turns off the check that stops text from outside the conversation driving a tool that changes things';return}function se(r,i){if(Array.isArray(r))return r.some((o)=>se(o,i));if(typeof r!=="object"||r===null)return!1;return Object.entries(r).some(([o,a])=>o.toLowerCase()===i||se(a,i))}function An(r){return r.file??Qs(r.agentDir,"agent.yaml")}var wi={slug:"config_read",provider:X,summary:"Reads this agent's own configuration and lists what can be changed in it.",whenToUse:"you need to know how you are configured, or what would have to change for you to do something you currently cannot — which tool to enable, which permission rule to add",whenNotToUse:"for anything that is not your own configuration; an ordinary file is file_read. You do not need to read it before every answer, only when the question is about how you are set up",mutating:!1,trust:"trusted",trustReason:"The manifest is the runtime's own file, written and validated by the runtime. Fencing it would put a warning about strangers around the agent's own settings.",policyArg:"path",tags:["read","config"],parameters:{type:"object",properties:{path:{type:"string",description:"A single setting, such as tools.pinned. Omit to see the whole configuration and every setting that can be changed."}}}},bi={slug:"config_set",provider:X,summary:"Changes one setting in this agent's own configuration.",whenToUse:"the person asks you to change how you are configured, or asks you to do something that needs a tool or permission you do not have and tells you to go ahead and enable it",whenNotToUse:"on your own initiative. Say what you would change and why, and let them ask — and never to remove a restriction someone set, which is refused anyway. The change takes effect when the agent next starts, not in this conversation",mutating:!0,trust:"trusted",trustReason:"It reports the old and new value of one setting the runtime just validated, and nothing else.",policyArg:"path",tags:["write","config"],parameters:{type:"object",properties:{path:{type:"string",description:"The setting, as a dotted path: tools.pinned, tools.policy.allow, model.main.temperature. config_read with no path lists them."},value:{type:"string",description:'The new value, written the way it would appear in the file: a bare word, a number, or a list as ["a", "b"]. Replaces what is there.'}},required:["path","value"]}};function vi(r){try{return Qr(r)}catch(i){throw hi(r,i instanceof Error?i.message:String(i))}}function ki(r){return async(i)=>{let o=An(r),a;try{a=await Zs(o,"utf8")}catch(w){throw Rn(o,String(w))}let u=typeof i.path==="string"?i.path.trim():"";if(u!==""){let w=K(a),k=w.getIn(u.split("."),!1);if(k===void 0)return`${u} is not set in this configuration. It can be — see config_read with no path for the full list.`;return`${u}:
12
- ${Ct(_e(k)||$e(k)?k.toJS(w):k).trimEnd()}`}let h=K(a),g=yi.map((w)=>{let k=h.getIn(w.path.split("."),!1),S=_e(k)||$e(k)?k.toJS(h):k,T=S===void 0||S===null?"(not set)":Array.isArray(S)?`[${S.map((_)=>typeof _==="object"&&_!==null?JSON.stringify(_):String(_)).join(", ")}]`:Ct(S).trim(),N=w.toAgent===void 0?w.means:`${w.means}. ${w.toAgent}`;return`- ${w.path} = ${T}
13
- ${N}`}).join(`
10
+ `)}function Fs(r){return{spec:Ms,handler:async(i,o)=>{let a=await r.call("COMPOSIO_REMOTE_WORKBENCH",{[Ps]:String(i.code??"")},o.signal);if(!a.ok)return`The workbench failed: ${a.error??"no detail supplied"}`;return Us(a.data)}}}function Ds(r){return{[Ce]:Ns(r),[Le]:js(r),[rt]:Fs(r)}}var qt="composio.session.json";function on(r){return Gs(r)?Gt(r,Q.stateDir,qt):Gt(qs(r),Q.stateDir,qt)}function Js(r,i){let o;try{o=sn(on(r),"utf8")}catch{return}try{let u=JSON.parse(o)?.sessions;if(typeof u!=="object"||u===null)return;let h=u[i];return typeof h==="string"&&h!==""?h:void 0}catch{return}}function Vs(r,i,o){let a=on(r);Ks(Ws(a),{recursive:!0});let u={};try{let v=JSON.parse(sn(a,"utf8"))?.sessions;if(typeof v==="object"&&v!==null){for(let[S,T]of Object.entries(v))if(typeof T==="string")u[S]=T}}catch{u={}}let h={sessions:{...u,[i]:o}},g=`${a}.${process.pid}.tmp`;return Hs(g,`${JSON.stringify(h,null,2)}
11
+ `,"utf8"),Bs(g,a),a}var Ys="COMPOSIO_API_KEY";class an{id="composio";#e;#t;#s;#i;#o;#r;#n;#a;#c=[];#d;constructor(r){this.#e=r.dir,this.#t=r.userId??"default",this.#s=r.now??(()=>new Date),this.#r=r.apiKeyEnv??Ys;let i=r.env[this.#r];this.#i=r.baseUrl??"https://backend.composio.dev/api/v3",this.#o=i===void 0||i===""?void 0:new Yt({apiKey:i,baseUrl:this.#i,...r.fetch===void 0?{}:{fetch:r.fetch}});let o=Pt(this.#e);this.#n=o.tools,this.#a=o.fetchedAt}async resolve(r){let i=[],o=[],a=Ds(this.#u());for(let u of r){let h=a[u];if(h!==void 0){i.push(h);continue}let g=this.#n[u];if(g===void 0)continue;if(tn(g))o.push(u);i.push(this.#h(Es(g)))}return this.#c=o,i}async list(){return[...Rs,...Object.keys(this.#n)]}async available(){return[{slug:Ce,summary:nn.summary},{slug:Le,summary:rn.summary}]}uncached(r){return r.filter((i)=>this.#n[i]===void 0)}explainUnresolved(r){if(Object.keys(this.#n).length>0||r.length===0)return;return ms(r,Te(this.#e))}describe(){return{cached:Object.keys(this.#n).length,fetchedAt:this.#a,cachePath:Te(this.#e),assumedMutating:this.#c}}async refresh(r,i){let o=this.#o;if(o===void 0)throw Ut(this.#r);let a={},u=[],h=[];for(let w of r){let v=await o.tool(w,i);if(v===void 0){u.push(w);continue}a[w]=v;let S=this.#n[w];if(S===void 0||JSON.stringify(S)!==JSON.stringify(v))h.push(w)}this.#n={...this.#n,...a};let g=fs(this.#e,this.#n,this.#i,this.#s);return this.#a=Pt(this.#e).fetchedAt,{fetched:Object.keys(a).length,missing:u,changed:h,cachePath:g}}async#l(r,i=!1){let o=this.#o;if(o===void 0)throw Ft(this.#r);if(!i){let u=this.#d??Js(this.#e,this.#t);if(u!==void 0)return this.#d=u,u}let a=await o.createSession(this.#t,r);return this.#d=a.session_id,Vs(this.#e,this.#t,a.session_id),a.session_id}#u(){return{call:async(r,i,o)=>{let a=this.#o;if(a===void 0)throw Ft(this.#r);let u=await this.#l(o),h=await a.executeMeta(u,r,i,o);if("notFound"in h){u=await this.#l(o,!0);let g=await a.executeMeta(u,r,i,o);if("notFound"in g)return{ok:!1,data:{},error:"the session could not be opened"};h=g}return h},fetchSchemas:async(r,i)=>{await this.refresh(r,i);let o={};for(let a of r){let u=this.#n[a];if(u!==void 0)o[a]=u}return o}}}#h(r){return{spec:r,handler:async(i,o)=>{let a=this.#o;if(a===void 0)throw Ut(this.#r);let u=await a.execute(r.slug,i,this.#t,o.signal);if(!u.ok){let h=u.error??"no detail supplied";if(/connected account|not connected|no connection/i.test(h)){let g=r.tags[0]??"the toolkit";throw gs(r.slug,g)}throw ps(r.slug,200,h)}return typeof u.data==="string"?u.data:JSON.stringify(u.data,null,2)}}}}var Jt=["apiKeyEnv","userId","baseUrl"];function Ye(r,i){let o=r[i];if(o===void 0)return;if(typeof o!=="string"||o==="")throw new y({code:"composio_config_invalid",message:`tools.providers.composio.${i} must be a non-empty string.`,hint:`Got ${o===null?"null":typeof o}. ${i==="apiKeyEnv"?"This is the *name* of an environment variable, never the key itself — a manifest holding a literal key fails validation.":"Remove the key to use the default."}`,field:`tools.providers.composio.${i}`});return o}function st(r){let i=Object.keys(r.config).filter((h)=>!Jt.includes(h));if(i.length>0)throw new y({code:"composio_config_unknown",message:`tools.providers.composio has ${i.length===1?"a key":"keys"} the Composio provider does not read: ${i.join(", ")}.`,hint:`Accepted keys are ${Jt.join(", ")}. Refused rather than ignored, because a setting that looks applied and is not is worse than a rejected manifest.`,field:"tools.providers.composio"});let o=Ye(r.config,"apiKeyEnv"),a=Ye(r.config,"userId"),u=Ye(r.config,"baseUrl");return new an({dir:r.dir,env:r.env,...o===void 0?{}:{apiKeyEnv:o},...a===void 0?{}:{userId:a},...u===void 0?{}:{baseUrl:u}})}var Xs="0.1.0",cn={name:"composio",version:Xs,dispachApi:"^0.1",permissions:[{kind:"network",hosts:["backend.composio.dev"]},{kind:"env",vars:["COMPOSIO_API_KEY"]},{kind:"fs",paths:["<state>/composio"],mode:"write"}],setup(r){r.defineToolProvider("composio",st)}};import{readFile as zs}from"node:fs/promises";import{join as Zs}from"node:path";import{tmpdir as mi}from"node:os";import{join as pi}from"node:path";import{mkdir as _i,realpath as Ei,rm as fn,stat as Ti}from"node:fs/promises";import{isAbsolute as Ri,resolve as ct}from"node:path";import{open as Cn}from"node:fs/promises";import{existsSync as Ni}from"node:fs";import{homedir as pn}from"node:os";import{isAbsolute as jn,relative as Li,resolve as be,sep as ji}from"node:path";import{spawn as Bi}from"node:child_process";import{open as Hi,readFile as Wi}from"node:fs/promises";import{mkdir as po,readFile as Kn,stat as Bn,writeFile as Hn}from"node:fs/promises";import{dirname as go,isAbsolute as yo,resolve as wn}from"node:path";import{isAbsolute as wo,relative as bo,resolve as vo,sep as Wn}from"node:path";import{readFile as Lo}from"node:fs/promises";import{readdir as jo}from"node:fs/promises";import{join as Mo,relative as Po,sep as kn}from"node:path";import{statSync as qo}from"node:fs";import{mkdir as Jo,rm as Rn}from"node:fs/promises";import{delimiter as Vo,join as at}from"node:path";function Qs(){return new f({code:"exec_command_empty",message:"exec was called with no command.",hint:"Put the whole shell command in the command field, exactly as it would be typed at a prompt — for example `ls -la` or `npm test`."})}function ei(r,i){return new y({code:"exec_workdir_missing",message:`The directory to run in does not exist: ${r}`,hint:i?"This is where a previous exec call left the shell, and it has since been removed or renamed. The remembered directory has been cleared, so the next call starts from the agent's own directory; pass workdir to choose a different one.":"workdir must name a directory that already exists. A relative path is resolved against the directory the last exec call ended in, the way a shell would.",field:"workdir"})}function ti(r,i){return new f({code:"exec_pty_unavailable",message:`A terminal was requested and this machine cannot provide one: ${i}`,hint:`pty: true allocates a terminal with the system \`script\` command, which is missing or unusable on this ${r} host. Refused rather than quietly falling back to a pipe: the fallback would run the command with no terminal while the observation claimed otherwise, and a program that checks isatty() would take the other branch with nothing reporting it. Re-run with pty omitted if the command does not need one.`,field:"pty"})}function ln(r,i){return new f({code:"exec_spawn_failed",message:`The shell could not be started for: ${r}`,hint:`The operating system refused before the command ran, so nothing was executed: ${i}. This is a failure of the host rather than of the command — check that /bin/sh exists and that the directory is readable.`})}function ni(){return new f({code:"file_path_empty",message:"A file tool was called with no path.",hint:"Give the path field a value — either absolute, or relative to the current working directory, which is wherever the last exec call left it."})}function An(r){return new f({code:"file_missing",message:`There is no file at ${r}.`,hint:"Check the path against what glob returns rather than guessing at it. A relative path is resolved against the current working directory, which starts at the agent's own directory and moves when a shell command changes it.",field:"path"})}function ri(r,i,o){return new f({code:"file_too_large",message:`${r} is ${i} bytes, over the ${o}-byte limit for reading.`,hint:"Use grep to find the part that matters and read around it with offset and limit, rather than pulling the whole file into the conversation.",field:"path"})}function si(r,i){return new f({code:"file_is_binary",message:`${r} is not a text file (${i} bytes).`,hint:"Refused rather than decoded: a binary rendered as text is thousands of meaningless tokens and no information. If something about the file is needed — its type, its size, what it contains — a shell command that inspects it will answer better.",field:"path"})}function ii(r,i){return new f({code:"file_protected",message:`${r} cannot be written: ${i}.`,hint:"This is a standing rule and no permission setting overrides it — a rule that authorised writing to the agent's own definition would be a rule authorising its own replacement. Say what change was wanted and let the person make it themselves.",field:"path"})}function oi(r,i){let o=i.length>120?`${i.slice(0,120)}…`:i;return new f({code:"file_edit_no_match",message:`That text does not appear in ${r}: ${JSON.stringify(o)}`,hint:"The match is exact, including indentation and line breaks. Read the file and copy the text out of it rather than reconstructing it from memory — nothing was changed, so the file is still as it was.",field:"find"})}function ai(r,i){return new f({code:"file_edit_ambiguous",message:`That text appears ${i} times in ${r}, so it does not identify one place.`,hint:"Nothing was changed: picking one of several matches would be a guess, and a wrong guess reports success while editing the wrong line. Include a surrounding line or two to make it unique, or pass all: true if every occurrence should change.",field:"find"})}function ci(r,i){return new f({code:"grep_pattern_invalid",message:`That is not a valid regular expression: ${r}`,hint:`${i}. Refused rather than searched literally — a literalised pattern finds nothing and returns an empty result, which reads as "it is not there" instead of "the pattern was wrong". Escape any regex character meant literally, such as a dot or a bracket.`,field:"pattern"})}function di(r,i){return new f({code:"file_outside_root",message:`${r} is outside the directories this agent may change.`,hint:`Writable: ${i.join(", ")}. Everything else is read-only by default — an agent that has misunderstood a request cannot damage anything while misunderstanding it. To work somewhere else, the person you work for adds it to tools.providerConfig.writeRoots in agent.yaml; nothing said in a conversation can add one. Reading outside these directories is allowed and unaffected.`,field:"path"})}function On(r,i){return new f({code:"config_read_failed",message:`This agent's configuration could not be read from ${r}.`,hint:`${i}. The agent is running, so the file existed at boot — it has been moved or its permissions have changed since.`})}function li(r,i){return new f({code:"config_path_unknown",message:`"${r}" is not a setting config_set will change.`,hint:`Settable: ${i.join(", ")}. Deliberately a list rather than anything the schema accepts: a tool that can write any field can write the ones that decide what it is allowed to do, and the list is where that judgement lives. Call config_read with no path to see each one explained.`,field:"path"})}function ui(r,i){return new f({code:"config_value_unreadable",message:`That value could not be read: ${JSON.stringify(r)}`,hint:`${i}. Write it the way it would appear in the file — a bare word, a number, or a list as ["a", "b"]. Refused rather than guessed at, because guessing is how tools.pinned becomes a list of single characters.`,field:"value"})}function hi(r,i,o){return new f({code:"config_invalid",message:`Setting ${r} to ${JSON.stringify(i)} would produce a configuration that does not load: ${o}`,hint:"Nothing was written, so the agent is unchanged and still starts. An invalid manifest is not a failure that shows up now — it is one that shows up at the next boot, by which time the change looks like it succeeded.",field:"value"})}function un(r,i){return new f({code:"config_refused",message:`${r} cannot be changed from inside a conversation: ${i}.`,hint:"No permission rule overrides this, and asking again will not change it. Every other setting can be changed — including enabling a tool or adding a permission rule, which is what this tool is for. Name the exact line you would have added and let the person put it in themselves.",field:"path"})}function fi(r){return new f({code:"exec_too_many_background",message:`${r.length} commands are already running in the background, which is the limit.`,hint:`Wait for one to finish, or stop one yourself. Already running: ${r.map((i)=>i.length>60?`${i.slice(0,57)}...`:i).join("; ")}. A command that outruns its timeout is left running rather than discarded, so a loop that starts one per attempt reaches this quickly — which is the point of the limit.`})}var W="system";function ut(){return pi(mi(),`${Q.slug}-${W}`)}var gi=De.filter((r)=>r.agentListed);function hn(r,i){let o=r.toLowerCase(),a="who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line",u="where the API listens, and what authenticates it, is not yours to decide — the same reason writeRoots is refused. Enabling it on 127.0.0.1 is settable; binding anywhere reachable is a person's call",h="widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(o.split(".").includes("writeroots"))return"widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(o.startsWith("tools.providers")&&se(i,"writeroots"))return"widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(o.split(".").includes("allowfrom"))return"who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line";if(o==="channels"&&se(i,"allowfrom"))return"who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line";if(o==="server.host"||o==="server.tokenenv")return"where the API listens, and what authenticates it, is not yours to decide — the same reason writeRoots is refused. Enabling it on 127.0.0.1 is settable; binding anywhere reachable is a person's call";if(o==="server"&&(se(i,"host")||se(i,"tokenenv")))return"where the API listens, and what authenticates it, is not yours to decide — the same reason writeRoots is refused. Enabling it on 127.0.0.1 is settable; binding anywhere reachable is a person's call";if(o==="tools.policy.deny")return"removing or replacing the deny rules is the one edit whose only purpose is to remove a restriction someone deliberately set";if(i!==void 0&&o==="tools.untrusted.onmutate"&&String(i).toLowerCase()==="allow")return'setting the write gate to "allow" turns off the check that stops text from outside the conversation driving a tool that changes things';return}function se(r,i){if(Array.isArray(r))return r.some((o)=>se(o,i));if(typeof r!=="object"||r===null)return!1;return Object.entries(r).some(([o,a])=>o.toLowerCase()===i||se(a,i))}function In(r){return r.file??Zs(r.agentDir,"agent.yaml")}var yi={slug:"config_read",provider:W,summary:"Reads this agent's own configuration and lists what can be changed in it.",whenToUse:"you need to know how you are configured, or what would have to change for you to do something you currently cannot — which tool to enable, which permission rule to add",whenNotToUse:"for anything that is not your own configuration; an ordinary file is file_read. You do not need to read it before every answer, only when the question is about how you are set up",mutating:!1,trust:"trusted",trustReason:"The manifest is the runtime's own file, written and validated by the runtime. Fencing it would put a warning about strangers around the agent's own settings.",policyArg:"path",tags:["read","config"],parameters:{type:"object",properties:{path:{type:"string",description:"A single setting, such as tools.pinned. Omit to see the whole configuration and every setting that can be changed."}}}},wi={slug:"config_set",provider:W,summary:"Changes one setting in this agent's own configuration.",whenToUse:"the person asks you to change how you are configured, or asks you to do something that needs a tool or permission you do not have and tells you to go ahead and enable it",whenNotToUse:"on your own initiative. Say what you would change and why, and let them ask — and never to remove a restriction someone set, which is refused anyway. The change takes effect when the agent next starts, not in this conversation",mutating:!0,trust:"trusted",trustReason:"It reports the old and new value of one setting the runtime just validated, and nothing else.",policyArg:"path",tags:["write","config"],parameters:{type:"object",properties:{path:{type:"string",description:"The setting, as a dotted path: tools.pinned, tools.policy.allow, model.main.temperature. config_read with no path lists them."},value:{type:"string",description:'The new value, written the way it would appear in the file: a bare word, a number, or a list as ["a", "b"]. Replaces what is there.'}},required:["path","value"]}};function bi(r){try{return Vt(r)}catch(i){throw ui(r,i instanceof Error?i.message:String(i))}}function vi(r){return async(i)=>{let o=In(r),a;try{a=await zs(o,"utf8")}catch(w){throw On(o,String(w))}let u=typeof i.path==="string"?i.path.trim():"";if(u!==""){let w=U(a),v=w.getIn(u.split("."),!1);if(v===void 0)return`${u} is not set in this configuration. It can be — see config_read with no path for the full list.`;return`${u}:
12
+ ${Dt(Ae(v)||Re(v)?v.toJS(w):v).trimEnd()}`}let h=U(a),g=gi.map((w)=>{let v=h.getIn(w.path.split("."),!1),S=Ae(v)||Re(v)?v.toJS(h):v,T=S===void 0||S===null?"(not set)":Array.isArray(S)?`[${S.map((_)=>typeof _==="object"&&_!==null?JSON.stringify(_):String(_)).join(", ")}]`:Dt(S).trim(),L=w.toAgent===void 0?w.means:`${w.means}. ${w.toAgent}`;return`- ${w.path} = ${T}
13
+ ${L}`}).join(`
14
14
  `);return[`This agent is ${h.get("name")??h.get("id")}, configured at ${o}.`,"","Settings config_set can change, with their current values:",g,"","Anything not on this list is not settable from a conversation. A change takes effect when the agent next starts, not in the current conversation.","","Some edits are refused whatever the rules say. Removing a check: replacing tools.policy.deny, or setting tools.untrusted.onMutate to allow. Deciding reach: a writeRoots list anywhere, a channel's allowFrom, and server.host or server.tokenEnv. Enabling a capability is what a person asks you for; where you may write, who may talk to you, and what address you listen on are theirs — name what you need and why, and let them add it.","",`The whole file, comments and all, is at ${o} — read it with file_read if that tool is enabled, or ask the person to open it.`].join(`
15
- `)}}function $i(r){return async(i)=>{let o=An(r),a=typeof i.path==="string"?i.path.trim():"",u=typeof i.value==="string"?i.value:String(i.value??""),h=dn(a);if(h!==void 0)throw cn(a,h);if(!cr.includes(a))throw ui(a,cr);let g=vi(u),w=dn(a,g);if(w!==void 0)throw cn(a,w);let k;try{k=await Jr({file:o,path:a.split("."),value:g})}catch(T){if(T instanceof j&&T.code==="manifest_edit_unreadable")throw Rn(o,String(T.cause??T.message));if(T instanceof j&&T.code==="manifest_edit_invalid"){let N=T.message.slice(T.message.indexOf(": ")+2);throw fi(a,u,N)}throw T}let S=k.before!==void 0;return[`Set ${a} in ${o}.`,S?`It was: ${Ct(k.before).trim()}`:"It was not set before.",`It is now: ${Ct(g).trim()}`,"","The configuration still validates. This takes effect when the agent next starts — nothing in the current conversation changes, so do not try the new tool yet.",...Si(k.manifest,g)].join(`
16
- `)}}function Si(r,i){if(!se(i,"tokenenv")&&!se(i,"apikeyenv"))return[];let o=new Set;for(let a of r.channels??[]){let u=a.tokenEnv;if(typeof u==="string"&&u!=="")o.add(u)}if(o.size===0)return[];return["",`This will NOT start until ${[...o].join(" and ")} ${o.size===1?"is":"are"} set in the .env beside the manifest — the value is read at boot, and a missing one fails the load rather than the first message. You cannot write that file; it is protected because it holds every secret here. Tell the person the variable name and where it goes.`]}function _i(r){return[{spec:wi,handler:ki(r)},{spec:bi,handler:$i(r)}]}var xi=6000,Oi=3000,un=1500,Ii=new TextDecoder("utf-8");async function st(r,i,o){let a=await xn(r,"r");try{let u=new Uint8Array(o),{bytesRead:h}=await a.read(u,0,o,i);return Ii.decode(u.subarray(0,h))}finally{await a.close()}}async function Cn(r){let i=await xn(r,"r"),o;try{o=(await i.stat()).size}finally{await i.close()}if(o<=xi)return{head:Se(await st(r,0,o)),tail:"",bytes:o,spilled:!1};return{head:Se(await st(r,0,Oi)),tail:Se(await st(r,o-un,un)),bytes:o,spilled:!0}}function Ci(r){return r.replace(/^(?:\^[A-Z?]\s*)+/,"")}function Ni(r){if(r<1024)return`${r} B`;if(r<1048576)return`${(r/1024).toFixed(1)} KB`;return`${(r/1048576).toFixed(1)} MB`}function Pi(r){if(r==="~")return hn();return r.startsWith("~/")?Ee(hn(),r.slice(2)):r}var Ui="workspace";function Fi(r,i=[]){let o=Ee(r),a=Ee(o,Ui);return{primary:Li(a)?a:o,extra:i.map((u)=>Nn(u)?Ee(u):Ee(o,u))}}function Di(r,i){if(r===i)return!0;let o=ji(i,r);return o!==""&&!o.startsWith(`..${Mi}`)&&o!==".."&&!Nn(o)}function Ln(r){return[r.primary,...r.extra]}function Ki(r,i){return Ln(i).some((o)=>Di(r,o))}function Bi(r,i){let o=r.extra.length===0?"":` Also writable: ${r.extra.join(", ")}.`;if(i==="read")return` Relative paths are resolved against ${r.primary}. Reading elsewhere is allowed — give an absolute path for it.`;if(i==="write")return` You work in ${r.primary}. A relative path lands there, and that is where anything you create belongs unless the person names somewhere else. Writing anywhere else is refused.${o}`;return` Every command starts in ${r.primary}, and that is where anything you create belongs unless the person names somewhere else. Nothing stops a command from leaving it, so this one is on you: use a relative path, and do not reach for ~ or an absolute path outside it on your own initiative.${o}`}function ut(r,i,o,a=r.mutating?"write":"read"){let u={...r.parameters.properties};for(let h of o){let g=u[h];if(g===void 0)continue;u[h]={...g,description:`${g.description??""}${Bi(i,a)}`}}return{...r,parameters:{...r.parameters,properties:u}}}var oe=new Map,qi=8;function Ji(){return[...oe.entries()].map(([r,i])=>({pid:r,...i})).sort((r,i)=>i.since-r.since)}function Vi(){let r=[];for(let[i,o]of oe)try{process.kill(-i,"SIGTERM"),r.push(`${i} (${o.command})`)}catch{}return oe.clear(),r}function Yi(){for(let r of[...oe.keys()])try{process.kill(r,0)}catch{oe.delete(r)}}var Xi=250,fn=2000,zi=new Set(["sleep","git","ssh","scp","sudo","su","doas"]);function Zi(r){for(let i of r.split(/\s+/)){if(/^[A-Za-z_]\w*=/.test(i))continue;return i.replace(/^.*\//,"").toLowerCase()}return""}function Qi(r){let i=Xr(r);if(i.length===0)return!1;return i.every((o)=>!zi.has(Zi(o)))}function jn(r){return`'${r.replaceAll("'","'\\''")}'`}function eo(r,i){return[r,"__code=$?",`{ printf '%s\\n' "$__code"; pwd; } > ${jn(i)} 2>/dev/null`,"exit $__code"].join(`
17
- `)}function to(r,i,o=process.platform){if(!i)return{file:"/bin/sh",args:["-c",r],env:{}};if(o==="linux")return{file:"script",args:["-qec",`/bin/sh -c ${jn(r)}`,"/dev/null"],env:{SHELL:"/bin/sh"}};return{file:"script",args:["-q","/dev/null","/bin/sh","-c",r],env:{SHELL:"/bin/sh"}}}function je(r,i){let o=r.pid;if(o===void 0)return;try{process.kill(-o,i)}catch{}}async function no(r){try{let[i,o]=(await Gi(r,"utf8")).split(`
18
- `),a=Number.parseInt(i??"",10),u=o?.trim();return{...Number.isNaN(a)?{}:{code:a},...u===void 0||u===""?{}:{cwd:u}}}catch{return{}}}async function Mn(r){if(Yi(),oe.size>=qi)throw mi(Ji().map((S)=>S.command));let i=eo(r.command,r.statusPath),{file:o,args:a,env:u}=to(i,r.pty),h=await Wi(r.outPath,"w"),g;try{g=Hi(o,a,{cwd:r.cwd,env:{...r.env,...u},stdio:["ignore",h.fd,h.fd],detached:!0})}catch(S){throw await h.close(),an(r.command,String(S))}let w=await new Promise((S,T)=>{let N=!1,_=!1,R=setTimeout(L,r.background?Xi:r.timeoutMs),M=(U)=>{if(N)return;N=!0,clearTimeout(R),r.signal.removeEventListener("abort",F),S(U)};function L(){if(r.background||Qi(r.command)){if(g.unref(),g.pid!==void 0)oe.set(g.pid,{command:r.command,since:Date.now(),outPath:r.outPath});M({ending:"backgrounded",...g.pid===void 0?{}:{pid:g.pid}});return}_=!0,je(g,"SIGTERM"),setTimeout(()=>je(g,"SIGKILL"),fn).unref?.()}function F(){je(g,"SIGTERM"),setTimeout(()=>je(g,"SIGKILL"),fn).unref?.()}r.signal.addEventListener("abort",F,{once:!0}),g.on("error",(U)=>{if(N)return;N=!0,clearTimeout(R),r.signal.removeEventListener("abort",F),T(r.pty&&so(U)?ni(process.platform,String(U)):an(r.command,String(U)))}),g.on("exit",(U,de)=>{M({ending:_?"killed":"finished",...U===null?{}:{code:U},...de===null?{}:{killedBy:de},...g.pid===void 0?{}:{pid:g.pid}})})}).finally(()=>h.close()),k=await no(r.statusPath);return{...w,...k.code===void 0?{}:{code:k.code},...k.cwd===void 0?{}:{cwdAfter:k.cwd}}}function so(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}var ct=120000,Pn=600000,io=5000,ao={slug:"exec",provider:X,summary:"Runs a shell command on this computer and returns what it printed.",whenToUse:"you need to do something on this machine that no other tool covers — run a build or a test suite, use a command-line program, inspect what is running, or move and archive files in bulk",whenNotToUse:"reading one file, writing one file, or finding files by name or content — use file_read, file_write, glob and grep instead. They are more reliable and their targets can be checked against the permission rules; a path buried in a shell string cannot be",mutating:!0,trust:"untrusted",policyArg:"command",tags:["write","system","shell"],parameters:{type:"object",properties:{command:{type:"string",description:"The command, exactly as it would be typed at a shell prompt. Set environment variables inline (VAR=value command) rather than expecting them to survive from an earlier call."},workdir:{type:"string",description:"Directory to run in. Relative paths are resolved against wherever the previous command ended up. Defaults to that directory, so a cd carries over."},timeoutMs:{type:"integer",description:`How long to wait, in milliseconds. Default ${ct}, maximum ${Pn}.`,default:ct},pty:{type:"boolean",description:"Give the command a terminal. Needed only by programs that behave differently without one, such as those that ask for a password or draw a progress display.",default:!1},background:{type:"boolean",description:"Start it and return immediately instead of waiting. Use for something long-running like a dev server; the output keeps accumulating in a file whose path is reported.",default:!1}},required:["command"]}};function co(r,i){let o=r===void 0||r<=0?ct:r,a=Math.min(o,Pn),u=i-io;return Math.max(1,Math.min(a,u>0?u:Math.floor(i*0.8)))}function mn(r){return typeof r==="number"&&Number.isFinite(r)?r:void 0}function lo(r,i){let o=lt();return{out:at(o,`${r.turnId}-${i}.log`),status:at(o,`${r.turnId}-${i}.status`)}}function uo(r){return async(i,o)=>{let a=typeof i.command==="string"?i.command.trim():"";if(a==="")throw ei();let u=r.sessions.lastCwd(o.sessionKey),h=u??r.roots.primary,g=typeof i.workdir==="string"?i.workdir.trim():"",w=g===""?h:Ai(g)?g:at(h,g),k;try{if(k=await Ti(w),!(await Ri(k)).isDirectory())throw Error("not a directory")}catch{let U=g===""&&u!==void 0;if(U)r.sessions.forget(o.sessionKey);throw ti(w,U)}let S=co(mn(i.timeoutMs),o.deadlineMs),T=mn(i.timeoutMs)!==void 0&&S<Number(i.timeoutMs),N=i.background===!0,_=lt();await Ei(_,{recursive:!0});let R=lo(o,ho(a,o.turnId)),M=await Mn({command:a,cwd:k,env:r.env,timeoutMs:S,pty:i.pty===!0,background:N,signal:o.signal,outPath:R.out,statusPath:R.status});if(M.cwdAfter!==void 0)r.sessions.remember(o.sessionKey,M.cwdAfter);let L=await Cn(R.out),F=i.pty===!0?{...L,head:Ci(L.head)}:L;if(await ln(R.status,{force:!0}),!F.spilled&&M.ending!=="backgrounded")await ln(R.out,{force:!0});return fo({command:a,cwd:k,run:M,observation:F,clamped:T,timeoutMs:S,path:R.out})}}function ho(r,i){let o=2166136261;for(let a of[r,i])for(let u=0;u<a.length;u+=1)o^=a.charCodeAt(u),o=Math.imul(o,16777619);return(o>>>0).toString(16).padStart(8,"0")}function fo(r){let i=[];if(r.clamped)i.push(`The requested timeout was longer than allowed, so this ran with ${r.timeoutMs} ms.`);if(r.run.ending==="backgrounded")return i.push(`Still running${r.run.pid===void 0?"":` as process ${r.run.pid}`}. It was left alone rather than stopped, and keeps writing to ${r.path}; read that file to see how far it has got. Nothing here is its final result.`),[...i,it("Output so far",r.observation.head)].join(`
19
-
20
- `);if(r.run.ending==="killed")i.push(`Stopped after ${r.timeoutMs} ms without finishing, and everything it started was stopped with it. Whatever it had already done still happened.`);else if(r.run.code!==void 0&&r.run.code!==0)i.push(`Failed with exit code ${r.run.code}.`);else if(r.run.killedBy!==void 0)i.push(`Ended on signal ${r.run.killedBy}.`);if(r.run.cwdAfter!==void 0&&r.run.cwdAfter!==r.cwd)i.push(`The working directory is now ${r.run.cwdAfter}, and the next exec call starts there.`);let o=r.run.ending==="killed"||(r.run.code??0)!==0,a=[];if(r.observation.spilled){if(i.push(`Output was ${Ni(r.observation.bytes)}, too much to include. All of it is in ${r.path}; what follows is the ${o?"start and end":"start"}.`),a.push(it("First part of the output",r.observation.head)),o)a.push(it("End of the output",r.observation.tail))}else if(r.observation.head.trim()!=="")a.push(r.observation.head.trimEnd());else if(i.length===0)return"The command finished successfully and printed nothing.";return[...i,...a].join(`
21
-
22
- `)}function it(r,i){return`${r}:
23
- ${i.trimEnd()}`}function mo(r){return{spec:ut(ao,r.roots,["command","workdir"],"shell"),handler:uo(r)}}var ko=["agent.yaml","agent.yml","SOUL.md","SOUL.compact.md","AGENTS.md","POLICY.md","REMINDER.md"],$o=[".ssh",".aws",".kube",".gnupg",".docker"],So=/^(?:\.env(\..+)?|\.netrc|\.npmrc|\.pypirc|id_[a-z0-9]+|.*\.pem|.*\.key)$/i;function _o(r){return r.split(Bn).filter((i)=>i!=="")}function Eo(r,i){let o=_o(r),a=o[o.length-1]??"";for(let w of $o)if(o.includes(w))return`${w}/ holds credentials, and nothing under it is writable by an agent`;if(So.test(a))return`${a} holds secrets — the manifest names environment variables, and their values are not the agent's to edit`;let u=vo(i.agentDir),h=bo(u,r);if(h!==""&&!h.startsWith("..")&&!wo(h)){let w=h.split(Bn),k=w[w.length-1]??"";if(ko.includes(k))return`${h} is part of this agent's own definition — who it is, what it does, or what it is permitted to do — and it is not editable from inside a turn`;if(w[0]?.startsWith(".")===!0)return`${h} is runtime state this agent depends on`}for(let w of i.extra??[])if(r.includes(w)||a===w)return`${a} is listed in tools.providerConfig.protect`;return}var gn=2000000,dt=400;function To(r){return r.subarray(0,8000).includes(0)}var Ro={slug:"file_read",provider:X,summary:"Reads a file and returns its contents.",whenToUse:"you need to see what is in a file — its code, its configuration, its text — before answering about it or changing it",whenNotToUse:"you are looking for which files exist or which ones mention something; that is glob and grep. Never read a file by running cat through the shell",mutating:!1,trust:"untrusted",policyArg:"path",tags:["read","file"],parameters:{type:"object",properties:{path:{type:"string",description:"The file, absolute or relative to the current working directory."},offset:{type:"integer",description:"First line to return, counting from 1. Use for a long file."},limit:{type:"integer",description:`How many lines to return. Defaults to ${dt}.`,default:dt}},required:["path"]}},Ao={slug:"file_write",provider:X,summary:"Writes a file, creating any folders it needs, and replaces it if it already exists.",whenToUse:"you are creating a new file, or replacing one whose whole contents you are producing. Folders in the path are created for you, so this needs no separate step and no shell",whenNotToUse:"you are changing part of an existing file — that is file_edit, which cannot silently destroy the rest of it",mutating:!0,trust:"trusted",trustReason:"It reports what it wrote — the path, the line count — and never any of the content, so nothing from the file reaches the model through it.",policyArg:"path",tags:["write","file"],parameters:{type:"object",properties:{path:{type:"string",description:"The file, absolute or relative to the current working directory."},content:{type:"string",description:"The complete new contents."}},required:["path","content"]}},xo={slug:"file_edit",provider:X,summary:"Replaces an exact piece of text in a file, leaving the rest untouched.",whenToUse:"you are changing part of a file you have already read — a line, a block, a value — and everything else should stay as it is",whenNotToUse:"you have not read the file in this conversation, or you are writing the whole thing; guessing at text that is already there fails rather than damaging the file, but it still wastes the step",mutating:!0,trust:"trusted",trustReason:"It reports which occurrence changed and how long the file now is, never the text on either side of the change.",policyArg:"path",tags:["write","file"],parameters:{type:"object",properties:{path:{type:"string",description:"The file, absolute or relative to the current working directory."},find:{type:"string",description:"The exact text to replace, copied from the file including its indentation. It must appear exactly once unless all is true."},replace:{type:"string",description:"What to put in its place."},all:{type:"boolean",description:"Replace every occurrence instead of requiring exactly one.",default:!1}},required:["path","find","replace"]}};function Me(r,i,o,a){let u=Pi(typeof r==="string"?r.trim():"");if(u==="")throw ri();let h=i.lastCwd(o)??a;return yo(u)?pn(u):pn(h,u)}function Hn(r,i){if(!Ki(r,i.roots))throw li(r,Ln(i.roots));let o=Eo(r,{agentDir:i.agentDir,...i.protect===void 0?{}:{extra:i.protect}});if(o!==void 0)throw oi(r,o)}function bn(r){return typeof r==="number"&&Number.isFinite(r)?r:void 0}function Oo(r){return async(i,o)=>{let a=Me(i.path,r.sessions,o.sessionKey,r.roots.primary),u;try{u=(await Dn(a)).size}catch{throw Tn(a)}if(u>gn)throw si(a,u,gn);let h=await Fn(a);if(To(h))throw ii(a,u);let w=Se(h.toString("utf8")).split(`
24
- `),k=Math.max(1,bn(i.offset)??1),S=Math.max(1,bn(i.limit)??dt),T=w.slice(k-1,k-1+S);if(T.length===0)return`${a} has ${w.length} lines, so there is nothing at line ${k}.`;let N=T.join(`
25
- `),_=k-1+T.length;if(k===1&&_>=w.length)return N;return`Lines ${k}-${_} of ${w.length} in ${a}:
26
- ${N}`}}function Io(r){return async(i,o)=>{let a=Me(i.path,r.sessions,o.sessionKey,r.roots.primary);Hn(a,r);let u=typeof i.content==="string"?i.content:String(i.content??""),h=await Dn(a).then(()=>!0,()=>!1);await po(go(a),{recursive:!0}),await Kn(a,u,"utf8");let g=u===""?0:u.split(`
27
- `).length;return`${h?"Replaced":"Created"} ${a} — ${g} line${g===1?"":"s"}, ${u.length} characters.`}}function Co(r){return async(i,o)=>{let a=Me(i.path,r.sessions,o.sessionKey,r.roots.primary);Hn(a,r);let u=typeof i.find==="string"?i.find:"",h=typeof i.replace==="string"?i.replace:"",g;try{g=await Fn(a,"utf8")}catch{throw Tn(a)}let w=u===""?0:g.split(u).length-1;if(w===0)throw ai(a,u);if(w>1&&i.all!==!0)throw ci(a,w);let k=i.all===!0?g.split(u).join(h):g.replace(u,h);await Kn(a,k,"utf8");let S=i.all===!0?w:1;return`Edited ${a} — replaced ${S} occurrence${S===1?"":"s"}. The file is now ${k.split(`
28
- `).length} lines.`}}function No(r){let i=(o)=>ut(o,r.roots,["path"]);return[{spec:i(Ro),handler:Oo(r)},{spec:i(Ao),handler:Io(r)},{spec:i(xo),handler:Co(r)}]}var Uo=new Set(["node_modules",".git",".hg",".svn","dist","build","out",".next",".turbo",".cache","coverage","__pycache__",".venv","venv","target","vendor"]);function Wn(r){let i="";for(let o=0;o<r.length;o+=1){let a=r[o]??"";if(a==="*"){if(r[o+1]==="*"){if(r[o+2]==="/"){i+="(?:.*/)?",o+=2;continue}i+=".*",o+=1;continue}i+="[^/]*";continue}if(a==="?"){i+="[^/]";continue}i+=a.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${i}$`)}function Fo(r){return vn==="/"?r:r.split(vn).join("/")}async function Gn(r,i){let o=[],a=[r];while(a.length>0){let u=a.shift();if(u===void 0)break;let h;try{h=await jo(u,{withFileTypes:!0})}catch{continue}for(let g of h){let w=Mo(u,g.name);if(g.isDirectory()){if(Uo.has(g.name))continue;if(i.hidden!==!0&&g.name.startsWith("."))continue;a.push(w);continue}if(!g.isFile())continue;if(i.hidden!==!0&&g.name.startsWith("."))continue;let k=Fo(Po(r,w));if(i.accept!==void 0&&!i.accept(k))continue;if(o.length>=i.limit)return{files:o,truncated:!0};o.push(k)}}return{files:o,truncated:!1}}var kn=200,$n=100,Do=1e6,Ko={slug:"glob",provider:X,summary:"Finds files whose path matches a pattern.",whenToUse:"you need to know which files exist, or where a file is, when you know something about its name — every test file, every yaml, anything under a directory",whenNotToUse:"you know what a file is called and want to see it, which is file_read; or you are searching for text inside files, which is grep",mutating:!1,trust:"untrusted",policyArg:"pattern",tags:["read","file","search"],parameters:{type:"object",properties:{pattern:{type:"string",description:"A path pattern. * matches within one directory, ** matches across directories — for example **/*.test.ts or src/**/index.*"},path:{type:"string",description:"Directory to search under. Defaults to the current directory."},hidden:{type:"boolean",description:"Include files and directories whose name begins with a dot.",default:!1}},required:["pattern"]}},Bo={slug:"grep",provider:X,summary:"Finds lines in files that match a regular expression.",whenToUse:"you need to find where something is written — a function name, a setting, a phrase — without knowing which file it is in",whenNotToUse:"you are looking for files by name, which is glob; or you already know the file, in which case read it. Never run grep or rg through the shell",mutating:!1,trust:"untrusted",policyArg:"pattern",tags:["read","file","search"],parameters:{type:"object",properties:{pattern:{type:"string",description:"A regular expression, matched against each line."},path:{type:"string",description:"Directory to search under. Defaults to the current directory."},glob:{type:"string",description:"Only search files whose path matches this, for example **/*.ts. Searches everything if omitted."},ignoreCase:{type:"boolean",description:"Match regardless of case.",default:!1}},required:["pattern"]}};function qn(r,i,o){let a=typeof r.path==="string"&&r.path.trim()!==""?r.path:".";return Me(a,i.sessions,o,i.roots.primary)}function Ho(r){return async(i,o)=>{let a=typeof i.pattern==="string"?i.pattern.trim():"",u=qn(i,r,o.sessionKey),h=Wn(a),g=await Gn(u,{limit:kn,...i.hidden===!0?{hidden:!0}:{},accept:(k)=>h.test(k)});if(g.files.length===0)return`No file under ${u} matches ${a}. Directories like node_modules, .git and dist are never searched${i.hidden===!0?"":", and dot-files are skipped unless hidden is true"}.`;return`${g.truncated?`The first ${g.files.length} of more than ${kn} matches for ${a} under ${u} — narrow the pattern to see the rest:`:`${g.files.length} match${g.files.length===1?"":"es"} for ${a} under ${u}:`}
15
+ `)}}function ki(r){return async(i)=>{let o=In(r),a=typeof i.path==="string"?i.path.trim():"",u=typeof i.value==="string"?i.value:String(i.value??""),h=hn(a);if(h!==void 0)throw un(a,h);if(!pr.includes(a))throw li(a,pr);let g=bi(u),w=hn(a,g);if(w!==void 0)throw un(a,w);let v;try{v=await Zt({file:o,path:a.split("."),value:g})}catch(T){if(T instanceof z&&T.code==="manifest_edit_unreadable")throw On(o,String(T.cause??T.message));if(T instanceof z&&T.code==="manifest_edit_invalid"){let L=T.message.slice(T.message.indexOf(": ")+2);throw hi(a,u,L)}throw T}let S=v.before!==void 0;return[`Set ${a} in ${o}.`,S?`It was: ${Dt(v.before).trim()}`:"It was not set before.",`It is now: ${Dt(g).trim()}`,"","The configuration still validates. This takes effect when the agent next starts — nothing in the current conversation changes, so do not try the new tool yet.",...$i(v.manifest,g)].join(`
16
+ `)}}function $i(r,i){if(!se(i,"tokenenv")&&!se(i,"apikeyenv"))return[];let o=new Set;for(let a of r.channels??[]){let u=a.tokenEnv;if(typeof u==="string"&&u!=="")o.add(u)}if(o.size===0)return[];return["",`This will NOT start until ${[...o].join(" and ")} ${o.size===1?"is":"are"} set in the .env beside the manifest — the value is read at boot, and a missing one fails the load rather than the first message. You cannot write that file; it is protected because it holds every secret here. Tell the person the variable name and where it goes.`]}function Si(r){return[{spec:yi,handler:vi(r)},{spec:wi,handler:ki(r)}]}var Ai=6000,xi=3000,mn=1500,Oi=new TextDecoder("utf-8");async function it(r,i,o){let a=await Cn(r,"r");try{let u=new Uint8Array(o),{bytesRead:h}=await a.read(u,0,o,i);return Oi.decode(u.subarray(0,h))}finally{await a.close()}}async function Nn(r){let i=await Cn(r,"r"),o;try{o=(await i.stat()).size}finally{await i.close()}if(o<=Ai)return{head:xe(await it(r,0,o)),tail:"",bytes:o,spilled:!1};return{head:xe(await it(r,0,xi)),tail:xe(await it(r,o-mn,mn)),bytes:o,spilled:!0}}function Ii(r){return r.replace(/^(?:\^[A-Z?]\s*)+/,"")}function Ci(r){if(r<1024)return`${r} B`;if(r<1048576)return`${(r/1024).toFixed(1)} KB`;return`${(r/1048576).toFixed(1)} MB`}function Mi(r){if(r==="~")return pn();return r.startsWith("~/")?be(pn(),r.slice(2)):r}var Pi="workspace";function Ui(r,i=[]){let o=be(r),a=be(o,Pi);return{primary:Ni(a)?a:o,extra:i.map((u)=>jn(u)?be(u):be(o,u))}}function Fi(r,i){if(r===i)return!0;let o=Li(i,r);return o!==""&&!o.startsWith(`..${ji}`)&&o!==".."&&!jn(o)}function Pn(r){return[r.primary,...r.extra]}function Di(r,i){return Pn(i).some((o)=>Fi(r,o))}function Ki(r,i){let o=r.extra.length===0?"":` Also writable: ${r.extra.join(", ")}.`;if(i==="read")return` Relative paths are resolved against ${r.primary}. Reading elsewhere is allowed — give an absolute path for it.`;if(i==="write")return` You work in ${r.primary}. A relative path lands there, and that is where anything you create belongs unless the person names somewhere else. Writing anywhere else is refused.${o}`;return` Every command starts in ${r.primary}, and that is where anything you create belongs unless the person names somewhere else. Nothing stops a command from leaving it, so this one is on you: use a relative path, and do not reach for ~ or an absolute path outside it on your own initiative.${o}`}function ht(r,i,o,a=r.mutating?"write":"read"){let u={...r.parameters.properties};for(let h of o){let g=u[h];if(g===void 0)continue;u[h]={...g,description:`${g.description??""}${Ki(i,a)}`}}return{...r,parameters:{...r.parameters,properties:u}}}var oe=new Map,Gi=8;function qi(){return[...oe.entries()].map(([r,i])=>({pid:r,...i})).sort((r,i)=>i.since-r.since)}function Ji(){let r=[];for(let[i,o]of oe)try{process.kill(-i,"SIGTERM"),r.push(`${i} (${o.command})`)}catch{}return oe.clear(),r}function Vi(){for(let r of[...oe.keys()])try{process.kill(r,0)}catch{oe.delete(r)}}var Yi=250,gn=2000,Xi=new Set(["sleep","git","ssh","scp","sudo","su","doas"]);function zi(r){for(let i of r.split(/\s+/)){if(/^[A-Za-z_]\w*=/.test(i))continue;return i.replace(/^.*\//,"").toLowerCase()}return""}function Zi(r){let i=no(r);if(i.length===0)return!1;return i.every((o)=>!Xi.has(zi(o)))}function Un(r){return`'${r.replaceAll("'","'\\''")}'`}function Qi(r,i){return[r,"__code=$?",`{ printf '%s\\n' "$__code"; pwd; } > ${Un(i)} 2>/dev/null`,"exit $__code"].join(`
17
+ `)}function eo(r,i,o=process.platform){if(!i)return{file:"/bin/sh",args:["-c",r],env:{}};if(o==="linux")return{file:"script",args:["-qec",`/bin/sh -c ${Un(r)}`,"/dev/null"],env:{SHELL:"/bin/sh"}};return{file:"script",args:["-q","/dev/null","/bin/sh","-c",r],env:{SHELL:"/bin/sh"}}}function je(r,i){let o=r.pid;if(o===void 0)return;try{process.kill(-o,i)}catch{}}async function to(r){try{let[i,o]=(await Wi(r,"utf8")).split(`
18
+ `),a=Number.parseInt(i??"",10),u=o?.trim();return{...Number.isNaN(a)?{}:{code:a},...u===void 0||u===""?{}:{cwd:u}}}catch{return{}}}async function Fn(r){if(Vi(),oe.size>=Gi)throw fi(qi().map((S)=>S.command));let i=Qi(r.command,r.statusPath),{file:o,args:a,env:u}=eo(i,r.pty),h=await Hi(r.outPath,"w"),g;try{g=Bi(o,a,{cwd:r.cwd,env:{...r.env,...u},stdio:["ignore",h.fd,h.fd],detached:!0})}catch(S){throw await h.close(),ln(r.command,String(S))}let w=await new Promise((S,T)=>{let L=!1,_=!1,I=setTimeout(j,r.background?Yi:r.timeoutMs),M=(P)=>{if(L)return;L=!0,clearTimeout(I),r.signal.removeEventListener("abort",F),S(P)};function j(){if(r.background||Zi(r.command)){if(g.unref(),g.pid!==void 0)oe.set(g.pid,{command:r.command,since:Date.now(),outPath:r.outPath});M({ending:"backgrounded",...g.pid===void 0?{}:{pid:g.pid}});return}_=!0,je(g,"SIGTERM"),setTimeout(()=>je(g,"SIGKILL"),gn).unref?.()}function F(){je(g,"SIGTERM"),setTimeout(()=>je(g,"SIGKILL"),gn).unref?.()}r.signal.addEventListener("abort",F,{once:!0}),g.on("error",(P)=>{if(L)return;L=!0,clearTimeout(I),r.signal.removeEventListener("abort",F),T(r.pty&&ro(P)?ti(process.platform,String(P)):ln(r.command,String(P)))}),g.on("exit",(P,de)=>{M({ending:_?"killed":"finished",...P===null?{}:{code:P},...de===null?{}:{killedBy:de},...g.pid===void 0?{}:{pid:g.pid}})})}).finally(()=>h.close()),v=await to(r.statusPath);return{...w,...v.code===void 0?{}:{code:v.code},...v.cwd===void 0?{}:{cwdAfter:v.cwd}}}function ro(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}var dt=120000,Dn=600000,so=5000,io={slug:"exec",provider:W,summary:"Runs a shell command on this computer and returns what it printed.",whenToUse:"you need to do something on this machine that no other tool covers — run a build or a test suite, use a command-line program, inspect what is running, or move and archive files in bulk",whenNotToUse:"reading one file, writing one file, or finding files by name or content — use file_read, file_write, glob and grep instead. They are more reliable and their targets can be checked against the permission rules; a path buried in a shell string cannot be",mutating:!0,trust:"untrusted",policyArg:"command",tags:["write","system","shell"],parameters:{type:"object",properties:{command:{type:"string",description:"The command, exactly as it would be typed at a shell prompt. Set environment variables inline (VAR=value command) rather than expecting them to survive from an earlier call."},workdir:{type:"string",description:"Directory to run in. Relative paths are resolved against wherever the previous command ended up. Defaults to that directory, so a cd carries over."},timeoutMs:{type:"integer",description:`How long to wait, in milliseconds. Default ${dt}, maximum ${Dn}.`,default:dt},pty:{type:"boolean",description:"Give the command a terminal. Needed only by programs that behave differently without one, such as those that ask for a password or draw a progress display.",default:!1},background:{type:"boolean",description:"Start it and return immediately instead of waiting. Use for something long-running like a dev server; the output keeps accumulating in a file whose path is reported.",default:!1}},required:["command"]}};function oo(r,i){let o=r===void 0||r<=0?dt:r,a=Math.min(o,Dn),u=i-so;return Math.max(1,Math.min(a,u>0?u:Math.floor(i*0.8)))}function yn(r){return typeof r==="number"&&Number.isFinite(r)?r:void 0}function ao(r,i){let o=ut();return{out:ct(o,`${r.turnId}-${i}.log`),status:ct(o,`${r.turnId}-${i}.status`)}}function uo(r){return async(i,o)=>{let a=typeof i.command==="string"?i.command.trim():"";if(a==="")throw Qs();let u=r.sessions.lastCwd(o.sessionKey),h=u??r.roots.primary,g=typeof i.workdir==="string"?i.workdir.trim():"",w=g===""?h:Ri(g)?g:ct(h,g),v;try{if(v=await Ei(w),!(await Ti(v)).isDirectory())throw Error("not a directory")}catch{let P=g===""&&u!==void 0;if(P)r.sessions.forget(o.sessionKey);throw ei(w,P)}let S=oo(yn(i.timeoutMs),o.deadlineMs),T=yn(i.timeoutMs)!==void 0&&S<Number(i.timeoutMs),L=i.background===!0,_=ut();await _i(_,{recursive:!0});let I=ao(o,ho(a,o.turnId)),M=await Fn({command:a,cwd:v,env:r.env,timeoutMs:S,pty:i.pty===!0,background:L,signal:o.signal,outPath:I.out,statusPath:I.status});if(M.cwdAfter!==void 0)r.sessions.remember(o.sessionKey,M.cwdAfter);let j=await Nn(I.out),F=i.pty===!0?{...j,head:Ii(j.head)}:j;if(await fn(I.status,{force:!0}),!F.spilled&&M.ending!=="backgrounded")await fn(I.out,{force:!0});return fo({command:a,cwd:v,run:M,observation:F,clamped:T,timeoutMs:S,path:I.out})}}function ho(r,i){let o=2166136261;for(let a of[r,i])for(let u=0;u<a.length;u+=1)o^=a.charCodeAt(u),o=Math.imul(o,16777619);return(o>>>0).toString(16).padStart(8,"0")}function fo(r){let i=[];if(r.clamped)i.push(`The requested timeout was longer than allowed, so this ran with ${r.timeoutMs} ms.`);if(r.run.ending==="backgrounded")return i.push(`Still running${r.run.pid===void 0?"":` as process ${r.run.pid}`}. It was left alone rather than stopped, and keeps writing to ${r.path}; read that file to see how far it has got. Nothing here is its final result.`),[...i,ot("Output so far",r.observation.head)].join(`
19
+
20
+ `);if(r.run.ending==="killed")i.push(`Stopped after ${r.timeoutMs} ms without finishing, and everything it started was stopped with it. Whatever it had already done still happened.`);else if(r.run.code!==void 0&&r.run.code!==0)i.push(`Failed with exit code ${r.run.code}.`);else if(r.run.killedBy!==void 0)i.push(`Ended on signal ${r.run.killedBy}.`);if(r.run.cwdAfter!==void 0&&r.run.cwdAfter!==r.cwd)i.push(`The working directory is now ${r.run.cwdAfter}, and the next exec call starts there.`);let o=r.run.ending==="killed"||(r.run.code??0)!==0,a=[];if(r.observation.spilled){if(i.push(`Output was ${Ci(r.observation.bytes)}, too much to include. All of it is in ${r.path}; what follows is the ${o?"start and end":"start"}.`),a.push(ot("First part of the output",r.observation.head)),o)a.push(ot("End of the output",r.observation.tail))}else if(r.observation.head.trim()!=="")a.push(r.observation.head.trimEnd());else if(i.length===0)return"The command finished successfully and printed nothing.";return[...i,...a].join(`
21
+
22
+ `)}function ot(r,i){return`${r}:
23
+ ${i.trimEnd()}`}function mo(r){return{spec:ht(io,r.roots,["command","workdir"],"shell"),handler:uo(r)}}var ko=["agent.yaml","agent.yml","SOUL.md","SOUL.compact.md","AGENTS.md","POLICY.md","REMINDER.md"],$o=[".ssh",".aws",".kube",".gnupg",".docker"],So=/^(?:\.env(\..+)?|\.netrc|\.npmrc|\.pypirc|id_[a-z0-9]+|.*\.pem|.*\.key)$/i;function _o(r){return r.split(Wn).filter((i)=>i!=="")}function Eo(r,i){let o=_o(r),a=o[o.length-1]??"";for(let w of $o)if(o.includes(w))return`${w}/ holds credentials, and nothing under it is writable by an agent`;if(So.test(a))return`${a} holds secrets — the manifest names environment variables, and their values are not the agent's to edit`;let u=vo(i.agentDir),h=bo(u,r);if(h!==""&&!h.startsWith("..")&&!wo(h)){let w=h.split(Wn),v=w[w.length-1]??"";if(ko.includes(v))return`${h} is part of this agent's own definition — who it is, what it does, or what it is permitted to do — and it is not editable from inside a turn`;if(w[0]?.startsWith(".")===!0)return`${h} is runtime state this agent depends on`}for(let w of i.extra??[])if(r.includes(w)||a===w)return`${a} is listed in tools.providerConfig.protect`;return}var bn=2000000,lt=400;function To(r){return r.subarray(0,8000).includes(0)}var Ro={slug:"file_read",provider:W,summary:"Reads a file and returns its contents.",whenToUse:"you need to see what is in a file — its code, its configuration, its text — before answering about it or changing it",whenNotToUse:"you are looking for which files exist or which ones mention something; that is glob and grep. Never read a file by running cat through the shell",mutating:!1,trust:"untrusted",policyArg:"path",tags:["read","file"],parameters:{type:"object",properties:{path:{type:"string",description:"The file, absolute or relative to the current working directory."},offset:{type:"integer",description:"First line to return, counting from 1. Use for a long file."},limit:{type:"integer",description:`How many lines to return. Defaults to ${lt}.`,default:lt}},required:["path"]}},Ao={slug:"file_write",provider:W,summary:"Writes a file, creating any folders it needs, and replaces it if it already exists.",whenToUse:"you are creating a new file, or replacing one whose whole contents you are producing. Folders in the path are created for you, so this needs no separate step and no shell",whenNotToUse:"you are changing part of an existing file — that is file_edit, which cannot silently destroy the rest of it",mutating:!0,trust:"trusted",trustReason:"It reports what it wrote — the path, the line count — and never any of the content, so nothing from the file reaches the model through it.",policyArg:"path",tags:["write","file"],parameters:{type:"object",properties:{path:{type:"string",description:"The file, absolute or relative to the current working directory."},content:{type:"string",description:"The complete new contents."}},required:["path","content"]}},xo={slug:"file_edit",provider:W,summary:"Replaces an exact piece of text in a file, leaving the rest untouched.",whenToUse:"you are changing part of a file you have already read — a line, a block, a value — and everything else should stay as it is",whenNotToUse:"you have not read the file in this conversation, or you are writing the whole thing; guessing at text that is already there fails rather than damaging the file, but it still wastes the step",mutating:!0,trust:"trusted",trustReason:"It reports which occurrence changed and how long the file now is, never the text on either side of the change.",policyArg:"path",tags:["write","file"],parameters:{type:"object",properties:{path:{type:"string",description:"The file, absolute or relative to the current working directory."},find:{type:"string",description:"The exact text to replace, copied from the file including its indentation. It must appear exactly once unless all is true."},replace:{type:"string",description:"What to put in its place."},all:{type:"boolean",description:"Replace every occurrence instead of requiring exactly one.",default:!1}},required:["path","find","replace"]}};function Me(r,i,o,a){let u=Mi(typeof r==="string"?r.trim():"");if(u==="")throw ni();let h=i.lastCwd(o)??a;return yo(u)?wn(u):wn(h,u)}function Gn(r,i){if(!Di(r,i.roots))throw di(r,Pn(i.roots));let o=Eo(r,{agentDir:i.agentDir,...i.protect===void 0?{}:{extra:i.protect}});if(o!==void 0)throw ii(r,o)}function vn(r){return typeof r==="number"&&Number.isFinite(r)?r:void 0}function Oo(r){return async(i,o)=>{let a=Me(i.path,r.sessions,o.sessionKey,r.roots.primary),u;try{u=(await Bn(a)).size}catch{throw An(a)}if(u>bn)throw ri(a,u,bn);let h=await Kn(a);if(To(h))throw si(a,u);let w=xe(h.toString("utf8")).split(`
24
+ `),v=Math.max(1,vn(i.offset)??1),S=Math.max(1,vn(i.limit)??lt),T=w.slice(v-1,v-1+S);if(T.length===0)return`${a} has ${w.length} lines, so there is nothing at line ${v}.`;let L=T.join(`
25
+ `),_=v-1+T.length;if(v===1&&_>=w.length)return L;return`Lines ${v}-${_} of ${w.length} in ${a}:
26
+ ${L}`}}function Io(r){return async(i,o)=>{let a=Me(i.path,r.sessions,o.sessionKey,r.roots.primary);Gn(a,r);let u=typeof i.content==="string"?i.content:String(i.content??""),h=await Bn(a).then(()=>!0,()=>!1);await po(go(a),{recursive:!0}),await Hn(a,u,"utf8");let g=u===""?0:u.split(`
27
+ `).length;return`${h?"Replaced":"Created"} ${a} — ${g} line${g===1?"":"s"}, ${u.length} characters.`}}function Co(r){return async(i,o)=>{let a=Me(i.path,r.sessions,o.sessionKey,r.roots.primary);Gn(a,r);let u=typeof i.find==="string"?i.find:"",h=typeof i.replace==="string"?i.replace:"",g;try{g=await Kn(a,"utf8")}catch{throw An(a)}let w=u===""?0:g.split(u).length-1;if(w===0)throw oi(a,u);if(w>1&&i.all!==!0)throw ai(a,w);let v=i.all===!0?g.split(u).join(h):g.replace(u,h);await Hn(a,v,"utf8");let S=i.all===!0?w:1;return`Edited ${a} — replaced ${S} occurrence${S===1?"":"s"}. The file is now ${v.split(`
28
+ `).length} lines.`}}function No(r){let i=(o)=>ht(o,r.roots,["path"]);return[{spec:i(Ro),handler:Oo(r)},{spec:i(Ao),handler:Io(r)},{spec:i(xo),handler:Co(r)}]}var Uo=new Set(["node_modules",".git",".hg",".svn","dist","build","out",".next",".turbo",".cache","coverage","__pycache__",".venv","venv","target","vendor"]);function qn(r){let i="";for(let o=0;o<r.length;o+=1){let a=r[o]??"";if(a==="*"){if(r[o+1]==="*"){if(r[o+2]==="/"){i+="(?:.*/)?",o+=2;continue}i+=".*",o+=1;continue}i+="[^/]*";continue}if(a==="?"){i+="[^/]";continue}i+=a.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${i}$`)}function Fo(r){return kn==="/"?r:r.split(kn).join("/")}async function Vn(r,i){let o=[],a=[r];while(a.length>0){let u=a.shift();if(u===void 0)break;let h;try{h=await jo(u,{withFileTypes:!0})}catch{continue}for(let g of h){let w=Mo(u,g.name);if(g.isDirectory()){if(Uo.has(g.name))continue;if(i.hidden!==!0&&g.name.startsWith("."))continue;a.push(w);continue}if(!g.isFile())continue;if(i.hidden!==!0&&g.name.startsWith("."))continue;let v=Fo(Po(r,w));if(i.accept!==void 0&&!i.accept(v))continue;if(o.length>=i.limit)return{files:o,truncated:!0};o.push(v)}}return{files:o,truncated:!1}}var $n=200,Sn=100,Do=1e6,Ko={slug:"glob",provider:W,summary:"Finds files whose path matches a pattern.",whenToUse:"you need to know which files exist, or where a file is, when you know something about its name — every test file, every yaml, anything under a directory",whenNotToUse:"you know what a file is called and want to see it, which is file_read; or you are searching for text inside files, which is grep",mutating:!1,trust:"untrusted",policyArg:"pattern",tags:["read","file","search"],parameters:{type:"object",properties:{pattern:{type:"string",description:"A path pattern. * matches within one directory, ** matches across directories — for example **/*.test.ts or src/**/index.*"},path:{type:"string",description:"Directory to search under. Defaults to the current directory."},hidden:{type:"boolean",description:"Include files and directories whose name begins with a dot.",default:!1}},required:["pattern"]}},Bo={slug:"grep",provider:W,summary:"Finds lines in files that match a regular expression.",whenToUse:"you need to find where something is written — a function name, a setting, a phrase — without knowing which file it is in",whenNotToUse:"you are looking for files by name, which is glob; or you already know the file, in which case read it. Never run grep or rg through the shell",mutating:!1,trust:"untrusted",policyArg:"pattern",tags:["read","file","search"],parameters:{type:"object",properties:{pattern:{type:"string",description:"A regular expression, matched against each line."},path:{type:"string",description:"Directory to search under. Defaults to the current directory."},glob:{type:"string",description:"Only search files whose path matches this, for example **/*.ts. Searches everything if omitted."},ignoreCase:{type:"boolean",description:"Match regardless of case.",default:!1}},required:["pattern"]}};function Yn(r,i,o){let a=typeof r.path==="string"&&r.path.trim()!==""?r.path:".";return Me(a,i.sessions,o,i.roots.primary)}function Ho(r){return async(i,o)=>{let a=typeof i.pattern==="string"?i.pattern.trim():"",u=Yn(i,r,o.sessionKey),h=qn(a),g=await Vn(u,{limit:$n,...i.hidden===!0?{hidden:!0}:{},accept:(v)=>h.test(v)});if(g.files.length===0)return`No file under ${u} matches ${a}. Directories like node_modules, .git and dist are never searched${i.hidden===!0?"":", and dot-files are skipped unless hidden is true"}.`;return`${g.truncated?`The first ${g.files.length} of more than ${$n} matches for ${a} under ${u} — narrow the pattern to see the rest:`:`${g.files.length} match${g.files.length===1?"":"es"} for ${a} under ${u}:`}
29
29
  ${g.files.join(`
30
- `)}`}}function Wo(r){return async(i,o)=>{let a=typeof i.pattern==="string"?i.pattern:"",u=qn(i,r,o.sessionKey),h;try{h=new RegExp(a,i.ignoreCase===!0?"i":"")}catch(_){throw di(a,String(_))}let g=typeof i.glob==="string"&&i.glob.trim()!==""?Wn(i.glob.trim()):void 0,w=await Gn(u,{limit:5000,...g===void 0?{}:{accept:(_)=>g.test(_)}}),k=[],S=0,T=!1;for(let _ of w.files){if(k.length>=$n){T=!0;break}let R;try{let L=await Lo(`${u}/${_}`);if(L.length>Do||L.subarray(0,8000).includes(0))continue;R=L.toString("utf8")}catch{continue}S+=1;let M=R.split(`
31
- `);for(let L=0;L<M.length;L+=1){let F=M[L]??"";if(!h.test(F))continue;if(k.length>=$n){T=!0;break}let U=F.length>300?`${F.slice(0,300)}…`:F;k.push(`${_}:${L+1}: ${Se(U).trim()}`)}}if(k.length===0)return`Nothing under ${u} matches ${a}${g===void 0?"":` in files matching ${String(i.glob)}`}. ${S} file${S===1?"":"s"} were searched; node_modules, .git, dist and dot-files are skipped.`;return`${T?`The first ${k.length} matches for ${a} under ${u} — there are more, so narrow the pattern or pass a glob:`:`${k.length} match${k.length===1?"":"es"} for ${a} under ${u}, across ${S} file${S===1?"":"s"} searched:`}
32
- ${k.join(`
33
- `)}`}}function Go(r){let i=(o)=>ut(o,r.roots,["path"]);return[{spec:i(Ko),handler:Ho(r)},{spec:i(Bo),handler:Wo(r)}]}class Jn{#e=new Map;lastCwd(r){return this.#e.get(r)}remember(r,i){this.#e.set(r,i)}forget(r){this.#e.delete(r)}}function Sn(r){return r.toLowerCase().replace(/[\s_.-]+/g,"")}class Vn{id=X;#e=new Jn;#t;constructor(r){let i=Fi(r.dir,r.writeRoots??[]),o={sessions:this.#e,agentDir:r.dir,roots:i,...r.protect===void 0?{}:{protect:r.protect}};this.#t=[mo({sessions:this.#e,env:r.env,roots:i}),...No(o),...Go({sessions:this.#e,roots:i}),..._i({agentDir:r.dir})]}available(){return Promise.resolve(this.#t.map((r)=>({slug:r.spec.slug,summary:r.spec.summary})))}resolve(r){let i=new Set(r.map(Sn));return Promise.resolve(this.#t.filter((o)=>i.has(Sn(o.spec.slug))))}stop(){return Promise.resolve(Vi())}list(){return Promise.resolve(this.#t.map((r)=>r.spec.slug))}}var _n=["protect","writeRoots"];function ht(r){let i=Object.keys(r.config).filter((u)=>!_n.includes(u));if(i.length>0)throw new y({code:"system_config_unknown",message:`tools.providerConfig has ${i.length===1?"a key":"keys"} the system provider does not read: ${i.join(", ")}.`,hint:`Accepted keys are ${_n.join(", ")} — extra paths the file tools refuse to write, and extra directories they may write. Refused rather than ignored, because a protection that looks applied and is not is worse than a rejected manifest.`,field:"tools.providerConfig"});let o=r.config.protect,a=r.config.writeRoots;return new Vn({env:r.env,dir:r.dir,...Array.isArray(o)?{protect:o.map((u)=>String(u))}:{},...Array.isArray(a)?{writeRoots:a.map((u)=>String(u))}:{}})}function Yo(r){return`'${r.replaceAll("'","'\\''")}'`}class Pe{#e;constructor(r){this.#e=r.env}has(r){let i=this.#e.PATH??process.env.PATH??"";for(let o of i.split(Vo)){if(o==="")continue;try{let a=qo(ot(o,r));if(a.isFile()&&(a.mode&73)!==0)return!0}catch{}}return!1}async run(r){let i=lt();await Jo(i,{recursive:!0});let o=Xo([r.command,...r.args].join(" ")),a=ot(i,`skill-${o}.out`),u=ot(i,`skill-${o}.status`),h=[r.command,...r.args].map(Yo).join(" "),g=await Mn({command:h,cwd:r.cwd,env:this.#e,timeoutMs:r.timeoutMs,pty:!1,background:!1,signal:r.signal,outPath:a,statusPath:u}),w=await Cn(a);if(await En(u,{force:!0}),!w.spilled&&g.ending!=="backgrounded")await En(a,{force:!0});let k=g.ending==="killed"||g.ending==="backgrounded",S=w.spilled?`${w.head}
30
+ `)}`}}function Wo(r){return async(i,o)=>{let a=typeof i.pattern==="string"?i.pattern:"",u=Yn(i,r,o.sessionKey),h;try{h=new RegExp(a,i.ignoreCase===!0?"i":"")}catch(_){throw ci(a,String(_))}let g=typeof i.glob==="string"&&i.glob.trim()!==""?qn(i.glob.trim()):void 0,w=await Vn(u,{limit:5000,...g===void 0?{}:{accept:(_)=>g.test(_)}}),v=[],S=0,T=!1;for(let _ of w.files){if(v.length>=Sn){T=!0;break}let I;try{let j=await Lo(`${u}/${_}`);if(j.length>Do||j.subarray(0,8000).includes(0))continue;I=j.toString("utf8")}catch{continue}S+=1;let M=I.split(`
31
+ `);for(let j=0;j<M.length;j+=1){let F=M[j]??"";if(!h.test(F))continue;if(v.length>=Sn){T=!0;break}let P=F.length>300?`${F.slice(0,300)}…`:F;v.push(`${_}:${j+1}: ${xe(P).trim()}`)}}if(v.length===0)return`Nothing under ${u} matches ${a}${g===void 0?"":` in files matching ${String(i.glob)}`}. ${S} file${S===1?"":"s"} were searched; node_modules, .git, dist and dot-files are skipped.`;return`${T?`The first ${v.length} matches for ${a} under ${u} — there are more, so narrow the pattern or pass a glob:`:`${v.length} match${v.length===1?"":"es"} for ${a} under ${u}, across ${S} file${S===1?"":"s"} searched:`}
32
+ ${v.join(`
33
+ `)}`}}function Go(r){let i=(o)=>ht(o,r.roots,["path"]);return[{spec:i(Ko),handler:Ho(r)},{spec:i(Bo),handler:Wo(r)}]}class Xn{#e=new Map;lastCwd(r){return this.#e.get(r)}remember(r,i){this.#e.set(r,i)}forget(r){this.#e.delete(r)}}function _n(r){return r.toLowerCase().replace(/[\s_.-]+/g,"")}class zn{id=W;#e=new Xn;#t;constructor(r){let i=Ui(r.dir,r.writeRoots??[]),o={sessions:this.#e,agentDir:r.dir,roots:i,...r.protect===void 0?{}:{protect:r.protect}};this.#t=[mo({sessions:this.#e,env:r.env,roots:i}),...No(o),...Go({sessions:this.#e,roots:i}),...Si({agentDir:r.dir})]}available(){return Promise.resolve(this.#t.map((r)=>({slug:r.spec.slug,summary:r.spec.summary})))}resolve(r){let i=new Set(r.map(_n));return Promise.resolve(this.#t.filter((o)=>i.has(_n(o.spec.slug))))}stop(){return Promise.resolve(Ji())}list(){return Promise.resolve(this.#t.map((r)=>r.spec.slug))}}var Tn=["protect","writeRoots"];function ft(r){let i=Object.keys(r.config).filter((u)=>!Tn.includes(u));if(i.length>0)throw new y({code:"system_config_unknown",message:`tools.providerConfig has ${i.length===1?"a key":"keys"} the system provider does not read: ${i.join(", ")}.`,hint:`Accepted keys are ${Tn.join(", ")} — extra paths the file tools refuse to write, and extra directories they may write. Refused rather than ignored, because a protection that looks applied and is not is worse than a rejected manifest.`,field:"tools.providerConfig"});let o=r.config.protect,a=r.config.writeRoots;return new zn({env:r.env,dir:r.dir,...Array.isArray(o)?{protect:o.map((u)=>String(u))}:{},...Array.isArray(a)?{writeRoots:a.map((u)=>String(u))}:{}})}function Yo(r){return`'${r.replaceAll("'","'\\''")}'`}class Pe{#e;constructor(r){this.#e=r.env}has(r){let i=this.#e.PATH??process.env.PATH??"";for(let o of i.split(Vo)){if(o==="")continue;try{let a=qo(at(o,r));if(a.isFile()&&(a.mode&73)!==0)return!0}catch{}}return!1}async run(r){let i=ut();await Jo(i,{recursive:!0});let o=Xo([r.command,...r.args].join(" ")),a=at(i,`skill-${o}.out`),u=at(i,`skill-${o}.status`),h=[r.command,...r.args].map(Yo).join(" "),g=await Fn({command:h,cwd:r.cwd,env:this.#e,timeoutMs:r.timeoutMs,pty:!1,background:!1,signal:r.signal,outPath:a,statusPath:u}),w=await Nn(a);if(await Rn(u,{force:!0}),!w.spilled&&g.ending!=="backgrounded")await Rn(a,{force:!0});let v=g.ending==="killed"||g.ending==="backgrounded",S=w.spilled?`${w.head}
34
34
 
35
35
  … ${w.bytes} bytes in total; the rest is at ${a}
36
36
 
37
37
  ${w.tail}`:w.head;return{ok:g.ending==="finished"&&g.code===0,output:g.ending==="backgrounded"?`${S}
38
38
 
39
- Still running past ${r.timeoutMs} ms, left going rather than discarded. Output continues to accumulate at ${a}.`:S,...g.code===void 0?{}:{code:g.code},timedOut:k}}}function Xo(r){let i=2166136261;for(let o=0;o<r.length;o+=1)i^=r.charCodeAt(o),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")}var zo="0.1.0",Yn={name:"system",version:zo,dispachApi:"^0.1",permissions:[{kind:"exec",commands:["*"]},{kind:"fs",paths:["<workspace>"],mode:"write"}],setup(r){r.defineToolProvider("system",ht),r.defineScriptRunner(new Pe({env:r.env}))}};import{lookup as ga}from"node:dns/promises";function Xn(r,i){return new f({code:"web_url_unparseable",message:`That is not a URL: ${JSON.stringify(r)}`,hint:`${i}. Give a complete absolute URL including the scheme — https://example.com/page, not example.com/page. Parsed with the standard URL parser rather than a pattern, so what is accepted here is exactly what a browser would accept.`,field:"url"})}function Zo(r){return new f({code:"web_scheme_refused",message:`${r} URLs are not fetchable.`,hint:"Only http and https. This tool reaches the public web and nothing else — a file:// URL reads the disk, which is file_read's job and subject to its rules, and the other schemes reach services that were never designed to be spoken to by an HTTP client.",field:"url"})}function Qo(){return new f({code:"web_credentials_refused",message:"That URL carries a username and password.",hint:"Refused rather than stripped: a URL with credentials in it is either a secret that should not be in a conversation, or an attempt to make the host look like something it is not. Fetch the address on its own if the page is public.",field:"url"})}function ft(r,i,o,a,u){let h=i===r?i:`${r} → ${i}`;return new f({code:"web_address_refused",message:`${h} is ${o}${a===void 0?"":` (${a})`} and will not be fetched${u>0?`, reached by redirect ${u}`:""}.`,hint:"This is a standing rule with no setting that overrides it. Addresses off the public internet — loopback, link-local, private and carrier-grade NAT ranges — include the cloud metadata endpoint and every service on this machine, so a page that can make this tool fetch one is a page that can read them. Nothing was requested. If the page is genuinely public, check the hostname.",field:"url"})}function Ue(r,i){return new f({code:"web_host_refused",message:`${r} is not a public hostname: ${i}.`,hint:"Nothing was requested. This tool reaches the public web; names that only resolve inside this machine or this network are refused before any lookup happens.",field:"url"})}function zn(r,i){return new f({code:"web_host_unresolvable",message:`${r} could not be resolved: ${i}`,hint:"Refused rather than handed to the HTTP client anyway. The address check happens on what DNS returns, so a name that will not resolve here cannot be checked — and fetching it regardless would mean the one request nobody looked at is the one that failed the lookup. Check the spelling of the host.",field:"url"})}function Qn(r,i){return new f({code:"web_request_failed",message:`The request to ${r} did not complete: ${i}`,hint:"The address passed every check, so this is the network or the far end rather than a refusal. Worth one retry if it reads like a timeout; not worth retrying if the host is simply gone.",field:"url"})}function ea(r,i,o){return new f({code:"web_status_failed",message:`${r} answered ${i}${o===""?"":` ${o}`}.`,hint:`${i===404?"The page is not there — check the URL against a search result rather than guessing at the path.":i===403||i===401?"The page requires credentials or refuses automated clients. There is no setting that supplies either; treat the page as unavailable and say so.":"A server-side failure. One retry is reasonable; a second is not."}`,field:"url"})}function er(r,i){return new f({code:"web_too_many_redirects",message:`${r} redirected more than ${i} times.`,hint:"Followed manually and re-checked at every hop, which is why the count is low — a redirect chain is the standard way to get a checked URL to end up somewhere unchecked. A chain this long is a redirect loop or a tracker, not a page.",field:"url"})}function ta(r,i){return new f({code:"web_content_unusable",message:`${r} returned ${i}, which has no text to extract.`,hint:"Refused rather than decoded: a binary rendered as text is thousands of meaningless tokens and no information. This tool reads HTML, plain text, JSON and similar. PDF and image extraction are deliberately not in scope.",field:"url"})}function na(r,i){return new y({code:"web_search_key_missing",message:`The ${r} search backend needs ${i} and it is not set.`,hint:`Set ${i} in the .env beside agent.yaml, or in the environment. The manifest names the variable and never holds the key — a manifest with a literal key fails validation.`,field:"tools.providers.web.apiKeyEnv"})}function ra(r,i,o){return new f({code:"web_search_failed",message:`${r} answered ${i}: ${o}`,hint:`${i===401||i===403?"The API key was rejected. Check the value of the variable named in tools.providers.web.apiKeyEnv — the manifest holds the name, the .env holds the key.":i===429?"Rate limited. This is the backend's own quota; nothing in the manifest raises it.":"A failure at the search backend rather than in the query."}`})}function mt(r,i){return new y({code:"web_config_invalid",message:`tools.providers.web.${r} ${i}`,hint:"Refused rather than defaulted around: a search backend silently different from the one configured returns different results with nothing reporting why.",field:`tools.providers.web.${r}`})}var tr=["tavily","brave","exa"];function D(r,i){return typeof r==="object"&&r!==null?r[i]:void 0}function z(r){return typeof r==="string"?r:""}function wt(r){return Array.isArray(r)?r:[]}var sa={id:"tavily",defaultKeyEnv:"TAVILY_API_KEY",request(r,i,o){return{url:"https://api.tavily.com/search",init:{method:"POST",headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify({query:r,max_results:i,search_depth:"basic",include_answer:!1})}}},read(r){return wt(D(r,"results")).map((i)=>({title:z(D(i,"title")),url:z(D(i,"url")),snippet:z(D(i,"content"))}))}},ia={id:"brave",defaultKeyEnv:"BRAVE_API_KEY",request(r,i,o){let a=new URL("https://api.search.brave.com/res/v1/web/search");return a.searchParams.set("q",r),a.searchParams.set("count",String(i)),{url:a.href,init:{method:"GET",headers:{accept:"application/json","x-subscription-token":o}}}},read(r){return wt(D(D(r,"web"),"results")).map((i)=>({title:z(D(i,"title")),url:z(D(i,"url")),snippet:z(D(i,"description"))}))}},oa={id:"exa",defaultKeyEnv:"EXA_API_KEY",request(r,i,o){return{url:"https://api.exa.ai/search",init:{method:"POST",headers:{"x-api-key":o,"content-type":"application/json"},body:JSON.stringify({query:r,numResults:i,contents:{text:{maxCharacters:400}}})}}},read(r){return wt(D(r,"results")).map((i)=>({title:z(D(i,"title")),url:z(D(i,"url")),snippet:z(D(i,"text"))||z(D(i,"snippet"))}))}},aa={tavily:sa,brave:ia,exa:oa};function ir(r){return aa[r]}async function ca(r,i){let o=i.statusText;try{let a=await i.text();if(a!=="")o=a.length>300?`${a.slice(0,300)}…`:a}catch{}throw ra(r,i.status,o)}var da=["script","style","noscript","template","svg","canvas","iframe","head"],la=/<\/?(?:p|div|br|hr|section|article|header|footer|nav|aside|main|h[1-6]|li|tr|td|th|blockquote|pre|figcaption|dt|dd)\b[^>]*>/gi,ua={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",hellip:"…",mdash:"—",ndash:"–",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",times:"×",middot:"·",bull:"•",copy:"©",reg:"®",trade:"™",deg:"°",eacute:"é",egrave:"è",agrave:"à",ccedil:"ç",uuml:"ü",ouml:"ö",auml:"ä"};function or(r){return r.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]{1,31});/g,(i,o)=>{if(o.startsWith("#")){let a=o.startsWith("#x")||o.startsWith("#X")?Number.parseInt(o.slice(2),16):Number.parseInt(o.slice(1),10);if(!Number.isFinite(a)||a<0||a>1114111)return i;if(a>=55296&&a<=57343)return i;return String.fromCodePoint(a)}return ua[o.toLowerCase()]??i})}function ha(r){let i=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(r);if(i===null)return;let o=dr(or(i[1]??""));return o===""?void 0:o}function fa(r){let i=r;for(let o of da)i=i.replace(new RegExp(`<${o}\\b[^>]*>[\\s\\S]*?</${o}>`,"gi")," "),i=i.replace(new RegExp(`<${o}\\b[^>]*>[\\s\\S]*$`,"i")," ");return i=i.replace(/<!--[\s\S]*?-->/g," "),i=i.replace(la,`
40
- `),i=i.replace(/<[^>]*>/g," "),i=or(i),i.split(`
39
+ Still running past ${r.timeoutMs} ms, left going rather than discarded. Output continues to accumulate at ${a}.`:S,...g.code===void 0?{}:{code:g.code},timedOut:v}}}function Xo(r){let i=2166136261;for(let o=0;o<r.length;o+=1)i^=r.charCodeAt(o),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")}var zo="0.1.0",Zn={name:"system",version:zo,dispachApi:"^0.1",permissions:[{kind:"exec",commands:["*"]},{kind:"fs",paths:["<workspace>"],mode:"write"}],setup(r){r.defineToolProvider("system",ft),r.defineScriptRunner(new Pe({env:r.env}))}};import{lookup as ga}from"node:dns/promises";function Qn(r,i){return new f({code:"web_url_unparseable",message:`That is not a URL: ${JSON.stringify(r)}`,hint:`${i}. Give a complete absolute URL including the scheme — https://example.com/page, not example.com/page. Parsed with the standard URL parser rather than a pattern, so what is accepted here is exactly what a browser would accept.`,field:"url"})}function Zo(r){return new f({code:"web_scheme_refused",message:`${r} URLs are not fetchable.`,hint:"Only http and https. This tool reaches the public web and nothing else — a file:// URL reads the disk, which is file_read's job and subject to its rules, and the other schemes reach services that were never designed to be spoken to by an HTTP client.",field:"url"})}function Qo(){return new f({code:"web_credentials_refused",message:"That URL carries a username and password.",hint:"Refused rather than stripped: a URL with credentials in it is either a secret that should not be in a conversation, or an attempt to make the host look like something it is not. Fetch the address on its own if the page is public.",field:"url"})}function mt(r,i,o,a,u){let h=i===r?i:`${r} → ${i}`;return new f({code:"web_address_refused",message:`${h} is ${o}${a===void 0?"":` (${a})`} and will not be fetched${u>0?`, reached by redirect ${u}`:""}.`,hint:"This is a standing rule with no setting that overrides it. Addresses off the public internet — loopback, link-local, private and carrier-grade NAT ranges — include the cloud metadata endpoint and every service on this machine, so a page that can make this tool fetch one is a page that can read them. Nothing was requested. If the page is genuinely public, check the hostname.",field:"url"})}function Ue(r,i){return new f({code:"web_host_refused",message:`${r} is not a public hostname: ${i}.`,hint:"Nothing was requested. This tool reaches the public web; names that only resolve inside this machine or this network are refused before any lookup happens.",field:"url"})}function er(r,i){return new f({code:"web_host_unresolvable",message:`${r} could not be resolved: ${i}`,hint:"Refused rather than handed to the HTTP client anyway. The address check happens on what DNS returns, so a name that will not resolve here cannot be checked — and fetching it regardless would mean the one request nobody looked at is the one that failed the lookup. Check the spelling of the host.",field:"url"})}function tr(r,i){return new f({code:"web_request_failed",message:`The request to ${r} did not complete: ${i}`,hint:"The address passed every check, so this is the network or the far end rather than a refusal. Worth one retry if it reads like a timeout; not worth retrying if the host is simply gone.",field:"url"})}function ea(r,i,o){return new f({code:"web_status_failed",message:`${r} answered ${i}${o===""?"":` ${o}`}.`,hint:`${i===404?"The page is not there — check the URL against a search result rather than guessing at the path.":i===403||i===401?"The page requires credentials or refuses automated clients. There is no setting that supplies either; treat the page as unavailable and say so.":"A server-side failure. One retry is reasonable; a second is not."}`,field:"url"})}function nr(r,i){return new f({code:"web_too_many_redirects",message:`${r} redirected more than ${i} times.`,hint:"Followed manually and re-checked at every hop, which is why the count is low — a redirect chain is the standard way to get a checked URL to end up somewhere unchecked. A chain this long is a redirect loop or a tracker, not a page.",field:"url"})}function ta(r,i){return new f({code:"web_content_unusable",message:`${r} returned ${i}, which has no text to extract.`,hint:"Refused rather than decoded: a binary rendered as text is thousands of meaningless tokens and no information. This tool reads HTML, plain text, JSON and similar. PDF and image extraction are deliberately not in scope.",field:"url"})}function na(r,i){return new y({code:"web_search_key_missing",message:`The ${r} search backend needs ${i} and it is not set.`,hint:`Set ${i} in the .env beside agent.yaml, or in the environment. The manifest names the variable and never holds the key — a manifest with a literal key fails validation.`,field:"tools.providers.web.apiKeyEnv"})}function ra(r,i,o){return new f({code:"web_search_failed",message:`${r} answered ${i}: ${o}`,hint:`${i===401||i===403?"The API key was rejected. Check the value of the variable named in tools.providers.web.apiKeyEnv — the manifest holds the name, the .env holds the key.":i===429?"Rate limited. This is the backend's own quota; nothing in the manifest raises it.":"A failure at the search backend rather than in the query."}`})}function pt(r,i){return new y({code:"web_config_invalid",message:`tools.providers.web.${r} ${i}`,hint:"Refused rather than defaulted around: a search backend silently different from the one configured returns different results with nothing reporting why.",field:`tools.providers.web.${r}`})}var rr=["tavily","brave","exa"];function D(r,i){return typeof r==="object"&&r!==null?r[i]:void 0}function q(r){return typeof r==="string"?r:""}function bt(r){return Array.isArray(r)?r:[]}var sa={id:"tavily",defaultKeyEnv:"TAVILY_API_KEY",request(r,i,o){return{url:"https://api.tavily.com/search",init:{method:"POST",headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},body:JSON.stringify({query:r,max_results:i,search_depth:"basic",include_answer:!1})}}},read(r){return bt(D(r,"results")).map((i)=>({title:q(D(i,"title")),url:q(D(i,"url")),snippet:q(D(i,"content"))}))}},ia={id:"brave",defaultKeyEnv:"BRAVE_API_KEY",request(r,i,o){let a=new URL("https://api.search.brave.com/res/v1/web/search");return a.searchParams.set("q",r),a.searchParams.set("count",String(i)),{url:a.href,init:{method:"GET",headers:{accept:"application/json","x-subscription-token":o}}}},read(r){return bt(D(D(r,"web"),"results")).map((i)=>({title:q(D(i,"title")),url:q(D(i,"url")),snippet:q(D(i,"description"))}))}},oa={id:"exa",defaultKeyEnv:"EXA_API_KEY",request(r,i,o){return{url:"https://api.exa.ai/search",init:{method:"POST",headers:{"x-api-key":o,"content-type":"application/json"},body:JSON.stringify({query:r,numResults:i,contents:{text:{maxCharacters:400}}})}}},read(r){return bt(D(r,"results")).map((i)=>({title:q(D(i,"title")),url:q(D(i,"url")),snippet:q(D(i,"text"))||q(D(i,"snippet"))}))}},aa={tavily:sa,brave:ia,exa:oa};function ar(r){return aa[r]}async function ca(r,i){let o=i.statusText;try{let a=await i.text();if(a!=="")o=a.length>300?`${a.slice(0,300)}…`:a}catch{}throw ra(r,i.status,o)}var da=["script","style","noscript","template","svg","canvas","iframe","head"],la=/<\/?(?:p|div|br|hr|section|article|header|footer|nav|aside|main|h[1-6]|li|tr|td|th|blockquote|pre|figcaption|dt|dd)\b[^>]*>/gi,ua={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",hellip:"…",mdash:"—",ndash:"–",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",times:"×",middot:"·",bull:"•",copy:"©",reg:"®",trade:"™",deg:"°",eacute:"é",egrave:"è",agrave:"à",ccedil:"ç",uuml:"ü",ouml:"ö",auml:"ä"};function cr(r){return r.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]{1,31});/g,(i,o)=>{if(o.startsWith("#")){let a=o.startsWith("#x")||o.startsWith("#X")?Number.parseInt(o.slice(2),16):Number.parseInt(o.slice(1),10);if(!Number.isFinite(a)||a<0||a>1114111)return i;if(a>=55296&&a<=57343)return i;return String.fromCodePoint(a)}return ua[o.toLowerCase()]??i})}function ha(r){let i=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(r);if(i===null)return;let o=dr(cr(i[1]??""));return o===""?void 0:o}function fa(r){let i=r;for(let o of da)i=i.replace(new RegExp(`<${o}\\b[^>]*>[\\s\\S]*?</${o}>`,"gi")," "),i=i.replace(new RegExp(`<${o}\\b[^>]*>[\\s\\S]*$`,"i")," ");return i=i.replace(/<!--[\s\S]*?-->/g," "),i=i.replace(la,`
40
+ `),i=i.replace(/<[^>]*>/g," "),i=cr(i),i.split(`
41
41
  `).map((o)=>dr(o)).filter((o,a,u)=>o!==""||(u[a-1]??"")!=="").join(`
42
- `).trim()}function dr(r){return r.replace(/\s+/g," ").trim()}function ma(r,i){let o=i.split(";")[0]?.trim().toLowerCase()??"";if(o.includes("html")||o.includes("xml")){let a=ha(r);return{text:fa(r),...a===void 0?{}:{title:a}}}return{text:r.trim()}}function pa(r){let i=r.split(";")[0]?.trim().toLowerCase()??"";if(i==="")return!0;if(i.startsWith("text/"))return!0;return/^application\/(?:json|xml|xhtml\+xml|ld\+json|rss\+xml|atom\+xml|javascript|x-ndjson)$/.test(i)}var ur={kind:"public"};function hr(r){let i=r.split(".");if(i.length!==4)return;let o=[];for(let a of i){if(a.length===0||a.length>3||!/^[0-9]+$/.test(a))return;if(a.length>1&&a.startsWith("0"))return;let u=Number(a);if(u>255)return;o.push(u)}return o}function ya(r){let i=r.split("%")[0]??"";if(i==="")return;if(!/^[0-9a-fA-F:.]+$/.test(i))return;let o=i.split("::");if(o.length>2)return;let a=(w)=>{if(w==="")return[];let k=w.split(":"),S=[];for(let T=0;T<k.length;T+=1){let N=k[T]??"";if(N.includes(".")){if(T!==k.length-1)return;let R=hr(N);if(R===void 0)return;S.push(...R);continue}if(N.length===0||N.length>4)return;let _=Number.parseInt(N,16);if(Number.isNaN(_))return;S.push(_>>8&255,_&255)}return S};if(o.length===1){let w=a(i);return w!==void 0&&w.length===16?w:void 0}let u=a(o[0]??""),h=a(o[1]??"");if(u===void 0||h===void 0)return;let g=16-u.length-h.length;if(g<0)return;return[...u,...Array(g).fill(0),...h]}function gt(r){let[i=0,o=0,a=0,u=0]=r;if(i===0)return{kind:"unspecified",range:"0.0.0.0/8"};if(i===127)return{kind:"loopback",range:"127.0.0.0/8"};if(i===10)return{kind:"private",range:"10.0.0.0/8"};if(i===172&&o>=16&&o<=31)return{kind:"private",range:"172.16.0.0/12"};if(i===192&&o===168)return{kind:"private",range:"192.168.0.0/16"};if(i===100&&o>=64&&o<=127)return{kind:"cgnat",range:"100.64.0.0/10"};if(i===169&&o===254)return{kind:"link-local",range:"169.254.0.0/16"};if(i===192&&o===0&&a===0)return{kind:"reserved",range:"192.0.0.0/24"};if(i===192&&o===0&&a===2)return{kind:"reserved",range:"192.0.2.0/24 (TEST-NET-1)"};if(i===198&&(o===18||o===19))return{kind:"reserved",range:"198.18.0.0/15"};if(i===198&&o===51&&a===100)return{kind:"reserved",range:"198.51.100.0/24 (TEST-NET-2)"};if(i===203&&o===0&&a===113)return{kind:"reserved",range:"203.0.113.0/24 (TEST-NET-3)"};if(i>=224&&i<=239)return{kind:"multicast",range:"224.0.0.0/4"};if(i===255&&o===255&&a===255&&u===255)return{kind:"reserved",range:"255.255.255.255"};if(i>=240)return{kind:"reserved",range:"240.0.0.0/4"};return ur}function wa(r){if(r.length!==16)return{kind:"reserved",range:"unparseable"};if(r.slice(0,10).every((h)=>h===0)&&r[10]===255&&r[11]===255)return gt(r.slice(12));if(r[0]===0&&r[1]===100&&r[2]===255&&r[3]===155&&r.slice(4,12).every((h)=>h===0))return gt(r.slice(12));if(r.every((h)=>h===0))return{kind:"unspecified",range:"::"};if(r.slice(0,15).every((h)=>h===0)&&r[15]===1)return{kind:"loopback",range:"::1"};let a=r[0]??0,u=r[1]??0;if((a&254)===252)return{kind:"private",range:"fc00::/7"};if(a===254&&(u&192)===128)return{kind:"link-local",range:"fe80::/10"};if(a===255)return{kind:"multicast",range:"ff00::/8"};if(a===32&&u===1&&r[2]===13&&r[3]===184)return{kind:"reserved",range:"2001:db8::/32"};return ur}function yt(r){let i=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,o=hr(i);if(o!==void 0)return gt(o);let a=ya(i);if(a!==void 0)return wa(a);return}var ba=new Set(["http:","https:"]),va=[".local",".localhost",".internal",".intranet",".lan",".home.arpa"];function ka(r){let i=r.trim();if(i==="")throw Xn(r,"the value is empty");try{return new URL(i)}catch(o){throw Xn(r,o instanceof Error?o.message:String(o))}}function $a(r){if(!ba.has(r.protocol))throw Zo(r.protocol.replace(":",""));if(r.username!==""||r.password!=="")throw Qo();let i=r.hostname.toLowerCase();if(i==="")throw Ue(r.href,"there is no host in the URL");if(i==="localhost")throw Ue(i,"it is this machine by definition");for(let a of va)if(i.endsWith(a))throw Ue(i,`${a} names are resolved on the local network, not the internet`);let o=i.startsWith("[")?"":i;if(o!==""&&!o.includes(".")&&yt(i)===void 0)throw Ue(i,"a name with no dot in it is completed by the local search domain")}async function Sa(r,i,o=0){$a(r);let a=r.hostname.toLowerCase(),u=yt(a);if(u!==void 0){if(u.kind!=="public")throw ft(a,a,u.kind,u.range,o);return}let h;try{h=await i(a)}catch(g){throw zn(a,g instanceof Error?g.message:String(g))}if(h.length===0)throw zn(a,"it has no addresses");for(let{address:g}of h){let w=yt(g);if(w===void 0)throw ft(a,g,"an address this cannot classify",void 0,o);if(w.kind!=="public")throw ft(a,g,w.kind,w.range,o)}}var _a=async(r)=>(await ga(r,{all:!0,verbatim:!0})).map((o)=>({address:o.address})),bt="web",fr=2000000,pt=6000,Fe=5,Ea=3000,Ta=20000,Ra={slug:"web_fetch",provider:bt,summary:"Reads one web page and returns its text.",whenToUse:"you have a specific URL — from the person, from a search result, from a document — and need what is actually on that page rather than what you remember about it",whenNotToUse:"you do not have a URL yet, which is web_search; the address is on this machine or this network, which is refused; or you want a file from disk, which is file_read",mutating:!1,trust:"untrusted",policyArg:"url",tags:["read","web"],parameters:{type:"object",properties:{url:{type:"string",description:"The complete address of one page, including https://. Public internet only — addresses on this machine or this network are refused."}},required:["url"]}};function Aa(r){return{spec:Ra,handler:Oa(r)}}function xa(r){let i=Math.max(1000,r-Ea);return Math.min(Ta,i)}function Oa(r){let i=r.maxBytes??fr;return async(o,a)=>{let u=String(o.url??""),h=ka(u),g=new AbortController,w=()=>{g.abort()};a.signal.addEventListener("abort",w,{once:!0});let k=setTimeout(w,xa(a.deadlineMs));try{for(let S=0;S<=Fe;S+=1){await Sa(h,r.lookup,S);let T;try{T=await r.fetch(h.href,{method:"GET",redirect:"manual",signal:g.signal,headers:{"user-agent":r.userAgent,accept:"text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5","accept-language":"en"}})}catch(de){throw Qn(h.href,de instanceof Error?de.message:String(de))}let N=T.headers.get("location");if(Ia(T.status)&&N!==null){if(await T.body?.cancel().catch(()=>{return}),S===Fe)throw er(u,Fe);try{h=new URL(N,h)}catch{throw Qn(h.href,`it redirected to an unusable address: ${N}`)}continue}if(!T.ok)throw await T.body?.cancel().catch(()=>{return}),ea(h.href,T.status,T.statusText);let _=T.headers.get("content-type")??"";if(!pa(_))throw await T.body?.cancel().catch(()=>{return}),ta(h.href,_.split(";")[0]?.trim()??"binary");let{text:R,read:M,capped:L}=await Ca(T,i),{title:F,text:U}=ma(R,_);return Na({url:h.href,requested:u,...F===void 0?{}:{title:F},text:U,read:M,capped:L,hops:S})}throw er(u,Fe)}finally{clearTimeout(k),a.signal.removeEventListener("abort",w)}}}function Ia(r){return r===301||r===302||r===303||r===307||r===308}async function Ca(r,i){let o=r.body;if(o===null)return{text:"",read:0,capped:!1};let a=o.getReader(),u=new TextDecoder("utf-8"),h=[],g=0,w=!1;try{for(;;){let{done:k,value:S}=await a.read();if(k)break;if(S===void 0)continue;if(g+=S.byteLength,g>=i){let T=S.byteLength-(g-i);h.push(u.decode(S.subarray(0,Math.max(0,T)),{stream:!0})),w=!0;break}h.push(u.decode(S,{stream:!0}))}}finally{await a.cancel().catch(()=>{return})}return h.push(u.decode()),{text:h.join(""),read:Math.min(g,i),capped:w}}function Na(r){let i=[];if(i.push(r.url),r.hops>0&&r.url!==r.requested)i.push(`redirected from ${r.requested} (${r.hops} hop${r.hops===1?"":"s"})`);if(r.title!==void 0)i.push(`title: ${r.title}`);let o=r.text,a=!1;if(o.length>pt)o=o.slice(0,pt),a=!0;let u=[];if(r.capped)u.push(`the download stopped at ${r.read.toLocaleString("en-US")} bytes, so the end of the page is missing`);if(a)u.push(`only the first ${pt.toLocaleString("en-US")} characters are shown`);if(u.length>0)i.push(`incomplete: ${u.join("; ")}`);return i.push(""),i.push(o===""?"(the page has no readable text)":o),i.join(`
43
- `)}var mr=5,pr=10,nr=300,La=3000,ja=15000,Ma={slug:"web_search",provider:bt,summary:"Searches the web and returns titles, addresses and short extracts.",whenToUse:"you need something current, something you are unsure about, or a page whose address you do not know — prices, news, documentation, whether a thing still exists",whenNotToUse:"you already have the URL, which is web_fetch; the answer is in a file or in this conversation; or you want to find a tool rather than a page, which this cannot do",mutating:!1,trust:"untrusted",policyArg:"query",tags:["read","web","search"],parameters:{type:"object",properties:{query:{type:"string",description:"What to search for, written the way you would type it into a search box. Keywords work better than a full sentence."},maxResults:{type:"integer",description:`How many results to return, 1 to ${pr}.`,default:mr}},required:["query"]}};function Pa(r){return{spec:Ma,handler:Ua(r)}}function Ua(r){let i=ir(r.backend);return async(o,a)=>{let u=String(o.query??"").trim();if(u==="")return"No query was given, so nothing was searched for. Call this again with the words you want to look up.";let h=r.env[r.apiKeyEnv]??"";if(h==="")throw na(i.id,r.apiKeyEnv);let g=Fa(o.maxResults),{url:w,init:k}=i.request(u,g,h),S=new AbortController,T=()=>{S.abort()};a.signal.addEventListener("abort",T,{once:!0});let N=setTimeout(T,Math.min(ja,Math.max(1000,a.deadlineMs-La)));try{let _=await r.fetch(w,{...k,signal:S.signal});if(!_.ok)await ca(i.id,_);let R=await _.json();return Da(u,i.read(R).slice(0,g))}finally{clearTimeout(N),a.signal.removeEventListener("abort",T)}}}function Fa(r){let i=typeof r==="number"?r:Number(r);if(!Number.isFinite(i))return mr;return Math.min(pr,Math.max(1,Math.trunc(i)))}function Da(r,i){if(i.length===0)return`No results for ${JSON.stringify(r)}. The search ran and came back empty — a narrower or differently worded query may find something, but do not assume the subject does not exist.`;let o=i.map((a,u)=>{let h=a.snippet.length>nr?`${a.snippet.slice(0,nr).trimEnd()}…`:a.snippet;return[`${u+1}. ${a.title===""?"(untitled)":a.title}`,` ${a.url}`,...h===""?[]:[` ${h.replace(/\s+/g," ")}`]].join(`
42
+ `).trim()}function dr(r){return r.replace(/\s+/g," ").trim()}function ma(r,i){let o=i.split(";")[0]?.trim().toLowerCase()??"";if(o.includes("html")||o.includes("xml")){let a=ha(r);return{text:fa(r),...a===void 0?{}:{title:a}}}return{text:r.trim()}}function pa(r){let i=r.split(";")[0]?.trim().toLowerCase()??"";if(i==="")return!0;if(i.startsWith("text/"))return!0;return/^application\/(?:json|xml|xhtml\+xml|ld\+json|rss\+xml|atom\+xml|javascript|x-ndjson)$/.test(i)}var lr={kind:"public"};function ur(r){let i=r.split(".");if(i.length!==4)return;let o=[];for(let a of i){if(a.length===0||a.length>3||!/^[0-9]+$/.test(a))return;if(a.length>1&&a.startsWith("0"))return;let u=Number(a);if(u>255)return;o.push(u)}return o}function ya(r){let i=r.split("%")[0]??"";if(i==="")return;if(!/^[0-9a-fA-F:.]+$/.test(i))return;let o=i.split("::");if(o.length>2)return;let a=(w)=>{if(w==="")return[];let v=w.split(":"),S=[];for(let T=0;T<v.length;T+=1){let L=v[T]??"";if(L.includes(".")){if(T!==v.length-1)return;let I=ur(L);if(I===void 0)return;S.push(...I);continue}if(L.length===0||L.length>4)return;let _=Number.parseInt(L,16);if(Number.isNaN(_))return;S.push(_>>8&255,_&255)}return S};if(o.length===1){let w=a(i);return w!==void 0&&w.length===16?w:void 0}let u=a(o[0]??""),h=a(o[1]??"");if(u===void 0||h===void 0)return;let g=16-u.length-h.length;if(g<0)return;return[...u,...Array(g).fill(0),...h]}function yt(r){let[i=0,o=0,a=0,u=0]=r;if(i===0)return{kind:"unspecified",range:"0.0.0.0/8"};if(i===127)return{kind:"loopback",range:"127.0.0.0/8"};if(i===10)return{kind:"private",range:"10.0.0.0/8"};if(i===172&&o>=16&&o<=31)return{kind:"private",range:"172.16.0.0/12"};if(i===192&&o===168)return{kind:"private",range:"192.168.0.0/16"};if(i===100&&o>=64&&o<=127)return{kind:"cgnat",range:"100.64.0.0/10"};if(i===169&&o===254)return{kind:"link-local",range:"169.254.0.0/16"};if(i===192&&o===0&&a===0)return{kind:"reserved",range:"192.0.0.0/24"};if(i===192&&o===0&&a===2)return{kind:"reserved",range:"192.0.2.0/24 (TEST-NET-1)"};if(i===198&&(o===18||o===19))return{kind:"reserved",range:"198.18.0.0/15"};if(i===198&&o===51&&a===100)return{kind:"reserved",range:"198.51.100.0/24 (TEST-NET-2)"};if(i===203&&o===0&&a===113)return{kind:"reserved",range:"203.0.113.0/24 (TEST-NET-3)"};if(i>=224&&i<=239)return{kind:"multicast",range:"224.0.0.0/4"};if(i===255&&o===255&&a===255&&u===255)return{kind:"reserved",range:"255.255.255.255"};if(i>=240)return{kind:"reserved",range:"240.0.0.0/4"};return lr}function wa(r){if(r.length!==16)return{kind:"reserved",range:"unparseable"};if(r.slice(0,10).every((h)=>h===0)&&r[10]===255&&r[11]===255)return yt(r.slice(12));if(r[0]===0&&r[1]===100&&r[2]===255&&r[3]===155&&r.slice(4,12).every((h)=>h===0))return yt(r.slice(12));if(r.every((h)=>h===0))return{kind:"unspecified",range:"::"};if(r.slice(0,15).every((h)=>h===0)&&r[15]===1)return{kind:"loopback",range:"::1"};let a=r[0]??0,u=r[1]??0;if((a&254)===252)return{kind:"private",range:"fc00::/7"};if(a===254&&(u&192)===128)return{kind:"link-local",range:"fe80::/10"};if(a===255)return{kind:"multicast",range:"ff00::/8"};if(a===32&&u===1&&r[2]===13&&r[3]===184)return{kind:"reserved",range:"2001:db8::/32"};return lr}function wt(r){let i=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,o=ur(i);if(o!==void 0)return yt(o);let a=ya(i);if(a!==void 0)return wa(a);return}var ba=new Set(["http:","https:"]),va=[".local",".localhost",".internal",".intranet",".lan",".home.arpa"];function ka(r){let i=r.trim();if(i==="")throw Qn(r,"the value is empty");try{return new URL(i)}catch(o){throw Qn(r,o instanceof Error?o.message:String(o))}}function $a(r){if(!ba.has(r.protocol))throw Zo(r.protocol.replace(":",""));if(r.username!==""||r.password!=="")throw Qo();let i=r.hostname.toLowerCase();if(i==="")throw Ue(r.href,"there is no host in the URL");if(i==="localhost")throw Ue(i,"it is this machine by definition");for(let a of va)if(i.endsWith(a))throw Ue(i,`${a} names are resolved on the local network, not the internet`);let o=i.startsWith("[")?"":i;if(o!==""&&!o.includes(".")&&wt(i)===void 0)throw Ue(i,"a name with no dot in it is completed by the local search domain")}async function Sa(r,i,o=0){$a(r);let a=r.hostname.toLowerCase(),u=wt(a);if(u!==void 0){if(u.kind!=="public")throw mt(a,a,u.kind,u.range,o);return}let h;try{h=await i(a)}catch(g){throw er(a,g instanceof Error?g.message:String(g))}if(h.length===0)throw er(a,"it has no addresses");for(let{address:g}of h){let w=wt(g);if(w===void 0)throw mt(a,g,"an address this cannot classify",void 0,o);if(w.kind!=="public")throw mt(a,g,w.kind,w.range,o)}}var _a=async(r)=>(await ga(r,{all:!0,verbatim:!0})).map((o)=>({address:o.address})),vt="web",mr=2000000,gt=6000,Fe=5,Ea=3000,Ta=20000,Ra={slug:"web_fetch",provider:vt,summary:"Reads one web page and returns its text.",whenToUse:"you have a specific URL — from the person, from a search result, from a document — and need what is actually on that page rather than what you remember about it",whenNotToUse:"you do not have a URL yet, which is web_search; the address is on this machine or this network, which is refused; or you want a file from disk, which is file_read",mutating:!1,trust:"untrusted",policyArg:"url",tags:["read","web"],parameters:{type:"object",properties:{url:{type:"string",description:"The complete address of one page, including https://. Public internet only — addresses on this machine or this network are refused."}},required:["url"]}};function Aa(r){return{spec:Ra,handler:Oa(r)}}function xa(r){let i=Math.max(1000,r-Ea);return Math.min(Ta,i)}function Oa(r){let i=r.maxBytes??mr;return async(o,a)=>{let u=String(o.url??""),h=ka(u),g=new AbortController,w=()=>{g.abort()};a.signal.addEventListener("abort",w,{once:!0});let v=setTimeout(w,xa(a.deadlineMs));try{for(let S=0;S<=Fe;S+=1){await Sa(h,r.lookup,S);let T;try{T=await r.fetch(h.href,{method:"GET",redirect:"manual",signal:g.signal,headers:{"user-agent":r.userAgent,accept:"text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5","accept-language":"en"}})}catch(de){throw tr(h.href,de instanceof Error?de.message:String(de))}let L=T.headers.get("location");if(Ia(T.status)&&L!==null){if(await T.body?.cancel().catch(()=>{return}),S===Fe)throw nr(u,Fe);try{h=new URL(L,h)}catch{throw tr(h.href,`it redirected to an unusable address: ${L}`)}continue}if(!T.ok)throw await T.body?.cancel().catch(()=>{return}),ea(h.href,T.status,T.statusText);let _=T.headers.get("content-type")??"";if(!pa(_))throw await T.body?.cancel().catch(()=>{return}),ta(h.href,_.split(";")[0]?.trim()??"binary");let{text:I,read:M,capped:j}=await Ca(T,i),{title:F,text:P}=ma(I,_);return Na({url:h.href,requested:u,...F===void 0?{}:{title:F},text:P,read:M,capped:j,hops:S})}throw nr(u,Fe)}finally{clearTimeout(v),a.signal.removeEventListener("abort",w)}}}function Ia(r){return r===301||r===302||r===303||r===307||r===308}async function Ca(r,i){let o=r.body;if(o===null)return{text:"",read:0,capped:!1};let a=o.getReader(),u=new TextDecoder("utf-8"),h=[],g=0,w=!1;try{for(;;){let{done:v,value:S}=await a.read();if(v)break;if(S===void 0)continue;if(g+=S.byteLength,g>=i){let T=S.byteLength-(g-i);h.push(u.decode(S.subarray(0,Math.max(0,T)),{stream:!0})),w=!0;break}h.push(u.decode(S,{stream:!0}))}}finally{await a.cancel().catch(()=>{return})}return h.push(u.decode()),{text:h.join(""),read:Math.min(g,i),capped:w}}function Na(r){let i=[];if(i.push(r.url),r.hops>0&&r.url!==r.requested)i.push(`redirected from ${r.requested} (${r.hops} hop${r.hops===1?"":"s"})`);if(r.title!==void 0)i.push(`title: ${r.title}`);let o=r.text,a=!1;if(o.length>gt)o=o.slice(0,gt),a=!0;let u=[];if(r.capped)u.push(`the download stopped at ${r.read.toLocaleString("en-US")} bytes, so the end of the page is missing`);if(a)u.push(`only the first ${gt.toLocaleString("en-US")} characters are shown`);if(u.length>0)i.push(`incomplete: ${u.join("; ")}`);return i.push(""),i.push(o===""?"(the page has no readable text)":o),i.join(`
43
+ `)}var gr=5,yr=10,sr=300,La=3000,ja=15000,Ma={slug:"web_search",provider:vt,summary:"Searches the web and returns titles, addresses and short extracts.",whenToUse:"you need something current, something you are unsure about, or a page whose address you do not know — prices, news, documentation, whether a thing still exists",whenNotToUse:"you already have the URL, which is web_fetch; the answer is in a file or in this conversation; or you want to find a tool rather than a page, which this cannot do",mutating:!1,trust:"untrusted",policyArg:"query",tags:["read","web","search"],parameters:{type:"object",properties:{query:{type:"string",description:"What to search for, written the way you would type it into a search box. Keywords work better than a full sentence."},maxResults:{type:"integer",description:`How many results to return, 1 to ${yr}.`,default:gr}},required:["query"]}};function Pa(r){return{spec:Ma,handler:Ua(r)}}function Ua(r){let i=ar(r.backend);return async(o,a)=>{let u=String(o.query??"").trim();if(u==="")return"No query was given, so nothing was searched for. Call this again with the words you want to look up.";let h=r.env[r.apiKeyEnv]??"";if(h==="")throw na(i.id,r.apiKeyEnv);let g=Fa(o.maxResults),{url:w,init:v}=i.request(u,g,h),S=new AbortController,T=()=>{S.abort()};a.signal.addEventListener("abort",T,{once:!0});let L=setTimeout(T,Math.min(ja,Math.max(1000,a.deadlineMs-La)));try{let _=await r.fetch(w,{...v,signal:S.signal});if(!_.ok)await ca(i.id,_);let I=await _.json();return Da(u,i.read(I).slice(0,g))}finally{clearTimeout(L),a.signal.removeEventListener("abort",T)}}}function Fa(r){let i=typeof r==="number"?r:Number(r);if(!Number.isFinite(i))return gr;return Math.min(yr,Math.max(1,Math.trunc(i)))}function Da(r,i){if(i.length===0)return`No results for ${JSON.stringify(r)}. The search ran and came back empty — a narrower or differently worded query may find something, but do not assume the subject does not exist.`;let o=i.map((a,u)=>{let h=a.snippet.length>sr?`${a.snippet.slice(0,sr).trimEnd()}…`:a.snippet;return[`${u+1}. ${a.title===""?"(untitled)":a.title}`,` ${a.url}`,...h===""?[]:[` ${h.replace(/\s+/g," ")}`]].join(`
44
44
  `)});return[`${i.length} result${i.length===1?"":"s"} for ${JSON.stringify(r)}:`,"",...o].join(`
45
- `)}var Ka="dispach-agent/0.1 (+https://github.com/moeen-mahmud/dispach)";function rr(r){return r.toLowerCase().replace(/[\s_.-]+/g,"")}class gr{id=bt;#e;constructor(r){let i=r.backend??"tavily",o=ir(i),a=r.fetch??((h,g)=>fetch(h,g)),u=r.lookup??_a;this.#e=[Pa({backend:i,apiKeyEnv:r.apiKeyEnv??o.defaultKeyEnv,env:r.env,fetch:a}),Aa({lookup:u,fetch:a,maxBytes:r.maxBytes??fr,userAgent:Ka})]}available(){return Promise.resolve(this.#e.map((r)=>({slug:r.spec.slug,summary:r.spec.summary})))}resolve(r){let i=new Set(r.map(rr));return Promise.resolve(this.#e.filter((o)=>i.has(rr(o.spec.slug))))}list(){return Promise.resolve(this.#e.map((r)=>r.spec.slug))}}var sr=["backend","apiKeyEnv","maxBytes"];function kt(r){let i=Object.keys(r.config).filter((h)=>!sr.includes(h));if(i.length>0)throw new y({code:"web_config_unknown",message:`The web provider's configuration has ${i.length===1?"a key":"keys"} it does not read: ${i.join(", ")}.`,hint:`Accepted keys are ${sr.join(", ")}. Refused rather than ignored, because a setting that looks applied and is not is worse than a rejected manifest. There is deliberately no setting that permits private addresses.`,field:"tools.providers.web"});let o=r.config.backend;if(o!==void 0&&!tr.includes(String(o)))throw mt("backend",`must be one of ${tr.join(", ")} — got ${JSON.stringify(o)}.`);let a=r.config.apiKeyEnv;if(a!==void 0&&(typeof a!=="string"||a===""))throw mt("apiKeyEnv","must be the non-empty name of an environment variable — never the key itself, which fails validation.");let u=r.config.maxBytes;if(u!==void 0&&(typeof u!=="number"||!Number.isFinite(u)||u<1000))throw mt("maxBytes","must be a number of at least 1000.");return new gr({env:r.env,...o===void 0?{}:{backend:String(o)},...typeof a==="string"?{apiKeyEnv:a}:{},...typeof u==="number"?{maxBytes:u}:{}})}var Ba="0.1.0",yr={name:"web",version:Ba,dispachApi:"^0.1",permissions:[{kind:"network",hosts:["*"]}],setup(r){r.defineToolProvider("web",kt)}};var I={composio:rt,system:ht,web:kt};function O(){return new Pe({env:process.env})}var W=Object.keys(I),C={telegram:Ve},q=Object.keys(C),P={"@dispach/channel-telegram":Lt,"@dispach/tools-composio":on,"@dispach/tools-system":Yn,"@dispach/tools-web":yr},ar=Object.keys(P);import{existsSync as Ae,mkdirSync as Va,readdirSync as Sr,readFileSync as _r,renameSync as Ya,rmSync as Te,statSync as Xa,writeFileSync as za}from"node:fs";import{join as ae,relative as Za}from"node:path";import{existsSync as Ha,mkdirSync as Wa,readFileSync as Ga,writeFileSync as qa}from"node:fs";import{join as St}from"node:path";var Je=[{name:"anthropic",url:"https://github.com/anthropics/skills",path:"skills",builtin:!0},{name:"github",url:"https://github.com/github/awesome-copilot",path:"skills",builtin:!0,curated:ro}],Ja=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function lr(r){return r.length>0&&r.length<=64&&Ja.test(r)}var wr=1;function jt(r){return St(ee(r),"sources.json")}function De(r){return St(ee(r),"sources")}function Be(r,i){return St(De(i),r)}function _t(r){let i=jt(r);if(!Ha(i))return{};let o;try{o=JSON.parse(Ga(i,"utf8"))}catch(a){throw new t({code:"skill_sources_unreadable",message:`${i} is not valid JSON: ${a instanceof Error?a.message:String(a)}`,hint:"Fix the file, or delete it — the built-in sources work with no file at all."})}if(typeof o!=="object"||o===null||Array.isArray(o))throw new t({code:"skill_sources_unreadable",message:`${i} does not hold a JSON object`,hint:`Expected {"version": ${wr}, "sources": [...]}. Delete the file to start from the built-in sources.`});return o}function V(r){let i=_t(r),o=(i.sources??[]).filter((g)=>lr(g.name)),a=new Set(i.disabled??[]),u=new Map(o.map((g)=>[g.name,g])),h=[];for(let g of Je){if(a.has(g.name))continue;let w=u.get(g.name);h.push(w===void 0?g:{...w,builtin:!1})}for(let g of o){if(Je.some((w)=>w.name===g.name))continue;h.push({...g,builtin:!1})}return h}function vr(r,i){let o=jt(i);Wa(ee(i),{recursive:!0});let a={version:wr,sources:r.sources??[],...r.disabled===void 0||r.disabled.length===0?{}:{disabled:r.disabled}};qa(o,`${JSON.stringify(a,null,4)}
46
- `)}function Fr(r,i){let o=_t(i),a=(o.sources??[]).filter((h)=>h.name!==r.name),u=(o.disabled??[]).filter((h)=>h!==r.name);vr({...o,sources:[...a,r],disabled:u},i)}function Ur(r,i){let o=_t(i),a=(o.sources??[]).filter((k)=>k.name!==r),u=a.length!==(o.sources??[]).length,h=Je.some((k)=>k.name===r),g=(o.disabled??[]).includes(r);if(!u&&!h)return!1;if(h&&g&&!u)return!1;let w=h&&!g?[...o.disabled??[],r]:o.disabled??[];return vr({...o,sources:a,disabled:w},i),!0}function jr(r){let i=r.trim();if(i.length===0)throw $t(r);if(/^[\w.-]+\/[\w.-]+$/.test(i))return{url:`https://github.com/${i.replace(/\.git$/,"")}`};if(i.startsWith("git@")||i.startsWith("ssh://"))return{url:i};let o;try{o=new URL(i)}catch{throw $t(r)}if(o.protocol!=="https:"&&o.protocol!=="http:")throw $t(r);let a=o.pathname.split("/").filter((k)=>k.length>0),u=a.findIndex((k)=>k==="tree"||k==="blob");if(u<2)return{url:`${o.origin}/${a.join("/")}`.replace(/\.git$/,"")};let h=a.slice(0,u).join("/"),g=a[u+1],w=a.slice(u+2).join("/");return{url:`${o.origin}/${h}`.replace(/\.git$/,""),...g===void 0?{}:{ref:g},...w.length===0?{}:{path:w}}}function $t(r){return new t({code:"skill_source_url_invalid",message:`${JSON.stringify(r)} is not a repository`,hint:"Accepted: owner/repo, an https:// clone URL, a git@ SSH URL, or the page URL you were reading — .../tree/<branch>/<subdir> is understood."})}function $r(r){let i=r.split("/").filter((o)=>o.length>0);if(i.length===1)return{skill:i[0]};if(i.length===2)return{source:i[0],skill:i[1]};throw new t({code:"skill_ref_invalid",message:`${JSON.stringify(r)} is neither a skill name nor <source>/<skill>`,hint:"Use `pdf` to search every source, or `anthropic/pdf` to name one. A path is taken as a path only if it exists on disk."})}var Er="SKILL.md",Tr=180000,Qa=async(r,i)=>{let o=await pe({command:"git",args:r,...i===void 0?{}:{cwd:i},timeoutMs:Tr,maxBuffer:33554432,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"",SSH_ASKPASS:"",SSH_ASKPASS_REQUIRE:"never",GIT_SSH_COMMAND:"ssh -oBatchMode=yes -oStrictHostKeyChecking=accept-new"}});if(o.notFound)throw new t({code:"git_missing",message:"git is not on PATH, and a skill source is a git repository",hint:"Install git — on macOS `xcode-select --install` is enough. Until then, clone a repository by hand and use `skills install <agent> <path>`."});return{code:o.code,stdout:o.stdout,stderr:o.stderr,...o.signalled?{timedOut:!0}:{}}};function Rr(r,i){return ae(De(i),`${r}.json`)}function In(r,i){let o=Rr(r,i);if(!Ae(o))return{};try{return JSON.parse(_r(o,"utf8"))}catch{return{}}}function ce(r,i){return Ae(ae(Be(r,i),".git"))}function Ar(r){return r.startsWith(".")||r.startsWith("/")||r.startsWith("~")||Ae(r)}async function Qe(r,i={}){let o=i.git??Qa,a=i.env,u=Be(r.name,a),h=`${u}.partial`;Va(De(a),{recursive:!0}),Te(h,{recursive:!0,force:!0});let g=["clone","--depth","1","--single-branch",...r.ref===void 0?[]:["--branch",r.ref]],w=r.path!==void 0,k=!w,S=w?await o([...g,"--filter=blob:none","--sparse",r.url,h]):await o([...g,r.url,h]);if(S.code!==0&&w){Te(h,{recursive:!0,force:!0});let R=await o([...g,r.url,h]);if(R.code===0)k=!0,S=R}if(S.code!==0)throw Te(h,{recursive:!0,force:!0}),ec(r,S);if(r.path!==void 0&&!k){let R=await o(["sparse-checkout","set",r.path],h);if(R.code!==0)throw Te(h,{recursive:!0,force:!0}),new t({code:"skill_source_path_missing",message:`${r.name}: could not narrow the checkout to ${r.path}`,hint:`Check the path exists in ${r.url}. ${R.stderr.trim()||"git said nothing."}`})}let T=await o(["rev-parse","--short","HEAD"],h),N=T.code===0?T.stdout.trim():"unknown";Te(u,{recursive:!0,force:!0}),Ya(h,u);let _=be(r,a).length;return za(Rr(r.name,a),`${JSON.stringify({commit:N,fetchedAt:new Date().toISOString(),skills:_},null,4)}
47
- `),{commit:N,skills:_,unfiltered:k}}function ec(r,i){let o=i.stderr.trim().split(`
48
- `).slice(-3).join(" ");if(i.timedOut===!0)return new t({code:"skill_source_timeout",message:`${r.name}: git did not finish within ${Math.round(Tr/1000)}s`,hint:`Check the network, then try again — a partly fetched source was discarded, so the previous copy of ${r.name} is untouched.`});return new t({code:"skill_source_fetch_failed",message:`${r.name}: could not clone ${r.url}${o.length===0?"":` — ${o}`}`,hint:"A private repository needs a credential helper git can use without prompting. Check the URL and the branch; `sources remove` drops a source you no longer want."})}var tc=4,Or=new Set(["node_modules","dist","build","target","vendor",".git"]);function nc(r){let i=[],o=(a,u)=>{if(u>tc)return;let h;try{h=Sr(a,{withFileTypes:!0})}catch{return}if(Ae(ae(a,Er)))i.push(a);for(let g of h){if(!g.isDirectory())continue;if(g.name.startsWith(".")||Or.has(g.name))continue;o(ae(a,g.name),u+1)}};return o(r,0),i.sort()}var rc=[".py",".sh",".js",".ts",".mjs",".rb",".pl"];function Ir(r,i=0){if(i>3)return[];let o=[],a;try{a=Sr(r,{withFileTypes:!0})}catch{return[]}for(let u of a){let h=ae(r,u.name);if(u.isDirectory()){if(u.name.startsWith(".")||Or.has(u.name))continue;o.push(...Ir(h,i+1));continue}if(!u.isFile())continue;if((Xa(h).mode&73)!==0||rc.some((w)=>u.name.endsWith(w)))o.push(h)}return o}function be(r,i){let o=Be(r.name,i),a=r.path===void 0?o:ae(o,r.path);if(!Ae(a))return[];let u=[];for(let h of nc(a)){let g=_r(ae(h,Er),"utf8"),w=h.slice(h.lastIndexOf("/")+1),k={source:r.name,dir:h,repoPath:Za(o,h),scripts:Ir(h)};try{let S=Ie(w,g);u.push({...k,skill:S.frontmatter.name,description:S.frontmatter.description,tokens:v(S.body)})}catch(S){u.push({...k,skill:w,description:"",tokens:v(g),problem:S instanceof Error?S.message:String(S)})}}return u}var me="SKILL.md";function ve(r){try{let i=x(r.manifestPath,{knownProviders:W,knownChannels:q,env:{...p([r.manifestPath]),...r.envOverlay}}),a=r.action==="new"||r.action==="install"?mc(i.path,i.dir,i.manifest.skills):i.manifest.skills;if(a===void 0)return dc(r);let u=H(i.manifest.model.main.id,i.manifest.model.main.capabilities),h=Mr(a.dir)?a.dir:Et(i.dir,a.dir);if(r.action==="new")return gc(h,r);if(r.action==="remove")return vc(h,r);let g=Ke({dir:h,maxActive:a.maxActive,threshold:a.threshold,style:u.promptStyle,agentDir:i.dir,runner:O()});switch(r.action){case"list":return lc(h,g.skills,g,r);case"show":return uc(g.skills,r);case"install":return yc(h,r);default:return hc(g.skills,r)}}catch(i){if(r.json===!0&&i instanceof t)return process.stdout.write(`${JSON.stringify({ok:!1,error:i.toDetail(),details:i.details},null,2)}
45
+ `)}var Ka="dispach-agent/0.1 (+https://github.com/moeen-mahmud/dispach)";function ir(r){return r.toLowerCase().replace(/[\s_.-]+/g,"")}class wr{id=vt;#e;constructor(r){let i=r.backend??"tavily",o=ar(i),a=r.fetch??((h,g)=>fetch(h,g)),u=r.lookup??_a;this.#e=[Pa({backend:i,apiKeyEnv:r.apiKeyEnv??o.defaultKeyEnv,env:r.env,fetch:a}),Aa({lookup:u,fetch:a,maxBytes:r.maxBytes??mr,userAgent:Ka})]}available(){return Promise.resolve(this.#e.map((r)=>({slug:r.spec.slug,summary:r.spec.summary})))}resolve(r){let i=new Set(r.map(ir));return Promise.resolve(this.#e.filter((o)=>i.has(ir(o.spec.slug))))}list(){return Promise.resolve(this.#e.map((r)=>r.spec.slug))}}var or=["backend","apiKeyEnv","maxBytes"];function kt(r){let i=Object.keys(r.config).filter((h)=>!or.includes(h));if(i.length>0)throw new y({code:"web_config_unknown",message:`The web provider's configuration has ${i.length===1?"a key":"keys"} it does not read: ${i.join(", ")}.`,hint:`Accepted keys are ${or.join(", ")}. Refused rather than ignored, because a setting that looks applied and is not is worse than a rejected manifest. There is deliberately no setting that permits private addresses.`,field:"tools.providers.web"});let o=r.config.backend;if(o!==void 0&&!rr.includes(String(o)))throw pt("backend",`must be one of ${rr.join(", ")} — got ${JSON.stringify(o)}.`);let a=r.config.apiKeyEnv;if(a!==void 0&&(typeof a!=="string"||a===""))throw pt("apiKeyEnv","must be the non-empty name of an environment variable — never the key itself, which fails validation.");let u=r.config.maxBytes;if(u!==void 0&&(typeof u!=="number"||!Number.isFinite(u)||u<1000))throw pt("maxBytes","must be a number of at least 1000.");return new wr({env:r.env,...o===void 0?{}:{backend:String(o)},...typeof a==="string"?{apiKeyEnv:a}:{},...typeof u==="number"?{maxBytes:u}:{}})}var Ba="0.1.0",br={name:"web",version:Ba,dispachApi:"^0.1",permissions:[{kind:"network",hosts:["*"]}],setup(r){r.defineToolProvider("web",kt)}};var A={composio:st,system:ft,web:kt};function O(){return new Pe({env:process.env})}var Y=Object.keys(A),N={telegram:Ve},X=Object.keys(N),C={"@dispach/channel-telegram":Lt,"@dispach/tools-composio":cn,"@dispach/tools-system":Zn,"@dispach/tools-web":br},fr=Object.keys(C);import{existsSync as _e,mkdirSync as Va,readdirSync as Sr,readFileSync as Tr,renameSync as Ya,rmSync as $e,statSync as Xa,writeFileSync as za}from"node:fs";import{join as ae,relative as Za}from"node:path";import{existsSync as Ha,mkdirSync as Wa,readFileSync as Ga,writeFileSync as qa}from"node:fs";import{join as St}from"node:path";var et=[{name:"anthropic",url:"https://github.com/anthropics/skills",path:"skills",builtin:!0},{name:"github",url:"https://github.com/github/awesome-copilot",path:"skills",builtin:!0,curated:lo}],Ja=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function hr(r){return r.length>0&&r.length<=64&&Ja.test(r)}var vr=1;function Ht(r){return St(ee(r),"sources.json")}function Ke(r){return St(ee(r),"sources")}function Be(r,i){return St(Ke(i),r)}function _t(r){let i=Ht(r);if(!Ha(i))return{};let o;try{o=JSON.parse(Ga(i,"utf8"))}catch(a){throw new t({code:"skill_sources_unreadable",message:`${i} is not valid JSON: ${a instanceof Error?a.message:String(a)}`,hint:"Fix the file, or delete it — the built-in sources work with no file at all."})}if(typeof o!=="object"||o===null||Array.isArray(o))throw new t({code:"skill_sources_unreadable",message:`${i} does not hold a JSON object`,hint:`Expected {"version": ${vr}, "sources": [...]}. Delete the file to start from the built-in sources.`});return o}function G(r){let i=_t(r),o=(i.sources??[]).filter((g)=>hr(g.name)),a=new Set(i.disabled??[]),u=new Map(o.map((g)=>[g.name,g])),h=[];for(let g of et){if(a.has(g.name))continue;let w=u.get(g.name);h.push(w===void 0?g:{...w,builtin:!1})}for(let g of o){if(et.some((w)=>w.name===g.name))continue;h.push({...g,builtin:!1})}return h}function kr(r,i){let o=Ht(i);Wa(ee(i),{recursive:!0});let a={version:vr,sources:r.sources??[],...r.disabled===void 0||r.disabled.length===0?{}:{disabled:r.disabled}};qa(o,`${JSON.stringify(a,null,4)}
46
+ `)}function Kr(r,i){let o=_t(i),a=(o.sources??[]).filter((h)=>h.name!==r.name),u=(o.disabled??[]).filter((h)=>h!==r.name);kr({...o,sources:[...a,r],disabled:u},i)}function Hr(r,i){let o=_t(i),a=(o.sources??[]).filter((v)=>v.name!==r),u=a.length!==(o.sources??[]).length,h=et.some((v)=>v.name===r),g=(o.disabled??[]).includes(r);if(!u&&!h)return!1;if(h&&g&&!u)return!1;let w=h&&!g?[...o.disabled??[],r]:o.disabled??[];return kr({...o,sources:a,disabled:w},i),!0}function Wr(r){let i=r.trim();if(i.length===0)throw $t(r);if(/^[\w.-]+\/[\w.-]+$/.test(i))return{url:`https://github.com/${i.replace(/\.git$/,"")}`};if(i.startsWith("git@")||i.startsWith("ssh://"))return{url:i};let o;try{o=new URL(i)}catch{throw $t(r)}if(o.protocol!=="https:"&&o.protocol!=="http:")throw $t(r);let a=o.pathname.split("/").filter((v)=>v.length>0),u=a.findIndex((v)=>v==="tree"||v==="blob");if(u<2)return{url:`${o.origin}/${a.join("/")}`.replace(/\.git$/,"")};let h=a.slice(0,u).join("/"),g=a[u+1],w=a.slice(u+2).join("/");return{url:`${o.origin}/${h}`.replace(/\.git$/,""),...g===void 0?{}:{ref:g},...w.length===0?{}:{path:w}}}function $t(r){return new t({code:"skill_source_url_invalid",message:`${JSON.stringify(r)} is not a repository`,hint:"Accepted: owner/repo, an https:// clone URL, a git@ SSH URL, or the page URL you were reading — .../tree/<branch>/<subdir> is understood."})}function $r(r){let i=r.split("/").filter((o)=>o.length>0);if(i.length===1)return{skill:i[0]};if(i.length===2)return{source:i[0],skill:i[1]};throw new t({code:"skill_ref_invalid",message:`${JSON.stringify(r)} is neither a skill name nor <source>/<skill>`,hint:"Use `pdf` to search every source, or `anthropic/pdf` to name one. A path is taken as a path only if it exists on disk."})}var Rr="SKILL.md",xr=180000,Qa=async(r,i)=>{let o=await ge({command:"git",args:r,...i===void 0?{}:{cwd:i},timeoutMs:xr,maxBuffer:33554432,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"",SSH_ASKPASS:"",SSH_ASKPASS_REQUIRE:"never",GIT_SSH_COMMAND:"ssh -oBatchMode=yes -oStrictHostKeyChecking=accept-new"}});if(o.notFound)throw new t({code:"git_missing",message:"git is not on PATH, and a skill source is a git repository",hint:"Install git — on macOS `xcode-select --install` is enough. Until then, clone a repository by hand and use `skills install <agent> <path>`."});return{code:o.code,stdout:o.stdout,stderr:o.stderr,...o.signalled?{timedOut:!0}:{}}};function Or(r,i){return ae(Ke(i),`${r}.json`)}function Mn(r,i){let o=Or(r,i);if(!_e(o))return{};try{return JSON.parse(Tr(o,"utf8"))}catch{return{}}}function ce(r,i){return _e(ae(Be(r,i),".git"))}function Ir(r){return r.startsWith(".")||r.startsWith("/")||r.startsWith("~")||_e(r)}async function tt(r,i={}){let o=i.git??Qa,a=i.env,u=Be(r.name,a),h=`${u}.partial`;Va(Ke(a),{recursive:!0}),$e(h,{recursive:!0,force:!0});let g=["clone","--depth","1","--single-branch",...r.ref===void 0?[]:["--branch",r.ref]],w=r.path!==void 0,v=!w,S=w?await o([...g,"--filter=blob:none","--sparse",r.url,h]):await o([...g,r.url,h]);if(S.code!==0&&w){$e(h,{recursive:!0,force:!0});let I=await o([...g,r.url,h]);if(I.code===0)v=!0,S=I}if(S.code!==0)throw $e(h,{recursive:!0,force:!0}),ec(r,S);if(r.path!==void 0&&!v){let I=await o(["sparse-checkout","set",r.path],h);if(I.code!==0)throw $e(h,{recursive:!0,force:!0}),new t({code:"skill_source_path_missing",message:`${r.name}: could not narrow the checkout to ${r.path}`,hint:`Check the path exists in ${r.url}. ${I.stderr.trim()||"git said nothing."}`})}let T=await o(["rev-parse","--short","HEAD"],h),L=T.code===0?T.stdout.trim():"unknown";$e(u,{recursive:!0,force:!0}),Ya(h,u);let _=ke(r,a).length;return za(Or(r.name,a),`${JSON.stringify({commit:L,fetchedAt:new Date().toISOString(),skills:_},null,4)}
47
+ `),{commit:L,skills:_,unfiltered:v}}function ec(r,i){let o=i.stderr.trim().split(`
48
+ `).slice(-3).join(" ");if(i.timedOut===!0)return new t({code:"skill_source_timeout",message:`${r.name}: git did not finish within ${Math.round(xr/1000)}s`,hint:`Check the network, then try again — a partly fetched source was discarded, so the previous copy of ${r.name} is untouched.`});return new t({code:"skill_source_fetch_failed",message:`${r.name}: could not clone ${r.url}${o.length===0?"":` — ${o}`}`,hint:"A private repository needs a credential helper git can use without prompting. Check the URL and the branch; `sources remove` drops a source you no longer want."})}var tc=4,Cr=new Set(["node_modules","dist","build","target","vendor",".git"]);function nc(r){let i=[],o=(a,u)=>{if(u>tc)return;let h;try{h=Sr(a,{withFileTypes:!0})}catch{return}if(_e(ae(a,Rr)))i.push(a);for(let g of h){if(!g.isDirectory())continue;if(g.name.startsWith(".")||Cr.has(g.name))continue;o(ae(a,g.name),u+1)}};return o(r,0),i.sort()}var rc=[".py",".sh",".js",".ts",".mjs",".rb",".pl"];function Nr(r,i=0){if(i>3)return[];let o=[],a;try{a=Sr(r,{withFileTypes:!0})}catch{return[]}for(let u of a){let h=ae(r,u.name);if(u.isDirectory()){if(u.name.startsWith(".")||Cr.has(u.name))continue;o.push(...Nr(h,i+1));continue}if(!u.isFile())continue;if((Xa(h).mode&73)!==0||rc.some((w)=>u.name.endsWith(w)))o.push(h)}return o}function ke(r,i){let o=Be(r.name,i),a=r.path===void 0?o:ae(o,r.path);if(!_e(a))return[];let u=[];for(let h of nc(a)){let g=Tr(ae(h,Rr),"utf8"),w=h.slice(h.lastIndexOf("/")+1),v={source:r.name,dir:h,repoPath:Za(o,h),scripts:Nr(h)};try{let S=Ne(w,g);u.push({...v,skill:S.frontmatter.name,description:S.frontmatter.description,tokens:k(S.body)})}catch(S){u.push({...v,skill:w,description:"",tokens:k(g),problem:S instanceof Error?S.message:String(S)})}}return u}var fe="SKILL.md";function Se(r){try{let i=x(r.manifestPath,{knownProviders:Y,knownChannels:X,env:{...m([r.manifestPath]),...r.envOverlay}}),a=r.action==="new"||r.action==="install"?mc(i.path,i.dir,i.manifest.skills):i.manifest.skills;if(a===void 0)return dc(r);let u=H(i.manifest.model.main.id,i.manifest.model.main.capabilities),h=Pr(a.dir)?a.dir:Tt(i.dir,a.dir);if(r.action==="new")return gc(h,r);if(r.action==="remove")return vc(h,r);let g=He({dir:h,maxActive:a.maxActive,threshold:a.threshold,style:u.promptStyle,agentDir:i.dir,runner:O()});switch(r.action){case"list":return lc(h,g.skills,g,r);case"show":return uc(g.skills,r);case"install":return yc(h,r);default:return hc(g.skills,r)}}catch(i){if(r.json===!0&&i instanceof t)return process.stdout.write(`${JSON.stringify({ok:!1,error:i.toDetail(),details:i.details},null,2)}
49
49
  `),s;throw i}}function dc(r){if(r.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,configured:!1,skills:[]},null,2)}
50
50
  `),n;return process.stdout.write(`this agent has no skills configured
51
51
 
@@ -57,31 +57,31 @@ Still running past ${r.timeoutMs} ms, left going rather than discarded. Output c
57
57
  `+` skills new ${r.manifestPath} <name>
58
58
 
59
59
  either one turns skills on for this agent; neither needs agent.yaml edited by hand
60
- `),n}function lc(r,i,o,a){let u=ge(r);if(a.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,configured:!0,cached:o.cached,maxActive:o.maxActive,threshold:o.threshold,skills:i.map((h)=>({...Tt(h),...u[h.name]===void 0?{}:{origin:u[h.name]}}))},null,2)}
60
+ `),n}function lc(r,i,o,a){let u=me(r);if(a.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,configured:!0,cached:o.cached,maxActive:o.maxActive,threshold:o.threshold,skills:i.map((h)=>({...Rt(h),...u[h.name]===void 0?{}:{origin:u[h.name]}}))},null,2)}
61
61
  `),n;if(i.length===0)return process.stdout.write(`no skills in ${r}
62
62
 
63
63
  \`sources search <what it should do>\` ranks 440+ from the configured catalogues, then
64
64
  \`skills install <agent> <source>/<skill>\`. \`skills new <agent> <name>\` writes one from a template.
65
65
  `),n;process.stdout.write(`${l([{label:"skills",value:String(i.length)},{label:"per turn",value:`at most ${o.maxActive}`},{label:"threshold",value:o.threshold.toFixed(2)},{label:"index",value:o.cached?"cached":"scanned"}])}
66
- `),process.stdout.write(`${m("catalogue")}
67
- `);for(let h of i){let g=h.scripts.length===0?"":` ${h.scripts.length} script(s)`,w=h.frontmatter.whenNotToUse===void 0?" no when-not-to-use":"",k=u[h.name],S=k===void 0?"":` ${k.source}@${k.commit}`;process.stdout.write(` ${h.name.padEnd(20)} ${String(h.tokens).padStart(5)} tokens${g}${S}${w}
66
+ `),process.stdout.write(`${p("catalogue")}
67
+ `);for(let h of i){let g=h.scripts.length===0?"":` ${h.scripts.length} script(s)`,w=h.frontmatter.whenNotToUse===void 0?" no when-not-to-use":"",v=u[h.name],S=v===void 0?"":` ${v.source}@${v.commit}`;process.stdout.write(` ${h.name.padEnd(20)} ${String(h.tokens).padStart(5)} tokens${g}${S}${w}
68
68
  `)}return n}function uc(r,i){let o=i.name;if(o===void 0)return process.stdout.write("skills show needs a skill name — `skills list` names them\n"),s;let a=r.find((g)=>g.name===o);if(a===void 0){let g=r.map((w)=>w.name).join(", ");return process.stdout.write(`no skill named ${o}${g===""?"":`. Known: ${g}`}
69
69
  `),s}if(i.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,skill:fc(a)},null,2)}
70
70
  `),n;let{frontmatter:u}=a;if(process.stdout.write(`${l([{label:"name",value:a.name},{label:"directory",value:a.dir},{label:"body",value:`${a.tokens} tokens`},...u.license===void 0?[]:[{label:"license",value:u.license}],...u.compatibility===void 0?[]:[{label:"needs",value:u.compatibility}]])}
71
- `),process.stdout.write(`${m("description")}
71
+ `),process.stdout.write(`${p("description")}
72
72
  `),process.stdout.write(`${c(u.description)}
73
- `),process.stdout.write(`${m("when not to use")}
74
- `),process.stdout.write(`${c(u.whenNotToUse??`not declared — add metadata.${Re()} to improve routing`)}
75
- `),a.scripts.length>0){process.stdout.write(`${m("scripts")}
73
+ `),process.stdout.write(`${p("when not to use")}
74
+ `),process.stdout.write(`${c(u.whenNotToUse??`not declared — add metadata.${Oe()} to improve routing`)}
75
+ `),a.scripts.length>0){process.stdout.write(`${p("scripts")}
76
76
  `);for(let g of a.scripts)process.stdout.write(`${d(`${g.slug} — scripts/${g.file} via ${g.interpreter??"its own shebang"}`)}
77
- `)}if(a.ignoredScripts.length>0){process.stdout.write(`${m("in scripts/ and not runnable")}
77
+ `)}if(a.ignoredScripts.length>0){process.stdout.write(`${p("in scripts/ and not runnable")}
78
78
  `);for(let g of a.ignoredScripts)process.stdout.write(`${d(`${g.file} — ${g.reason}`)}
79
- `)}if(u.allowedTools!==void 0)process.stdout.write(`${m("allowed-tools, declared and not honoured")}
79
+ `)}if(u.allowedTools!==void 0)process.stdout.write(`${p("allowed-tools, declared and not honoured")}
80
80
  `),process.stdout.write(`${c(u.allowedTools)}
81
81
  `),process.stdout.write(`${c("this runtime reads the field and never acts on it; permissions live in tools.policy")}
82
- `);let h=Object.entries(u.metadata).filter(([g])=>g!==Re());if(h.length>0)process.stdout.write(`${m("metadata")}
82
+ `);let h=Object.entries(u.metadata).filter(([g])=>g!==Oe());if(h.length>0)process.stdout.write(`${p("metadata")}
83
83
  `),process.stdout.write(`${l(h.map(([g,w])=>({label:g,value:w})))}
84
- `);return n}function hc(r,i){let o=xr(r);if(i.json===!0)return process.stdout.write(`${JSON.stringify({ok:o.length===0,skills:r.map(Tt),findings:o},null,2)}
84
+ `);return n}function hc(r,i){let o=Ar(r);if(i.json===!0)return process.stdout.write(`${JSON.stringify({ok:o.length===0,skills:r.map(Rt),findings:o},null,2)}
85
85
  `),i.strict===!0&&o.length>0?s:n;let a=new Map;for(let u of o){let g=r.find((w)=>u.message.includes(` ${w.name}:`))?.name??"";a.set(g,[...a.get(g)??[],u])}for(let u of r){let h=a.get(u.name)??[];process.stdout.write(` ${u.name.padEnd(20)} ${h.length===0?"ok":`${h.length} warning(s)`}
86
86
  `)}if(o.length===0)return process.stdout.write(`
87
87
  no findings
@@ -90,40 +90,40 @@ no findings
90
90
  `),process.stdout.write(` hint: ${u.hint}
91
91
  `);return process.stdout.write(`
92
92
  ${o.length} finding(s) — warnings, not failures. --strict exits non-zero.
93
- `),i.strict===!0?s:n}function Tt(r){return{name:r.name,tokens:r.tokens,hasWhenNotToUse:r.frontmatter.whenNotToUse!==void 0,scripts:r.scripts.map((i)=>i.slug),ignoredScripts:r.ignoredScripts}}function fc(r){return{...Tt(r),dir:r.dir,description:r.frontmatter.description,...r.frontmatter.whenNotToUse===void 0?{}:{whenNotToUse:r.frontmatter.whenNotToUse},...r.frontmatter.license===void 0?{}:{license:r.frontmatter.license},...r.frontmatter.compatibility===void 0?{}:{compatibility:r.frontmatter.compatibility},...r.frontmatter.allowedTools===void 0?{}:{allowedToolsDeclaredNotHonoured:r.frontmatter.allowedTools},metadata:r.frontmatter.metadata}}function mc(r,i,o){let a=o?.dir??"./skills",u=Mr(a)?a:Et(i,a);if(Nr(u,{recursive:!0}),o!==void 0)return o;let h=br({file:r,path:["skills"],value:pc(a)});if(process.stdout.write(`${l([{label:"enabled",value:`skills.dir = ${a}`}])}
93
+ `),i.strict===!0?s:n}function Rt(r){return{name:r.name,tokens:r.tokens,hasWhenNotToUse:r.frontmatter.whenNotToUse!==void 0,scripts:r.scripts.map((i)=>i.slug),ignoredScripts:r.ignoredScripts}}function fc(r){return{...Rt(r),dir:r.dir,description:r.frontmatter.description,...r.frontmatter.whenNotToUse===void 0?{}:{whenNotToUse:r.frontmatter.whenNotToUse},...r.frontmatter.license===void 0?{}:{license:r.frontmatter.license},...r.frontmatter.compatibility===void 0?{}:{compatibility:r.frontmatter.compatibility},...r.frontmatter.allowedTools===void 0?{}:{allowedToolsDeclaredNotHonoured:r.frontmatter.allowedTools},metadata:r.frontmatter.metadata}}function mc(r,i,o){let a=o?.dir??"./skills",u=Pr(a)?a:Tt(i,a);if(jr(u,{recursive:!0}),o!==void 0)return o;let h=Er({file:r,path:["skills"],value:pc(a)});if(process.stdout.write(`${l([{label:"enabled",value:`skills.dir = ${a}`}])}
94
94
  `),h.reflowed)process.stdout.write(`${d("the file was re-serialised to add the block — it is valid, and comments may have moved")}
95
- `);return{dir:a,...Pr}}var Pr={maxActive:1,threshold:0.35};function pc(r){return{dir:r,...Pr}}function gc(r,i){let o=i.name;if(o===void 0)return process.stdout.write("skills new needs a name — `skills new <manifest> <name>`\n"),s;if(!kr(o))return process.stdout.write(`${o} is not a legal skill name: lowercase letters, digits and single hyphens, never leading, trailing or doubled, at most 64 characters.
96
- `),s;let a=G(r,o);if(te(a))return process.stdout.write(`${a} already exists — nothing was written
97
- `),s;return Nr(a,{recursive:!0}),ac(G(a,"SKILL.md"),tn(Zn,{SKILL_NAME:o,WHEN_NOT_TO_USE_KEY:Re()}),"utf8"),process.stdout.write(`${l([{label:"created",value:G(a,"SKILL.md")},{label:"name",value:o}])}
98
- `),process.stdout.write(`${m("next")}
95
+ `);return{dir:a,...Ur}}var Ur={maxActive:1,threshold:0.35};function pc(r){return{dir:r,...Ur}}function gc(r,i){let o=i.name;if(o===void 0)return process.stdout.write("skills new needs a name — `skills new <manifest> <name>`\n"),s;if(!_r(o))return process.stdout.write(`${o} is not a legal skill name: lowercase letters, digits and single hyphens, never leading, trailing or doubled, at most 64 characters.
96
+ `),s;let a=B(r,o);if(te(a))return process.stdout.write(`${a} already exists — nothing was written
97
+ `),s;return jr(a,{recursive:!0}),ac(B(a,"SKILL.md"),dn(Jn,{SKILL_NAME:o,WHEN_NOT_TO_USE_KEY:Oe()}),"utf8"),process.stdout.write(`${l([{label:"created",value:B(a,"SKILL.md")},{label:"name",value:o}])}
98
+ `),process.stdout.write(`${p("next")}
99
99
  ${d("edit the description — it is the only thing selection reads, so name the words someone would actually type")}
100
100
  ${d("write the steps in place of the placeholder body")}
101
101
  ${d("skills validate — it warns until the scaffold is replaced")}
102
102
  ${d("restart the agent: the catalogue is scanned once at boot")}
103
- `),n}function yc(r,i){let o=i.name;if(o===void 0)return process.stdout.write("skills install needs something to install — `skills install <manifest> anthropic/pdf`, or a local path\n\n `sources search <what you need>` finds one.\n"),s;let a=Ar(o),u;if(!a){let _=wc(o,i.sandboxEnv);if(_===void 0)return s;u=_}let h=u===void 0?Et(o):u.entry.dir;if(u===void 0){if(!te(h)||!Lr(h).isDirectory())return process.stdout.write(`${h} is not a directory
104
- `),s;if(te(o)&&V(i.sandboxEnv).some((_)=>_.name===o))process.stdout.write(`note: ${o} is also a source, and a directory of that name here wins — \`sources search\` to install from the source instead
103
+ `),n}function yc(r,i){let o=i.name;if(o===void 0)return process.stdout.write("skills install needs something to install — `skills install <manifest> anthropic/pdf`, or a local path\n\n `sources search <what you need>` finds one.\n"),s;let a=Ir(o),u;if(!a){let _=wc(o,i.sandboxEnv);if(_===void 0)return s;u=_}let h=u===void 0?Tt(o):u.entry.dir;if(u===void 0){if(!te(h)||!Mr(h).isDirectory())return process.stdout.write(`${h} is not a directory
104
+ `),s;if(te(o)&&G(i.sandboxEnv).some((_)=>_.name===o))process.stdout.write(`note: ${o} is also a source, and a directory of that name here wins — \`sources search\` to install from the source instead
105
105
 
106
- `)}let g={},w=[],S=te(G(h,me))?[h]:He(h,{withFileTypes:!0}).filter((_)=>_.isDirectory()&&te(G(h,_.name,me))).map((_)=>G(h,_.name));if(S.length===0)return process.stdout.write(`no ${me} in ${h} or in any directory directly inside it
107
- `),s;let T=[],N=[];for(let _ of S){let R;try{R=Ie(Cr(_),ic(G(_,me),"utf8")).frontmatter.name}catch(L){N.push(`${Cr(_)} — ${L instanceof Error?L.message:String(L)}`);continue}let M=G(r,R);if(te(M)){N.push(`${R} — already installed at ${M}`);continue}if(sc(_,M,{recursive:!0,preserveTimestamps:!0}),T.push(R),u!==void 0)g[R]={source:u.spec.name,url:u.spec.url,repoPath:u.entry.repoPath,commit:u.commit,...u.spec.ref===void 0?{}:{ref:u.spec.ref},installedAt:new Date().toISOString()};w.push(...Dr(M).map((L)=>`${R}/${cc(M,L)}`))}if(Object.keys(g).length>0)xt(r,g);if(i.collect!==void 0){for(let _ of T)i.collect.push({name:_,ok:!0,runnable:w.filter((R)=>R.startsWith(`${_}/`))});for(let _ of N){let R=_.indexOf(" — ");i.collect.push({name:R===-1?_:_.slice(0,R),ok:!1,reason:R===-1?_:_.slice(R+3),runnable:[]})}}if(i.quiet===!0)return T.length===0?s:n;process.stdout.write(`${l([{label:"from",value:u===void 0?h:`${u.spec.name} (${u.spec.url}) at ${u.commit}`},{label:"installed",value:T.join(", ")},{label:"skipped",value:N.length===0?"":String(N.length)}])}
108
- `);for(let _ of N)process.stdout.write(`${d(_)}
109
- `);if(w.length>0){if(process.stdout.write(`${m("this installed code, which the agent can run")}
106
+ `)}let g={},w=[],S=te(B(h,fe))?[h]:We(h,{withFileTypes:!0}).filter((_)=>_.isDirectory()&&te(B(h,_.name,fe))).map((_)=>B(h,_.name));if(S.length===0)return process.stdout.write(`no ${fe} in ${h} or in any directory directly inside it
107
+ `),s;let T=[],L=[];for(let _ of S){let I;try{I=Ne(Lr(_),ic(B(_,fe),"utf8")).frontmatter.name}catch(j){L.push(`${Lr(_)} — ${j instanceof Error?j.message:String(j)}`);continue}let M=B(r,I);if(te(M)){L.push(`${I} — already installed at ${M}`);continue}if(sc(_,M,{recursive:!0,preserveTimestamps:!0}),T.push(I),u!==void 0)g[I]={source:u.spec.name,url:u.spec.url,repoPath:u.entry.repoPath,commit:u.commit,...u.spec.ref===void 0?{}:{ref:u.spec.ref},installedAt:new Date().toISOString()};w.push(...Fr(M).map((j)=>`${I}/${cc(M,j)}`))}if(Object.keys(g).length>0)Ot(r,g);if(i.collect!==void 0){for(let _ of T)i.collect.push({name:_,ok:!0,runnable:w.filter((I)=>I.startsWith(`${_}/`))});for(let _ of L){let I=_.indexOf(" — ");i.collect.push({name:I===-1?_:_.slice(0,I),ok:!1,reason:I===-1?_:_.slice(I+3),runnable:[]})}}if(i.quiet===!0)return T.length===0?s:n;process.stdout.write(`${l([{label:"from",value:u===void 0?h:`${u.spec.name} (${u.spec.url}) at ${u.commit}`},{label:"installed",value:T.join(", ")},{label:"skipped",value:L.length===0?"":String(L.length)}])}
108
+ `);for(let _ of L)process.stdout.write(`${d(_)}
109
+ `);if(w.length>0){if(process.stdout.write(`${p("this installed code, which the agent can run")}
110
110
  ${w.slice(0,12).map((_)=>d(_)).join(`
111
111
  `)}
112
112
  `),w.length>12)process.stdout.write(`${c(`… and ${w.length-12} more`)}
113
113
  `);process.stdout.write(`${c("read them before the agent does; `tools.policy` can name a skill script by slug")}
114
- `)}if(T.length>0)process.stdout.write(`${m("next")}
114
+ `)}if(T.length>0)process.stdout.write(`${p("next")}
115
115
  ${d("skills validate — a vendored skill usually has no negative guidance, which is a warning and not a problem")}
116
116
  ${d("restart the agent: the catalogue is scanned once at boot")}
117
117
  `);return T.length===0?s:n}function wc(r,i){let o;try{o=$r(r)}catch(S){if(!(S instanceof t))throw S;process.stdout.write(`${S.message}
118
118
 
119
119
  ${S.hint}
120
- `);return}let a=V(i),u=o.source===void 0?a:a.filter((S)=>S.name===o.source);if(u.length===0){let S=E(o.source??"",a.map((T)=>T.name));process.stdout.write(`no source called ${o.source}
120
+ `);return}let a=G(i),u=o.source===void 0?a:a.filter((S)=>S.name===o.source);if(u.length===0){let S=E(o.source??"",a.map((T)=>T.name));process.stdout.write(`no source called ${o.source}
121
121
 
122
122
  ${S===void 0?"`sources list` shows them.":`Did you mean ${S}?`}
123
123
  `);return}if(u.filter((S)=>!ce(S.name,i)).length===u.length){process.stdout.write(`${u.length===1?`${u[0]?.name} has not`:"no source has"} been fetched yet, so there is nothing to install from
124
124
 
125
125
  \`sources update${o.source===void 0?"":` ${o.source}`}\` first, or \`sources search ${o.skill}\` which fetches on demand.
126
- `);return}let g=u.filter((S)=>ce(S.name,i)).flatMap((S)=>be(S,i).map((T)=>({entry:T,spec:S}))),w=g.filter((S)=>S.entry.skill===o.skill);if(w.length===0){let S=E(o.skill,g.map((T)=>T.entry.skill));process.stdout.write(`no skill called ${o.skill} in ${u.map((T)=>T.name).join(", ")}
126
+ `);return}let g=u.filter((S)=>ce(S.name,i)).flatMap((S)=>ke(S,i).map((T)=>({entry:T,spec:S}))),w=g.filter((S)=>S.entry.skill===o.skill);if(w.length===0){let S=E(o.skill,g.map((T)=>T.entry.skill));process.stdout.write(`no skill called ${o.skill} in ${u.map((T)=>T.name).join(", ")}
127
127
 
128
128
  ${S===void 0?`\`sources search ${o.skill}\` ranks what is there.`:`Did you mean ${S}? \`sources search ${o.skill}\` ranks the alternatives.`}
129
129
  `);return}if(w.length>1){process.stdout.write(`${w.length} sources carry a skill called ${o.skill}
@@ -131,37 +131,37 @@ ${d("restart the agent: the catalogue is scanned once at boot")}
131
131
  ${w.map((S)=>` ${S.spec.name}/${S.entry.skill} — ${S.spec.url}
132
132
  `).join("")}
133
133
  Name one.
134
- `);return}let k=w[0];if(k.entry.problem!==void 0){process.stdout.write(`${k.spec.name}/${k.entry.skill} will not load: ${k.entry.problem}
134
+ `);return}let v=w[0];if(v.entry.problem!==void 0){process.stdout.write(`${v.spec.name}/${v.entry.skill} will not load: ${v.entry.problem}
135
135
 
136
136
  Nothing was copied. That is upstream's to fix — installing a hand-edited copy from a path is the way round it.
137
- `);return}return{entry:k.entry,spec:k.spec,commit:In(k.spec.name,i).commit??"unknown"}}function Dr(r,i=0){if(i>3)return[];let o=[];for(let a of He(r,{withFileTypes:!0})){let u=G(r,a.name);if(a.isDirectory()){if(a.name.startsWith("."))continue;o.push(...Dr(u,i+1));continue}if(!a.isFile())continue;if((Lr(u).mode&73)!==0||bc.some((g)=>a.name.endsWith(g)))o.push(u)}return o}var bc=[".py",".sh",".js",".ts",".mjs",".rb",".pl"];function vc(r,i){let o=i.name;if(o===void 0)return process.stdout.write("skills remove needs a name — `skills list` names them\n"),s;let a=G(r,o);if(!te(G(a,me))){let g=te(r)?He(r,{withFileTypes:!0}).filter((w)=>w.isDirectory()&&te(G(r,w.name,me))).map((w)=>w.name).join(", "):"";return process.stdout.write(`no skill named ${o}${g===""?"":`. Known: ${g}`}
138
- `),s}let u=Kr(a),h=ge(r)[o];return oc(a,{recursive:!0,force:!0}),On(r,o),process.stdout.write(`${l([{label:"removed",value:a},{label:"files",value:String(u)},...h===void 0?[]:[{label:"came from",value:`${h.source} (${h.url}) at ${h.commit}`}]])}
137
+ `);return}return{entry:v.entry,spec:v.spec,commit:Mn(v.spec.name,i).commit??"unknown"}}function Fr(r,i=0){if(i>3)return[];let o=[];for(let a of We(r,{withFileTypes:!0})){let u=B(r,a.name);if(a.isDirectory()){if(a.name.startsWith("."))continue;o.push(...Fr(u,i+1));continue}if(!a.isFile())continue;if((Mr(u).mode&73)!==0||bc.some((g)=>a.name.endsWith(g)))o.push(u)}return o}var bc=[".py",".sh",".js",".ts",".mjs",".rb",".pl"];function vc(r,i){let o=i.name;if(o===void 0)return process.stdout.write("skills remove needs a name — `skills list` names them\n"),s;let a=B(r,o);if(!te(B(a,fe))){let g=te(r)?We(r,{withFileTypes:!0}).filter((w)=>w.isDirectory()&&te(B(r,w.name,fe))).map((w)=>w.name).join(", "):"";return process.stdout.write(`no skill named ${o}${g===""?"":`. Known: ${g}`}
138
+ `),s}let u=Dr(a),h=me(r)[o];return oc(a,{recursive:!0,force:!0}),Ln(r,o),process.stdout.write(`${l([{label:"removed",value:a},{label:"files",value:String(u)},...h===void 0?[]:[{label:"came from",value:`${h.source} (${h.url}) at ${h.commit}`}]])}
139
139
  `),process.stdout.write(`${d("restart the agent: the catalogue is scanned once at boot")}
140
- `),n}function Kr(r){let i=0;for(let o of He(r,{withFileTypes:!0}))i+=o.isDirectory()?Kr(G(r,o.name)):1;return i}async function et(r){let i=r.onStatus??(()=>{}),o=V(r.env),a=o.filter((h)=>!ce(h.name,r.env));for(let[h,g]of a.entries()){i(`fetching ${g.name} (${h+1} of ${a.length}) — once per machine, shared by every agent`);try{let w=await Qe(g,{...r.env===void 0?{}:{env:r.env},...r.git===void 0?{}:{git:r.git}});i(`${g.name}: ${w.skills} skills`)}catch(w){i(`${g.name} could not be fetched: ${w instanceof t?w.message:String(w)}`)}}let u=o.filter((h)=>ce(h.name,r.env)).map((h)=>({spec:h,entries:be(h,r.env)}));return oo(u)}async function kc(r){return await et({...r,onStatus:(i)=>process.stdout.write(`${i}
141
- `)})}function zr(r,i,o){let a=[];for(let u of r)ve({action:"install",manifestPath:i,name:u,quiet:!0,collect:a,...o.env===void 0?{}:{sandboxEnv:o.env},...o.envOverlay===void 0?{}:{envOverlay:o.envOverlay}});return Sc(a)}function $c(r,i,o){let a=[];for(let u of r)ve({action:"install",manifestPath:i,name:`${u.source}/${u.skill}`,quiet:!0,collect:a,...o.env===void 0?{}:{sandboxEnv:o.env},...o.envOverlay===void 0?{}:{envOverlay:o.envOverlay}});return a}function Sc(r){let i=vt(r);if(process.stdout.write(`${m(`installed ${i.installed.length} of ${i.total} skill${i.total===1?"":"s"}`,!0)}
140
+ `),n}function Dr(r){let i=0;for(let o of We(r,{withFileTypes:!0}))i+=o.isDirectory()?Dr(B(r,o.name)):1;return i}async function nt(r){let i=r.onStatus??(()=>{}),o=G(r.env),a=o.filter((h)=>!ce(h.name,r.env));for(let[h,g]of a.entries()){i(`fetching ${g.name} (${h+1} of ${a.length}) — once per machine, shared by every agent`);try{let w=await tt(g,{...r.env===void 0?{}:{env:r.env},...r.git===void 0?{}:{git:r.git}});i(`${g.name}: ${w.skills} skills`)}catch(w){i(`${g.name} could not be fetched: ${w instanceof t?w.message:String(w)}`)}}let u=o.filter((h)=>ce(h.name,r.env)).map((h)=>({spec:h,entries:ke(h,r.env)}));return co(u)}async function kc(r){return await nt({...r,onStatus:(i)=>process.stdout.write(`${i}
141
+ `)})}function qr(r,i,o){let a=[];for(let u of r)Se({action:"install",manifestPath:i,name:u,quiet:!0,collect:a,...o.env===void 0?{}:{sandboxEnv:o.env},...o.envOverlay===void 0?{}:{envOverlay:o.envOverlay}});return Sc(a)}function $c(r,i,o){let a=[];for(let u of r)Se({action:"install",manifestPath:i,name:`${u.source}/${u.skill}`,quiet:!0,collect:a,...o.env===void 0?{}:{sandboxEnv:o.env},...o.envOverlay===void 0?{}:{envOverlay:o.envOverlay}});return a}function Sc(r){let i=Et(r);if(process.stdout.write(`${p(`installed ${i.installed.length} of ${i.total} skill${i.total===1?"":"s"}`,!0)}
142
142
  `),i.installed.length>0)process.stdout.write(`${c(i.installed.join(", "))}
143
143
  `);for(let o of i.failed)process.stdout.write(`${d(`${o.name} — ${o.reason}`)}
144
- `);if(i.runnable>0)process.stdout.write(`${m("code that came with them")}
144
+ `);if(i.runnable>0)process.stdout.write(`${p("code that came with them")}
145
145
  ${c(`${i.runnable} runnable file${i.runnable===1?"":"s"} across ${i.withCode} skill${i.withCode===1?"":"s"} — \`skills show <agent> <skill>\` names them`)}
146
- `);return i.failed.length}async function Br(r){if(V(r.env).length===0)return process.stdout.write(`no skill sources are configured
146
+ `);return i.failed.length}async function Gr(r){if(G(r.env).length===0)return process.stdout.write(`no skill sources are configured
147
147
 
148
148
  \`${e.slug} sources add <url>\` adds one — a repository holding a skills/ directory.
149
149
  `),s;if(!(ie({plain:r.plain===!0,json:r.json===!0,oneShot:!1}).mode==="rich"&&r.json!==!0)){let _=await kc(r);if(_.length===0)return process.stdout.write(`nothing to show — no catalogue could be read
150
150
 
151
151
  \`${e.slug} sources update\` reports why.
152
- `),s;if(r.json===!0)return _c(_);return Tc(_,B(r.env))}let u=B(r.env);if(u.length===0)return process.stdout.write(`${m("no agent to install into",!0)}
152
+ `),s;if(r.json===!0)return _c(_);return Tc(_,K(r.env))}let u=K(r.env);if(u.length===0)return process.stdout.write(`${p("no agent to install into",!0)}
153
153
  ${c(`\`${e.slug} init\` creates one, then this command installs into it.`)}
154
- `),s;let[{render:h},{createElement:g},{SkillBrowser:w}]=await Promise.all([import("ink"),import("react"),import("./SkillBrowser-yyf2gy0q.js")]),k,S=()=>{},T=new Promise((_)=>{S=_});he(),process.stdout.write(we);let N=h(g(w,{title:Rc,agents:u,load:(_)=>et({...r,onStatus:_}),install:async(_,R)=>vt($c(_,R,r)),onDone:(_)=>{k=_,S()}}),{exitOnCtrlC:!1,...Y()});if(b(()=>N.unmount()),await T,N.unmount(),J(),await ue(),k===void 0)return n;for(let _ of k.failed)process.stderr.write(`${_.name} — ${_.reason}
155
- `);if(k.installed.length>0)process.stdout.write(`${k.installed.length} skill${k.installed.length===1?"":"s"} installed — \`${e.slug} skills list <agent>\` shows them
156
- `);return k.failed.length===k.total&&k.total>0?s:n}function _c(r){return process.stdout.write(`${JSON.stringify({skills:r.filter((i)=>i.entry!==void 0).map((i)=>({ref:`${i.entry?.source}/${i.entry?.skill}`,source:i.entry?.source,skill:i.entry?.skill,tokens:i.entry?.tokens,scripts:i.entry?.scripts.length??0,description:i.entry?.description}))},null,2)}
157
- `),n}function Ec(r){let o=r.reduce((h,g)=>g.kind==="item"?Math.max(h,g.label.length):h,0),a=yn(100,o+12,{nameMax:46}),u=[];for(let h of r){if(h.kind==="source"){u.push(`
158
- ${h.label}`);continue}if(h.kind==="group"){u.push(` ${h.label}`);continue}let g=wn({name:`${h.entry?.source}/${h.label}`,meta:h.meta??"",description:h.description??""},a);u.push(` ${g.name} ${g.meta} ${g.description}`.trimEnd())}return u.join(`
154
+ `),s;let[{render:h},{createElement:g},{SkillBrowser:w}]=await Promise.all([import("ink"),import("react"),import("./SkillBrowser-3qdp8080.js")]),v,S=()=>{},T=new Promise((_)=>{S=_});pe(),process.stdout.write(ve);let L=h(g(w,{title:Rc,agents:u,load:(_)=>nt({...r,onStatus:_}),install:async(_,I)=>Et($c(_,I,r)),onDone:(_)=>{v=_,S()}}),{exitOnCtrlC:!1,...Z()});if(b(()=>L.unmount()),await T,L.unmount(),J(),await ue(),v===void 0)return n;for(let _ of v.failed)process.stderr.write(`${_.name} — ${_.reason}
155
+ `);if(v.installed.length>0)process.stdout.write(`${v.installed.length} skill${v.installed.length===1?"":"s"} installed — \`${e.slug} skills list <agent>\` shows them
156
+ `);return v.failed.length===v.total&&v.total>0?s:n}function _c(r){return process.stdout.write(`${JSON.stringify({skills:r.filter((i)=>i.entry!==void 0).map((i)=>({ref:`${i.entry?.source}/${i.entry?.skill}`,source:i.entry?.source,skill:i.entry?.skill,tokens:i.entry?.tokens,scripts:i.entry?.scripts.length??0,description:i.entry?.description}))},null,2)}
157
+ `),n}function Ec(r){let o=r.reduce((h,g)=>g.kind==="item"?Math.max(h,g.label.length):h,0),a=xn(100,o+12,{nameMax:46}),u=[];for(let h of r){if(h.kind==="source"){u.push(`
158
+ ${h.label}`);continue}if(h.kind==="group"){u.push(` ${h.label}`);continue}let g=En({name:`${h.entry?.source}/${h.label}`,meta:h.meta??"",description:h.description??""},a);u.push(` ${g.name} ${g.meta} ${g.description}`.trimEnd())}return u.join(`
159
159
  `)}function Tc(r,i){process.stdout.write(`${Ec(r)}
160
- `);let o=r.find((u)=>u.entry!==void 0)?.entry,a=i[0]?.ref??"<agent>";return process.stdout.write(`${m("install")}
160
+ `);let o=r.find((u)=>u.entry!==void 0)?.entry,a=i[0]?.ref??"<agent>";return process.stdout.write(`${p("install")}
161
161
  ${c(`${e.slug} skills install ${a} ${o?.source??"anthropic"}/${o?.skill??"pdf"}`)}
162
162
  ${c(`${e.slug} skills — at a terminal, ticks several at once`,2)}
163
- `),n}var Rc=`${e.name} ${A}`;
164
- export{I,O,W,C,q,P,ar,Je,lr,jt,V,Fr,Ur,jr,In,ce,Qe,be,On,ve,et,zr,Br};
163
+ `),n}var Rc=`${e.name} ${R}`;
164
+ export{A,O,Y,N,X,C,fr,et,hr,Ht,G,Kr,Hr,Wr,Mn,ce,tt,ke,Ln,Se,nt,qr,Gr};
165
165
 
166
- //# debugId=060462C48FE06EFA64756E2164756E21
167
- //# sourceMappingURL=index-fvhg0xyd.js.map
166
+ //# debugId=67A2CE6B60D1C5FD64756E2164756E21
167
+ //# sourceMappingURL=index-ty24n0jh.js.map