dispach 0.1.2 → 0.2.0-pilot.1
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.
- package/README.md +196 -118
- package/dist/APEv2Parser-2wqk09q7.js +5 -0
- package/dist/APEv2Parser-2wqk09q7.js.map +9 -0
- package/dist/AiffParser-zw4g2bdd.js +5 -0
- package/dist/AiffParser-zw4g2bdd.js.map +12 -0
- package/dist/App-ez7ve0yp.js +11 -0
- package/dist/{App-b1yrwrcq.js.map → App-ez7ve0yp.js.map} +6 -7
- package/dist/AsfParser-2hfcf5z2.js +5 -0
- package/dist/AsfParser-2hfcf5z2.js.map +14 -0
- package/dist/ConfigEditor-aamadrx3.js +6 -0
- package/dist/{ConfigEditor-n8hdw6r7.js.map → ConfigEditor-aamadrx3.js.map} +2 -2
- package/dist/DsdiffParser-n8smktvb.js +5 -0
- package/dist/DsdiffParser-n8smktvb.js.map +11 -0
- package/dist/DsfParser-npmjp4vr.js +5 -0
- package/dist/DsfParser-npmjp4vr.js.map +11 -0
- package/dist/FlacParser-xpbs2zmb.js +5 -0
- package/dist/FlacParser-xpbs2zmb.js.map +9 -0
- package/dist/KeyProbe-4fp152yv.js +5 -0
- package/dist/{KeyProbe-9jjeze5r.js.map → KeyProbe-4fp152yv.js.map} +2 -2
- package/dist/MP4Parser-es3afcmw.js +5 -0
- package/dist/MP4Parser-es3afcmw.js.map +12 -0
- package/dist/MatroskaParser-kxysj649.js +5 -0
- package/dist/MatroskaParser-kxysj649.js.map +13 -0
- package/dist/MpegParser-b3rr7b0f.js +5 -0
- package/dist/MpegParser-b3rr7b0f.js.map +13 -0
- package/dist/MusepackParser-sgjzmq0r.js +5 -0
- package/dist/MusepackParser-sgjzmq0r.js.map +16 -0
- package/dist/OggParser-x8h54ynf.js +5 -0
- package/dist/OggParser-x8h54ynf.js.map +18 -0
- package/dist/Picker-rq015kzc.js +5 -0
- package/dist/{Picker-hfeh1g6m.js.map → Picker-rq015kzc.js.map} +2 -2
- package/dist/SessionPicker-03zyvd2f.js +5 -0
- package/dist/{SessionPicker-zyqkg4dn.js.map → SessionPicker-03zyvd2f.js.map} +2 -2
- package/dist/SkillBrowser-8s8rjv98.js +5 -0
- package/dist/{SkillBrowser-3qdp8080.js.map → SkillBrowser-8s8rjv98.js.map} +2 -2
- package/dist/WavPackParser-w515nnw2.js +5 -0
- package/dist/WavPackParser-w515nnw2.js.map +11 -0
- package/dist/WaveParser-sb0w9m20.js +5 -0
- package/dist/WaveParser-sb0w9m20.js.map +13 -0
- package/dist/WizardApp-wr1tftcr.js +5 -0
- package/dist/{WizardApp-vzpbydy3.js.map → WizardApp-wr1tftcr.js.map} +3 -3
- package/dist/agents.d.ts +19 -3
- package/dist/agents.d.ts.map +1 -1
- package/dist/channels-gx951qdp.js +31 -0
- package/dist/channels-gx951qdp.js.map +10 -0
- package/dist/channels.d.ts +26 -0
- package/dist/channels.d.ts.map +1 -0
- package/dist/client.js +11 -11
- package/dist/client.js.map +3 -3
- package/dist/config-wvjeejgd.js +24 -0
- package/dist/{config-g7za9x13.js.map → config-wvjeejgd.js.map} +2 -2
- package/dist/credential-10dn3fxj.js +19 -0
- package/dist/{credential-npr6z8c8.js.map → credential-10dn3fxj.js.map} +1 -1
- package/dist/daemon.d.ts.map +1 -1
- package/dist/index-10009hp8.js +11 -0
- package/dist/index-10009hp8.js.map +11 -0
- package/dist/index-1xwrkwh5.js +14 -0
- package/dist/index-1xwrkwh5.js.map +50 -0
- package/dist/index-34p39yfc.js +47 -0
- package/dist/index-34p39yfc.js.map +15 -0
- package/dist/index-3y96s740.js +6 -0
- package/dist/{index-hwpvhaza.js.map → index-3y96s740.js.map} +1 -1
- package/dist/index-4ybeefmn.js +6 -0
- package/dist/index-4ybeefmn.js.map +11 -0
- package/dist/index-59z88wrb.js +6 -0
- package/dist/{index-h9mw7b9d.js.map → index-59z88wrb.js.map} +2 -2
- package/dist/index-5fwzn21m.js +6 -0
- package/dist/{index-gz9x25tz.js.map → index-5fwzn21m.js.map} +2 -2
- package/dist/index-6dvnfk8y.js +6 -0
- package/dist/index-6dvnfk8y.js.map +10 -0
- package/dist/index-6p70fnb7.js +153 -0
- package/dist/index-6p70fnb7.js.map +20 -0
- package/dist/index-6s471ydn.js +12 -0
- package/dist/{index-j55s3ehk.js.map → index-6s471ydn.js.map} +2 -2
- package/dist/index-87wcawta.js +6 -0
- package/dist/{index-0d93hyfc.js.map → index-87wcawta.js.map} +2 -2
- package/dist/index-92gfcbw0.js +6 -0
- package/dist/index-92gfcbw0.js.map +9 -0
- package/dist/index-a0h0p20f.js +991 -0
- package/dist/{index-tv4yv7d2.js.map → index-a0h0p20f.js.map} +27 -23
- package/dist/index-bamw24xc.js +6 -0
- package/dist/{index-6q4wf8e3.js.map → index-bamw24xc.js.map} +1 -1
- package/dist/index-c8ge88a9.js +12 -0
- package/dist/{index-258d8bzg.js.map → index-c8ge88a9.js.map} +4 -3
- package/dist/index-cb2q8nae.js +6 -0
- package/dist/index-cb2q8nae.js.map +13 -0
- package/dist/index-ct6bw0a6.js +6 -0
- package/dist/{index-4z7axw4r.js.map → index-ct6bw0a6.js.map} +1 -1
- package/dist/index-cz6yjxyz.js +10 -0
- package/dist/index-cz6yjxyz.js.map +42 -0
- package/dist/index-d0c5abkw.js +6 -0
- package/dist/{index-vgc3y3rm.js.map → index-d0c5abkw.js.map} +3 -3
- package/dist/index-d0vagham.js +31 -0
- package/dist/index-d0vagham.js.map +188 -0
- package/dist/index-d0zxvr99.js +90 -0
- package/dist/index-d0zxvr99.js.map +13 -0
- package/dist/{index-s9mbq7h6.js → index-d9c97ver.js} +4 -4
- package/dist/{index-s9mbq7h6.js.map → index-d9c97ver.js.map} +1 -1
- package/dist/index-e508e0vt.js +6 -0
- package/dist/{index-tf71ap9v.js.map → index-e508e0vt.js.map} +1 -1
- package/dist/index-esq0knqx.js +6 -0
- package/dist/index-esq0knqx.js.map +10 -0
- package/dist/index-featyhps.js +6 -0
- package/dist/index-featyhps.js.map +10 -0
- package/dist/index-fnq44zdt.js +45 -0
- package/dist/index-fnq44zdt.js.map +74 -0
- package/dist/index-gmn80dwc.js +7 -0
- package/dist/{index-02dn6m2j.js.map → index-gmn80dwc.js.map} +2 -2
- package/dist/index-gwhx69qs.js +66 -0
- package/dist/index-gwhx69qs.js.map +12 -0
- package/dist/index-kjgzhf3w.js +9 -0
- package/dist/{index-6p999cx4.js.map → index-kjgzhf3w.js.map} +4 -6
- package/dist/index-m68cd91a.js +12 -0
- package/dist/index-m68cd91a.js.map +23 -0
- package/dist/{index-3g3ny01d.js → index-mhmgw54j.js} +4 -4
- package/dist/{index-3g3ny01d.js.map → index-mhmgw54j.js.map} +1 -1
- package/dist/{index-gme2egyq.js → index-qm612hwa.js} +4 -4
- package/dist/{index-gme2egyq.js.map → index-qm612hwa.js.map} +1 -1
- package/dist/{index-j7gyr5nx.js → index-qwntpbwe.js} +7 -7
- package/dist/{index-j7gyr5nx.js.map → index-qwntpbwe.js.map} +1 -1
- package/dist/index-qx3xdk4x.js +6 -0
- package/dist/{index-d4x6yvqh.js.map → index-qx3xdk4x.js.map} +3 -4
- package/dist/{index-4cf6v9nb.js → index-rh0meegk.js} +4 -4
- package/dist/{index-4cf6v9nb.js.map → index-rh0meegk.js.map} +1 -1
- package/dist/index-ryb159ff.js +9 -0
- package/dist/{index-ff514z3y.js.map → index-ryb159ff.js.map} +3 -5
- package/dist/{index-ammv5st7.js → index-s6zfpyqa.js} +6 -6
- package/dist/{index-ammv5st7.js.map → index-s6zfpyqa.js.map} +1 -1
- package/dist/index-s9va2kmc.js +429 -0
- package/dist/index-s9va2kmc.js.map +11 -0
- package/dist/index-v5dmsgpx.js +7 -0
- package/dist/index-v5dmsgpx.js.map +11 -0
- package/dist/index-vaj3mn3a.js +6 -0
- package/dist/index-vaj3mn3a.js.map +14 -0
- package/dist/index-vy0rbzws.js +6 -0
- package/dist/{index-fex44816.js.map → index-vy0rbzws.js.map} +2 -2
- package/dist/index-w0s77wfx.js +6 -0
- package/dist/{index-v8e92nfw.js.map → index-w0s77wfx.js.map} +1 -1
- package/dist/index-wx1jzjzr.js +6 -0
- package/dist/{index-qdbq8crg.js.map → index-wx1jzjzr.js.map} +2 -2
- package/dist/index-xbn26c8g.js +126 -0
- package/dist/index-xbn26c8g.js.map +14 -0
- package/dist/index-ytvwyp6k.js +6 -0
- package/dist/{index-9r0wyj6w.js.map → index-ytvwyp6k.js.map} +2 -2
- package/dist/{index-cqqb6gaq.js → index-yvnwpxbb.js} +5 -5
- package/dist/{index-cqqb6gaq.js.map → index-yvnwpxbb.js.map} +1 -1
- package/dist/index.js +379 -448
- package/dist/index.js.map +26 -28
- package/dist/init.d.ts.map +1 -1
- package/dist/lib/agent-secrets.d.ts +38 -0
- package/dist/lib/agent-secrets.d.ts.map +1 -0
- package/dist/lib/agent-template.d.ts +54 -0
- package/dist/lib/agent-template.d.ts.map +1 -0
- package/dist/lib/channel-actions.d.ts +103 -0
- package/dist/lib/channel-actions.d.ts.map +1 -0
- package/dist/lib/chat-frame.d.ts +12 -1
- package/dist/lib/chat-frame.d.ts.map +1 -1
- package/dist/lib/commands.d.ts +13 -0
- package/dist/lib/commands.d.ts.map +1 -1
- package/dist/lib/const.d.ts +1 -1
- package/dist/lib/daemon-plan.d.ts.map +1 -1
- package/dist/lib/help.d.ts.map +1 -1
- package/dist/lib/host-actions.d.ts +121 -0
- package/dist/lib/host-actions.d.ts.map +1 -0
- package/dist/lib/init-flow.d.ts +32 -0
- package/dist/lib/init-flow.d.ts.map +1 -1
- package/dist/lib/init-whatsapp.d.ts +52 -0
- package/dist/lib/init-whatsapp.d.ts.map +1 -0
- package/dist/lib/plugin-install.d.ts +120 -0
- package/dist/lib/plugin-install.d.ts.map +1 -0
- package/dist/lib/providers.d.ts.map +1 -1
- package/dist/lib/provision.d.ts +13 -0
- package/dist/lib/provision.d.ts.map +1 -1
- package/dist/lib/readme-table.d.ts +15 -0
- package/dist/lib/readme-table.d.ts.map +1 -0
- package/dist/lib/sandbox.d.ts +17 -0
- package/dist/lib/sandbox.d.ts.map +1 -1
- package/dist/lib/schema.d.ts +34 -1
- package/dist/lib/schema.d.ts.map +1 -1
- package/dist/lib/subcommand.d.ts.map +1 -1
- package/dist/lib/web-url.d.ts +15 -0
- package/dist/lib/web-url.d.ts.map +1 -0
- package/dist/lib/wizard.d.ts.map +1 -1
- package/dist/memory.d.ts.map +1 -1
- package/dist/model.d.ts.map +1 -1
- package/dist/plugins.d.ts +27 -8
- package/dist/plugins.d.ts.map +1 -1
- package/dist/restart.d.ts +21 -0
- package/dist/restart.d.ts.map +1 -0
- package/dist/run.d.ts.map +1 -1
- package/dist/schedules.d.ts.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/sessions.d.ts.map +1 -1
- package/dist/skills.d.ts.map +1 -1
- package/dist/status.d.ts +16 -0
- package/dist/status.d.ts.map +1 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/validate.d.ts.map +1 -1
- package/dist/web-61cjhpv2.js +14 -0
- package/dist/{web-vkb16r62.js.map → web-61cjhpv2.js.map} +3 -3
- package/dist/web.d.ts +2 -13
- package/dist/web.d.ts.map +1 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/wrapper-9msjh1xg.js +5 -0
- package/dist/wrapper-9msjh1xg.js.map +9 -0
- package/package.json +6 -3
- package/dist/App-b1yrwrcq.js +0 -11
- package/dist/ConfigEditor-n8hdw6r7.js +0 -6
- package/dist/KeyProbe-9jjeze5r.js +0 -5
- package/dist/Picker-hfeh1g6m.js +0 -5
- package/dist/SessionPicker-zyqkg4dn.js +0 -5
- package/dist/SkillBrowser-3qdp8080.js +0 -5
- package/dist/WizardApp-vzpbydy3.js +0 -5
- package/dist/config-g7za9x13.js +0 -24
- package/dist/credential-npr6z8c8.js +0 -19
- package/dist/index-02dn6m2j.js +0 -7
- package/dist/index-0d93hyfc.js +0 -6
- package/dist/index-1c5113t4.js +0 -66
- package/dist/index-1c5113t4.js.map +0 -12
- package/dist/index-258d8bzg.js +0 -12
- package/dist/index-4z7axw4r.js +0 -6
- package/dist/index-6p999cx4.js +0 -9
- package/dist/index-6q4wf8e3.js +0 -6
- package/dist/index-9r0wyj6w.js +0 -6
- package/dist/index-d4x6yvqh.js +0 -6
- package/dist/index-fecm8xe7.js +0 -77
- package/dist/index-fecm8xe7.js.map +0 -12
- package/dist/index-fex44816.js +0 -6
- package/dist/index-ff514z3y.js +0 -14
- package/dist/index-gz9x25tz.js +0 -6
- package/dist/index-h9mw7b9d.js +0 -6
- package/dist/index-hwpvhaza.js +0 -6
- package/dist/index-j55s3ehk.js +0 -12
- package/dist/index-mtn0g9vc.js +0 -7
- package/dist/index-mtn0g9vc.js.map +0 -11
- package/dist/index-qdbq8crg.js +0 -6
- package/dist/index-tf71ap9v.js +0 -6
- package/dist/index-ttwyrdjs.js +0 -427
- package/dist/index-ttwyrdjs.js.map +0 -11
- package/dist/index-tv4yv7d2.js +0 -903
- package/dist/index-ty24n0jh.js +0 -167
- package/dist/index-ty24n0jh.js.map +0 -19
- package/dist/index-v8e92nfw.js +0 -6
- package/dist/index-vgc3y3rm.js +0 -6
- package/dist/index-whaw4b18.js +0 -6
- package/dist/index-whaw4b18.js.map +0 -10
- package/dist/web-vkb16r62.js +0 -14
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{be,Be,_,O,fA,Sr,Sn,Dn,RA,ii,ko}from"./index-gwhx69qs.js";import{mA,SA,Ee,vt}from"./index-a0h0p20f.js";class k extends Error{status;retryable;retryAfterMs;detail;constructor(e){super(e.message);this.name="TelegramApiError",this.status=e.status,this.retryable=e.retryable,this.retryAfterMs=e.retryAfterMs,this.detail=e.detail}}var ln="https://api.telegram.org";class J{#e;#t;#i;constructor(e){this.#e=e.token,this.#t=e.fetch??((t,n)=>fetch(t,n)),this.#i=(e.baseUrl??ln).replace(/\/+$/,"")}async call(e,t,n){let r;try{r=await this.#t(`${this.#i}/bot${this.#e}/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t??{}),...n===void 0?{}:{signal:n}})}catch(s){throw new k({message:`Telegram ${e} did not complete: ${s instanceof Error?s.message:String(s)}`,status:0,retryable:!0,detail:{code:"telegram_unreachable",message:`Could not reach the Telegram Bot API for ${e}.`,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 i=await r.json().catch(()=>({}));if(r.ok&&i.ok&&i.result!==void 0)return i.result;throw un(e,r.status,i)}getMe(e){return this.call("getMe",{},e)}getUpdates(e,t){return this.call("getUpdates",{offset:e.offset,timeout:e.timeout,limit:e.limit??100,allowed_updates:["message"]},t)}sendMessage(e,t){return this.call("sendMessage",{chat_id:e.chatId,text:e.text,...e.threadId===void 0?{}:{message_thread_id:e.threadId}},t)}sendChatAction(e){return this.call("sendChatAction",{chat_id:e.chatId,action:"typing",...e.threadId===void 0?{}:{message_thread_id:e.threadId}})}setWebhook(e,t){return this.call("setWebhook",{url:e.url,allowed_updates:["message"],...e.secretToken===void 0?{}:{secret_token:e.secretToken},...e.dropPending===void 0?{}:{drop_pending_updates:e.dropPending}},t)}deleteWebhook(e){return this.call("deleteWebhook",{},e)}}function un(e,t,n){let r=n.description??`HTTP ${t}`,i=n.error_code??t,s=n.parameters?.retry_after;if(i===429)return new k({message:`Telegram rate-limited ${e}: ${r}`,status:i,retryable:!0,...s===void 0?{}:{retryAfterMs:s*1000},detail:{code:"telegram_rate_limited",message:`Telegram rate-limited ${e}.`,hint:s===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 ${s}s. The outbox honours that verbatim rather than applying its own backoff.`}});if(i===401)return new k({message:`Telegram rejected the bot token on ${e}: ${r}`,status:i,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(i===409)return new k({message:`Telegram reports a conflicting ${e}: ${r}`,status:i,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(i===400&&/too long/i.test(r))return new k({message:`Telegram refused ${e}: ${r}`,status:i,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 o=i===400||i===403;return new k({message:`Telegram refused ${e}: ${r}`,status:i,retryable:!o,detail:{code:o?"telegram_refused":"telegram_error",message:`Telegram refused ${e}: ${r}`,hint:o?"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 fn=4096,pn=30,$e=[1000,2000,5000,15000,30000],mn=350;class Te{id;type="telegram";limits={maxMessageChars:fn,idempotentSend:!1,minSendIntervalMs:mn};#e;#t;#i;#a;#c;#r=0;#n=!1;#s;#o;constructor(e){this.id=e.id,this.#e=e.api??new J({token:e.token}),this.#t=e.mode,this.#i=e.webhookUrl,this.#a=e.secretToken}async start(e){if(this.#n)return;if(this.#n=!0,this.#c=e,this.#s=new AbortController,this.#t==="webhook"){let t=this.#i;if(t===void 0||t===""){e.status("error","no webhookUrl"),e.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:t,...this.#a===void 0?{}:{secretToken:this.#a}}),e.status("connected",`webhook at ${t}`)}catch(n){e.status("error",n instanceof Error?n.message:String(n)),e.error(q(n,`registering the webhook for channel "${this.id}"`))}return}this.#o=this.#d(e,this.#s.signal)}async stop(){if(!this.#n)return;this.#n=!1,this.#s?.abort(),await this.#o?.catch(()=>{}),this.#o=void 0,this.#c?.status("disconnected"),this.#c=void 0}async send(e,t){let n=Se(e.thread);try{let r=await this.#e.sendMessage({chatId:e.recipient,text:e.text,...n===void 0?{}:{threadId:n}},t);return{ok:!0,providerMessageId:String(r.message_id)}}catch(r){if(r instanceof k)return{ok:!1,retryable:r.retryable,error:r.detail,...r.retryAfterMs===void 0?{}:{retryAfterMs:r.retryAfterMs}};return{ok:!1,retryable:!0,error:{code:"telegram_send_failed",message:r instanceof Error?r.message:String(r),hint:"An unclassified failure from the Telegram transport. Retried, because a failure nobody recognised is not a failure known to be permanent."}}}}async typing(e,t){let n=Se(t);await this.#e.sendChatAction({chatId:e,...n===void 0?{}:{threadId:n}})}async webhook(e){if(this.#a!==void 0){let r=e.headers["x-telegram-bot-api-secret-token"]??"";if(!wn(r,this.#a))return{status:401,detail:"bad secret token"}}let t=this.#c;if(t===void 0)return{status:503,detail:"channel not started"};let n=e.body;if(n===void 0||typeof n!=="object")return{status:400,detail:"not an update"};return this.#h(t,n),{status:200}}async#d(e,t){let n=0,r=!1;try{await this.#e.deleteWebhook(t)}catch{}try{let i=await this.#e.getMe(t);r=!0,e.status("connected",i.username===void 0?"long-poll":`@${i.username}, long-poll`)}catch(i){if(t.aborted)return;e.status("error",i instanceof Error?i.message:String(i)),e.error(q(i,`checking the bot token for channel "${this.id}"`))}while(this.#n&&!t.aborted)try{let i=await this.#e.getUpdates({offset:this.#r,timeout:pn},t);if(n>0)n=0,r=!0,e.status("connected","polling resumed");else if(!r)r=!0,e.status("connected","long-poll");for(let s of i)this.#r=Math.max(this.#r,s.update_id+1),this.#h(e,s)}catch(i){if(t.aborted)return;let s=$e[Math.min(n,$e.length-1)]??1000;if(n+=1,n===1||n%8===0)e.status("error",i instanceof Error?i.message:String(i)),e.error(q(i,`polling channel "${this.id}"`));await yn(s,t)}}#h(e,t){let n=t.message;if(n===void 0)return;let r=n.text??n.caption??"";if(r.trim()==="")return;if(n.from?.is_bot===!0)return;e.receive(gn(n,r))}}function gn(e,t){let n=e.from?.username,r=[e.from?.first_name,e.from?.last_name].filter(Boolean).join(" ");return{providerMessageId:`${e.chat.id}:${e.message_id}`,peerId:String(e.chat.id),...n===void 0?{}:{senderHandle:`@${n}`},...r===""?{}:{senderName:r},...e.message_thread_id===void 0?{}:{thread:String(e.message_thread_id)},text:t,receivedAt:new Date(e.date*1000).toISOString()}}function Se(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function q(e,t){if(e instanceof k)return e.detail;return{code:"telegram_channel_error",message:`${t} failed: ${e instanceof Error?e.message:String(e)}`,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 wn(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function yn(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}var V=(e)=>{let t=e.config,n=I(t,"tokenEnv")??"TELEGRAM_BOT_TOKEN",r=e.env[n];if(r===void 0||r==="")throw new _({code:"telegram_token_missing",message:`Channel "${e.id}" needs ${n}, which is not set.`,hint:`Export ${n}, or add it to the .env beside the manifest — then restart the agent. Get a token from @BotFather with /newbot. The agent starts either way: a channel is optional, so this channel is reported broken rather than blocking the load. It is refused here rather than at the first poll because an unset variable is a configuration mistake and needs no network round trip to discover.`,field:`channels[${e.id}].tokenEnv`});let i=I(t,"mode")??"longpoll";if(i!=="longpoll"&&i!=="webhook")throw new _({code:"telegram_mode_invalid",message:`Channel "${e.id}" declares mode "${i}".`,hint:"mode is longpoll or webhook, and the agent starts either way with this channel reported broken. 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[${e.id}].mode`});let s=I(t,"secretTokenEnv"),o=s===void 0?void 0:e.env[s];if(s!==void 0&&(o===void 0||o===""))throw new _({code:"telegram_secret_missing",message:`Channel "${e.id}" names secretTokenEnv ${s}, which is not set.`,hint:`Export ${s} 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[${e.id}].secretTokenEnv`});let a=I(t,"apiBaseUrl"),c=I(t,"webhookUrl");return new Te({id:e.id,token:r,mode:i,...c===void 0?{}:{webhookUrl:c},...o===void 0||o===""?{}:{secretToken:o},...a===void 0?{}:{api:new J({token:r,baseUrl:a})}})};function I(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var bn="0.1.0",Re={name:"telegram",version:bn,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["api.telegram.org"]},{kind:"env",vars:["TELEGRAM_BOT_TOKEN"]}],setup(e){e.defineChannel("telegram",V)}};import{isAbsolute as vn,resolve as kn}from"node:path";import{chmodSync as xe,mkdirSync as _n,readdirSync as $n,rmSync as Tn}from"node:fs";import{join as En}from"node:path";var An=65536,Rn=1000,Ce=[1000,2000,5000,15000,30000,60000],xn=3,Cn=512,Ie=60000,In=180000,Nn=3000,On=401,Mn={code:"whatsapp_bun_unsupported",message:"WhatsApp pairing does not complete under Bun — the socket opens and the handshake never finishes.",hint:"Measured against the same bundle: it pairs under Node in about two seconds and never under Bun. Every shipped install (npm, brew, the container) runs under Node; this process is running from a checkout with `bun run`. Use `node` — or the installed command — instead. It keeps trying regardless, in case the cause is fixed upstream."};function Ne(e){let t=e.authState?.creds;if(t===void 0)return!0;return t.registered===!0||t.account!==void 0&&t.account!==null}function Oe(){return typeof globalThis.Bun<"u"}class Pe{id;type="whatsapp";limits={maxMessageChars:An,idempotentSend:!1,minSendIntervalMs:Rn};alwaysAllow;#e;#t;#i;#a;#c;#r;#n;#s=!1;#o=0;#d=!1;#h=!0;#l=0;#f=!1;#p=new Set;#m=[];#g;constructor(e){this.id=e.id,this.#e=e.authDir,this.#t=e.pairWith,this.#i=e.deviceName,this.alwaysAllow=e.pairWith===void 0||e.pairWith===""?[]:[e.pairWith],this.#a=e.pairingDelayMs??Nn,this.#c=e.api}async start(e){if(this.#s)return;if(this.#s=!0,this.#r=e,Oe())e.error(Mn);this.#g=this.#b(e)}async stop(){if(!this.#s)return;this.#s=!1;try{this.#n?.end()}catch{}this.#n=void 0,this.#u?.(),this.#u=void 0,await this.#g?.catch(()=>{}),this.#g=void 0,this.#r?.status("disconnected"),this.#r=void 0}async send(e){let t=this.#n;if(t===void 0)return{ok:!1,retryable:!0,error:{code:"whatsapp_not_connected",message:`Channel "${this.id}" is not connected to WhatsApp.`,hint:"The reconnect loop keeps trying and the outbox holds this message. If it never connects, the pairing was probably revoked — check the channel's status, which carries the QR when one is waiting to be scanned."}};try{let r=(await t.sendMessage(Me(e.recipient),{text:e.text}))?.key?.id;if(r!==void 0&&r!==null){if(this.#m.push(r),this.#m.length>Cn)this.#m.shift()}return r===void 0||r===null?{ok:!0}:{ok:!0,providerMessageId:r}}catch(n){return{ok:!1,retryable:!0,error:{code:"whatsapp_send_failed",message:n instanceof Error?n.message:String(n),hint:"Retried, because an unclassified failure from an unofficial client is not one known to be permanent. A recipient that does not exist on WhatsApp fails this way too, and that one will not recover — check the number against `allowFrom`."}}}}async reset(){this.#y();try{this.#n?.end()}catch{}this.#n=void 0,this.#o=0,this.#r?.status("disconnected","unpaired — scan the next QR to link a device"),this.#u?.(),this.#u=void 0}async typing(e){await this.#n?.sendPresenceUpdate("composing",Me(e))}async#b(e){while(this.#s&&!this.#f){try{let t=this.#c??await jn();_n(this.#e,{recursive:!0,mode:448}),this.#d=this.#t!==void 0&&this.#t!=="";let n=await t.connect({authDir:this.#e,...this.#i===void 0?{}:{deviceName:this.#i},onUpdate:(r)=>this.#_(e,r),onCreds:()=>this.#T(),onMessages:(r)=>this.#$(e,r)});this.#n=n,this.#h=Ne(n),await this.#v(e,n),await this.#k()}catch(t){if(!this.#s)return;this.#w(e,t)}if(!this.#s)return;await Le(this.#S())}}async#v(e,t){let n=this.#t;if(n===void 0||n==="")return;if(Ne(t))return;if(typeof t.requestPairingCode!=="function"){e.status("needs_input",`channel "${this.id}" is set to pair by code and this build of baileys cannot`,{kind:"qr",payload:"",expiresAt:new Date(Date.now()+Ie).toISOString()});return}try{if(await Le(this.#a),!this.#s)return;let r=await t.requestPairingCode(n);e.status("needs_input",`enter this code on WhatsApp for +${n} — Linked devices › Link with phone number`,{kind:"pairing_code",payload:r,expiresAt:new Date(Date.now()+In).toISOString()})}catch(r){this.#d=!1,this.#w(e,r)}}#k(){if(!this.#s)return Promise.resolve();return new Promise((e)=>{this.#u=e})}#u;#_(e,t){if(t.qr!==void 0&&t.qr!==""&&!this.#d){e.status("needs_input",`scan to pair channel "${this.id}"`,{kind:"qr",payload:t.qr,expiresAt:new Date(Date.now()+Ie).toISOString()});return}if(t.connection==="open"){this.#l=0,this.#o=0;let n=this.#n?.user;if(this.#p.clear(),n?.id!==void 0)this.#p.add(L(n.id));if(n?.lid!==void 0)this.#p.add(L(n.lid));e.status("connected","paired");return}if(t.connection==="close"){if(t.lastDisconnect?.error?.output?.statusCode===On)if(this.#y(),this.#h)this.#l=0,e.status("disconnected","logged out — pairing again, scan the next QR"),e.error({code:"whatsapp_logged_out",message:`Channel "${this.id}" was logged out of WhatsApp.`,hint:"The stored session was revoked — from the phone's linked-devices screen, or by WhatsApp. The saved credentials have been deleted and a new QR follows; scan it to pair again."});else if(this.#l+=1,this.#o+=1,this.#l>=xn)this.#f=!0,e.status("error",`pairing refused ${this.#l} times — not asking again`),e.error({code:"whatsapp_pairing_refused",message:`WhatsApp refused ${this.#l} pairing attempts for channel "${this.id}" and none completed.`,hint:Oe()?"This is what the Bun limitation looks like from the outside: a code is issued and invalidated seconds later. Pair using the npm-installed package, whose bin runs under Node, then bring the paired session back. Retrying here only spends failed pairings against the number.":this.#i!==void 0?`deviceName is set ("${this.#i}"), and some accounts refuse a non-standard device name under pairing-by-code. Remove deviceName from the channel and pair again; check the number too. Repeated failed pairings are the thing that gets an account restricted, so this stops rather than continuing.`:"Check that the number is the one WhatsApp is registered to, in digits with no +. Repeated failed pairings are the thing that gets an account restricted, so this stops rather than continuing."});else e.status("disconnected","pairing refused — trying once more");else if(this.#o+=1,this.#o===1||this.#o%8===0)e.status("disconnected",t.lastDisconnect?.error?.message??"connection closed");this.#n=void 0,this.#u?.(),this.#u=void 0}}#$(e,t){if(t.type!=="notify")return;for(let n of t.messages){let r=Pn(n,{ownJids:this.#p,sentIds:this.#m});if(r!==void 0)e.receive(r)}}#w(e,t){if(this.#o+=1,this.#o!==1&&this.#o%8!==0)return;e.status("error",t instanceof Error?t.message:String(t)),e.error({code:"whatsapp_connect_failed",message:`Channel "${this.id}" could not connect: ${t instanceof Error?t.message:String(t)}`,hint:"The loop keeps retrying and the rest of the runtime is unaffected. If it never connects, check network access and whether the paired number is still linked in WhatsApp's linked-devices screen."})}#S(){let e=Math.min(this.#o,Ce.length-1);return Ce[e]??1000}#y(){Tn(this.#e,{recursive:!0,force:!0})}#T(){try{xe(this.#e,448);for(let e of $n(this.#e))xe(En(this.#e,e),384)}catch{}}}var Ln={ownJids:new Set,sentIds:[]};function Pn(e,t=Ln){let n=e.key?.remoteJid;if(n===null||n===void 0||n==="")return;let r=e.key?.id;if(e.key?.fromMe===!0){if(r!==null&&r!==void 0&&t.sentIds.includes(r))return;let h=L(n),u=e.key?.remoteJidAlt,l=u===null||u===void 0?void 0:L(u);if(!(t.ownJids.has(h)||l!==void 0&&t.ownJids.has(l)))return}if(n.endsWith("@g.us")||n==="status@broadcast")return;let i=e.message,s=i?.conversation??i?.extendedTextMessage?.text??i?.imageMessage?.caption??i?.videoMessage?.caption??i?.documentMessage?.caption??"";if(s.trim()==="")return;let o=e.messageTimestamp,a=typeof o==="number"?o:typeof o?.toNumber==="function"?o.toNumber():void 0,c=Un(n,e.key?.remoteJidAlt),d=e.pushName;return{...r===null||r===void 0?{}:{providerMessageId:r},peerId:c,senderHandle:Ue(c),...d===null||d===void 0||d===""?{}:{senderName:d},text:s,receivedAt:new Date(a===void 0?Date.now():a*1000).toISOString()}}function Un(e,t){if(e.endsWith("@s.whatsapp.net"))return e;if(t?.endsWith("@s.whatsapp.net")===!0)return t;return e}function L(e){let t=e.indexOf("@");if(t===-1)return e;let n=e.slice(0,t),r=n.indexOf(":");return`${r===-1?n:n.slice(0,r)}${e.slice(t)}`}function Ue(e){let t=e.indexOf("@"),n=t===-1?e:e.slice(0,t),r=n.indexOf(":");return r===-1?n:n.slice(0,r)}function Me(e){return e.includes("@")?e:`${Ue(e)}@s.whatsapp.net`}async function jn(){let e=await import("./index-d0vagham.js"),t=e.default,n=typeof t==="function"?t.default:void 0,r=typeof t==="function"?n??t:e.makeWASocket,i=e.useMultiFileAuthState??(typeof t==="function"?t.useMultiFileAuthState:void 0);if(typeof r!=="function"||typeof i!=="function")throw Error("the installed baileys package does not export makeWASocket and useMultiFileAuthState");return{connect:async({authDir:s,deviceName:o,onUpdate:a,onCreds:c,onMessages:d})=>{let{state:h,saveCreds:u}=await i(s),l=r({auth:h,printQRInTerminal:!1,browser:[o??"Ubuntu","Chrome","22.04.4"],logger:Fn(),markOnlineOnConnect:!1});return l.ev.on("connection.update",a),l.ev.on("creds.update",async()=>{await u(),await c()}),l.ev.on("messages.upsert",d),l}}}function Fn(){let e=()=>{},t={level:"silent",trace:e,debug:e,info:e,warn:e,error:e,fatal:e};return t.child=()=>t,t}function Le(e){return new Promise((t)=>setTimeout(t,e))}var Wn="./.whatsapp",X=(e)=>{let t=Y(e.config,"authDir")??Wn,n=vn(t)?t:kn(e.dir,t),r=e.config.api,i=Y(e.config,"pairWith"),s=i===void 0?void 0:i.replace(/[^0-9]/g,"");if(i!==void 0&&!/^[0-9]{6,20}$/.test(s??""))throw Error(`channels.${e.id}.pairWith: "${i}" is not a WhatsApp number — the digits with the country code, with or without a +.`);let o=Y(e.config,"deviceName");if(o!==void 0&&!/^[\x20-\x7e]{1,32}$/.test(o))throw Error(`channels.${e.id}.deviceName: "${o}" must be 1-32 printable ASCII characters — it is the bracket of the phone's Linked-devices label.`);let a=e.config.pairingDelayMs;return new Pe({id:e.id,authDir:n,...s===void 0?{}:{pairWith:s},...o===void 0?{}:{deviceName:o},...typeof a==="number"?{pairingDelayMs:a}:{},...r===void 0?{}:{api:r}})};var Bn="0.1.0",De={name:"whatsapp",version:Bn,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["web.whatsapp.com","*.whatsapp.net"]},{kind:"fs",paths:["<agent>/.whatsapp"],mode:"write"}],setup(e){e.defineChannel("whatsapp",X)}};function Y(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}import{mkdirSync as Kn,readFileSync as Gn,renameSync as Hn,writeFileSync as qn}from"node:fs";import{dirname as Jn,isAbsolute as Vn,join as je,resolve as Yn}from"node:path";import{mkdirSync as Er,readFileSync as st,renameSync as Ar,writeFileSync as Rr}from"node:fs";import{dirname as xr,isAbsolute as Cr,join as Ve,resolve as Ir}from"node:path";var P=1,Fe="tools.cache.json";function U(e){return Vn(e)?je(e,be.stateDir,Fe):je(Yn(e),be.stateDir,Fe)}function Xn(e){return typeof e==="object"&&e!==null&&typeof e.slug==="string"}function We(e){let t={version:P,provider:"composio",fetchedAt:"",baseUrl:"",tools:{}},n;try{n=Gn(U(e),"utf8")}catch{return t}try{let r=JSON.parse(n);if(typeof r!=="object"||r===null)return t;let i=r;if(i.version!==P)return t;let s={};for(let[o,a]of Object.entries(i.tools??{}))if(Xn(a))s[o]=a;return{version:P,provider:"composio",fetchedAt:typeof i.fetchedAt==="string"?i.fetchedAt:"",baseUrl:typeof i.baseUrl==="string"?i.baseUrl:"",tools:s}}catch{return t}}function zn(e,t,n,r){let i=U(e);Kn(Jn(i),{recursive:!0});let s={version:P,provider:"composio",fetchedAt:r().toISOString(),baseUrl:n,tools:t},o=`${i}.${process.pid}.tmp`;return qn(o,`${JSON.stringify(s,null,2)}
|
|
3
|
+
`,"utf8"),Hn(o,i),i}function Ke(e){return new _({code:"composio_key_missing",message:`The Composio provider needs an API key, and ${e} is not set.`,hint:`Set ${e} 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 Q(e,t,n){return new _({code:"composio_schema_unsupported",message:`The Composio tool "${e}" declares "${n}" at ${t}, 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 Qn(e,t){return new _({code:"composio_cache_miss",message:`${e.length===1?"A pinned Composio tool is":`${e.length} pinned Composio tools are`} not in the resolution cache: ${e.join(", ")}.`,hint:`Boot resolves tools from ${t} and makes no network call, because nothing may touch the network before runtime.ready. Run \`${be.slug} tools <manifest> --warm\` once to populate it, then start again.`,field:"tools.pinned"})}function x(e,t){return new O({code:"composio_request_failed",message:`Composio answered ${e}: ${t}`,hint:e===401||e===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.":e===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 Zn(e,t,n){return new O({code:"composio_execute_failed",message:`Composio could not run "${e}" (${t}): ${n}`,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 er(e,t){return new O({code:"composio_not_connected",message:`"${e}" needs a connected ${t} account and none was found.`,hint:`Connect ${t} 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 Ge(e){return new O({code:"composio_session_key_missing",message:`Searching your apps needs a Composio key, and ${e} is not set.`,hint:`Put the key in the .env beside this agent's manifest as ${e}=…, then restart. Get one from the Composio dashboard — the free tier is enough to connect an account and search the catalogue.`})}function He(e){return new O({code:"composio_no_match",message:`No tool matched "${e}".`,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 tr="https://backend.composio.dev/api/v3";function qe(e){return/\/v3$/.test(e)?e.replace(/\/v3$/,"/v3.1"):e}var nr=100;function C(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}async function N(e){let t;try{t=await e.json()}catch{return e.statusText===""?"no detail in the response body":e.statusText}let n=C(C(t)?.error),r=typeof n?.message==="string"?n.message:void 0,i=typeof n?.suggested_fix==="string"?n.suggested_fix:void 0;if(r===void 0)return e.statusText===""?"no detail":e.statusText;return i===void 0||i===""?r:`${r} — ${i}`}class ze{#e;#t;#i;constructor(e){this.#e=e.apiKey,this.#t=(e.baseUrl??tr).replace(/\/+$/,""),this.#i=e.fetch??((t,n)=>globalThis.fetch(t,n))}#a(e,t){return this.#i(`${this.#t}${e}`,{method:"GET",headers:{"x-api-key":this.#e,accept:"application/json"},...t===void 0?{}:{signal:t}})}async#c(e,t){let n=await this.#a(e,t);if(!n.ok)throw x(n.status,await N(n));return n.json()}async tool(e,t){let n=await this.#a(`/tools/${encodeURIComponent(e)}`,t);if(n.status===404)return;if(!n.ok)throw x(n.status,await N(n));let r=C(await n.json());return typeof r?.slug==="string"?r:void 0}async slugs(e){let t=[],n;for(let r=0;r<400;r+=1){let i=new URLSearchParams({limit:String(nr)});if(n!==void 0)i.set("cursor",n);let s=await this.#c(`/tools?${i.toString()}`,e);for(let a of s.items??[])if(typeof a.slug==="string")t.push(a.slug);let o=s.next_cursor;if(o===null||o===void 0||o===""||o===n)break;n=o}return t}async execute(e,t,n,r){let i=await this.#r(`${this.#t}/tools/execute/${encodeURIComponent(e)}`,{user_id:n,arguments:t},r);if(!i.ok)throw x(i.status,await N(i));let s=C(await i.json())??{},o=s.successful!==!1,a=typeof s.error==="string"&&s.error!==""?s.error:void 0;return{ok:o,data:s.data??s,...a===void 0?{}:{error:a}}}#r(e,t,n){return this.#i(e,{method:"POST",headers:{"x-api-key":this.#e,"content-type":"application/json",accept:"application/json"},body:JSON.stringify(t),...n===void 0?{}:{signal:n}})}async createSession(e,t){let n=await this.#r(`${qe(this.#t)}/tool_router/session`,{user_id:e},t);if(!n.ok)throw x(n.status,await N(n));let r=C(await n.json())??{},i=r.session_id;if(typeof i!=="string"||i==="")throw x(n.status,"no session_id in the response body");return r}async executeMeta(e,t,n,r){let i=await this.#r(`${qe(this.#t)}/tool_router/session/${encodeURIComponent(e)}/execute_meta`,{slug:t,arguments:n},r);if(i.status===404)return{notFound:!0};if(!i.ok)throw x(i.status,await N(i));let s=C(await i.json())??{},o=typeof s.error==="string"&&s.error!==""?s.error:void 0;return{ok:s.successful===void 0?o===void 0:s.successful!==!1,data:s.data??s,...o===void 0?{}:{error:o}}}}var Qe=["anyOf","oneOf","allOf","not","$ref"],rr=["format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minLength","maxLength","pattern","minItems","maxItems"],ir=new Set(["string","number","integer","boolean","array","object"]);function D(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function sr(e){let t=[];for(let n of rr){let r=e[n];if(r===void 0||r===null)continue;if(typeof r==="object")continue;t.push(`${n} ${String(r)}`)}return t.join(", ")}function or(e){let t=typeof e.description==="string"?e.description.trim():"",n=sr(e);if(t===""&&n==="")return;if(n==="")return t;return t===""?n:`${t} (${n})`}function Ze(e,t,n){for(let d of Qe)if(e[d]!==void 0)throw Q(t,n,d);let r=e.type;if(Array.isArray(r))throw Q(t,n,"type: []");let i=typeof r==="string"&&ir.has(r)?r:"string",s=or(e),o=Array.isArray(e.enum)?e.enum.filter((d)=>typeof d==="string"||typeof d==="number"||typeof d==="boolean"):void 0,a=i==="array"?D(e.items):void 0,c=i==="object"?D(e.properties):void 0;return{type:i,...s===void 0?{}:{description:s},...o===void 0||o.length===0?{}:{enum:o},...a===void 0?{}:{items:Ze(a,t,`${n}[]`)},...c===void 0?{}:{properties:tt(c,t,n),required:et(e.required)},...e.default===void 0||e.default===null?{}:{default:e.default}}}function et(e){return Array.isArray(e)?e.filter((t)=>typeof t==="string"):[]}function tt(e,t,n){let r={};for(let[i,s]of Object.entries(e)){let o=D(s);if(o===void 0)continue;r[i]=Ze(o,t,n===""?i:`${n}.${i}`)}return r}function ar(e){let t=e.input_parameters;if(t===void 0)return{type:"object",properties:{}};for(let s of Qe)if(t[s]!==void 0)throw Q(e.slug,"input_parameters",s);let n=D(t.properties)??{},r=et(t.required),i=tt(n,e.slug,"");return{type:"object",properties:i,...r.length===0?{}:{required:r.filter((s)=>(s in i))}}}function ee(e){let t=new Set(e.tags??[]);if(t.has("destructiveHint"))return!0;return!t.has("readOnlyHint")}function nt(e){let t=new Set(e.tags??[]);return!t.has("readOnlyHint")&&!t.has("destructiveHint")}function cr(e){let t=e.replace(/\s+/g," ").trim(),n=t.search(/\.\s|\.$/);return n===-1?t:t.slice(0,n+1)}function dr(e){let t=(e.description??e.human_description??"").trim(),n=t===""?`The ${e.slug} tool.`:cr(t),r=e.toolkit?.slug;return{slug:e.slug,provider:"composio",summary:n,whenToUse:t===""?`the task needs ${e.slug}`:t,mutating:ee(e),tags:[...r===void 0?[]:[r],...ee(e)?["write"]:["read"]],parameters:ar(e)}}var hr=8,Je=100,j="composio_search",F="composio_connect",re="composio_workbench",lr=[j,F,re];function T(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function te(e){return Array.isArray(e)?e:[]}function S(e){return typeof e==="string"&&e!==""?e:void 0}function ur(e){let t=e.replace(/\s+/g," ").trim();return t.length<=Je?t:`${t.slice(0,Je-1)}…`}var rt={slug:j,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 fr(e){let t=[];for(let n of te(e.results)){let r=T(n);if(r===void 0)continue;for(let i of[r.primary_tool_slugs,r.related_tool_slugs])for(let s of te(i))if(typeof s==="string"&&!t.includes(s))t.push(s)}return t.slice(0,hr)}function pr(e,t){let n=[];for(let r of e){let i=t[r];if(i===void 0)continue;let s=i.description??i.human_description??"";n.push({slug:r,summary:s===""?"no description supplied":ur(s),toolkit:i.toolkit?.slug??"",mutating:ee(i),assumed:nt(i)})}return n}function mr(e){let t=[];for(let n of te(e.toolkit_connection_statuses)){let r=T(n),i=S(r?.toolkit);if(i===void 0)continue;t.push({toolkit:i,connected:r?.has_active_connection===!0})}return t}function gr(e,t,n){let r=[`Tools that can "${e}":`,""];for(let o of t)r.push(` ${o.mutating?"write":"read "} ${o.slug}`),r.push(` ${o.summary}`);if(t.some((o)=>o.assumed))r.push(""),r.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 i=n.filter((o)=>!o.connected).map((o)=>o.toolkit),s=n.filter((o)=>o.connected).map((o)=>o.toolkit);if(r.push(""),s.length>0)r.push(`Already connected: ${s.join(", ")}.`);if(i.length>0)r.push(`Not connected yet: ${i.join(", ")}. Call composio_connect for each before these tools can run.`);return r.push(""),r.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."),r.join(`
|
|
4
|
+
`)}function wr(e){return{spec:rt,handler:async(t,n)=>{let r=String(t.use_case??"").trim(),i=await e.call("COMPOSIO_SEARCH_TOOLS",{queries:[{use_case:r}],session:{generate_id:!0}},n.signal);if(!i.ok)return`The search failed: ${i.error??"no detail supplied"}`;let s=T(i.data)??{},o=fr(s);if(o.length===0)throw He(r);let a=await e.fetchSchemas(o,n.signal),c=pr(o,a);if(c.length===0)throw He(r);return gr(r,c,mr(s))}}}var it={slug:F,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 ne(e,t=0){if(t>6)return;if(typeof e==="string")return/^https?:\/\/\S+$/.test(e.trim())?e.trim():void 0;for(let n of Array.isArray(e)?e:Object.values(T(e)??{})){let r=ne(n,t+1);if(r!==void 0)return r}return}function yr(e,t){let n=T(T(t.results)?.[e]),r=S(n?.status)?.toLowerCase(),i=S(n?.redirect_url)??ne(t.results)??ne(t);if(r==="active")return`${e} is already connected — nothing to do. Its tools work as soon as they are pinned.`;if(i===void 0)return`Composio returned no sign-in link for ${e}${r===void 0?"":` (status: ${r})`}. ${S(t.message)??"No detail was supplied."}`;return[`To connect ${e}, the person needs to open this and sign in:`,"",` ${i}`,"","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(`
|
|
5
|
+
`)}function br(e){return{spec:it,handler:async(t,n)=>{let r=String(t.toolkit??"").trim().toLowerCase(),i=await e.call("COMPOSIO_MANAGE_CONNECTIONS",{toolkits:[r]},n.signal);if(!i.ok)return`Could not start the connection for ${r}: ${i.error??"no detail supplied"}`;return yr(r,T(i.data)??{})}}}var vr={slug:re,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"]}},kr="code_to_execute";function _r(e){let t=T(e);if(t===void 0)return typeof e==="string"?e:JSON.stringify(e,null,2);let n=[],r=S(t.stdout),i=S(t.stderr),s=S(t.error),o=S(t.results);if(r!==void 0)n.push(r.trimEnd());if(o!==void 0)n.push(o.trimEnd());if(i!==void 0)n.push(`stderr:
|
|
6
|
+
${i.trimEnd()}`);if(s!==void 0)n.push(`error:
|
|
7
|
+
${s.trimEnd()}`);return n.length===0?"The code ran and printed nothing.":n.join(`
|
|
8
|
+
`)}function $r(e){return{spec:vr,handler:async(t,n)=>{let r=await e.call("COMPOSIO_REMOTE_WORKBENCH",{[kr]:String(t.code??"")},n.signal);if(!r.ok)return`The workbench failed: ${r.error??"no detail supplied"}`;return _r(r.data)}}}function Tr(e){return{[j]:wr(e),[F]:br(e),[re]:$r(e)}}var Ye="composio.session.json";function ot(e){return Cr(e)?Ve(e,be.stateDir,Ye):Ve(Ir(e),be.stateDir,Ye)}function Nr(e,t){let n;try{n=st(ot(e),"utf8")}catch{return}try{let i=JSON.parse(n)?.sessions;if(typeof i!=="object"||i===null)return;let s=i[t];return typeof s==="string"&&s!==""?s:void 0}catch{return}}function Or(e,t,n){let r=ot(e);Er(xr(r),{recursive:!0});let i={};try{let c=JSON.parse(st(r,"utf8"))?.sessions;if(typeof c==="object"&&c!==null){for(let[d,h]of Object.entries(c))if(typeof h==="string")i[d]=h}}catch{i={}}let s={sessions:{...i,[t]:n}},o=`${r}.${process.pid}.tmp`;return Rr(o,`${JSON.stringify(s,null,2)}
|
|
9
|
+
`,"utf8"),Ar(o,r),r}var Mr="COMPOSIO_API_KEY";class at{id="composio";#e;#t;#i;#a;#c;#r;#n;#s;#o=[];#d;constructor(e){this.#e=e.dir,this.#t=e.userId??"default",this.#i=e.now??(()=>new Date),this.#r=e.apiKeyEnv??Mr;let t=e.env[this.#r];this.#a=e.baseUrl??"https://backend.composio.dev/api/v3",this.#c=t===void 0||t===""?void 0:new ze({apiKey:t,baseUrl:this.#a,...e.fetch===void 0?{}:{fetch:e.fetch}});let n=We(this.#e);this.#n=n.tools,this.#s=n.fetchedAt}async resolve(e){let t=[],n=[],r=Tr(this.#l());for(let i of e){let s=r[i];if(s!==void 0){t.push(s);continue}let o=this.#n[i];if(o===void 0)continue;if(nt(o))n.push(i);t.push(this.#f(dr(o)))}return this.#o=n,t}async list(){return[...lr,...Object.keys(this.#n)]}async available(){return[{slug:j,summary:rt.summary},{slug:F,summary:it.summary}]}uncached(e){return e.filter((t)=>this.#n[t]===void 0)}explainUnresolved(e){if(Object.keys(this.#n).length>0||e.length===0)return;return Qn(e,U(this.#e))}describe(){return{cached:Object.keys(this.#n).length,fetchedAt:this.#s,cachePath:U(this.#e),assumedMutating:this.#o}}async refresh(e,t){let n=this.#c;if(n===void 0)throw Ke(this.#r);let r={},i=[],s=[];for(let a of e){let c=await n.tool(a,t);if(c===void 0){i.push(a);continue}r[a]=c;let d=this.#n[a];if(d===void 0||JSON.stringify(d)!==JSON.stringify(c))s.push(a)}this.#n={...this.#n,...r};let o=zn(this.#e,this.#n,this.#a,this.#i);return this.#s=We(this.#e).fetchedAt,{fetched:Object.keys(r).length,missing:i,changed:s,cachePath:o}}async#h(e,t=!1){let n=this.#c;if(n===void 0)throw Ge(this.#r);if(!t){let i=this.#d??Nr(this.#e,this.#t);if(i!==void 0)return this.#d=i,i}let r=await n.createSession(this.#t,e);return this.#d=r.session_id,Or(this.#e,this.#t,r.session_id),r.session_id}#l(){return{call:async(e,t,n)=>{let r=this.#c;if(r===void 0)throw Ge(this.#r);let i=await this.#h(n),s=await r.executeMeta(i,e,t,n);if("notFound"in s){i=await this.#h(n,!0);let o=await r.executeMeta(i,e,t,n);if("notFound"in o)return{ok:!1,data:{},error:"the session could not be opened"};s=o}return s},fetchSchemas:async(e,t)=>{await this.refresh(e,t);let n={};for(let r of e){let i=this.#n[r];if(i!==void 0)n[r]=i}return n}}}#f(e){return{spec:e,handler:async(t,n)=>{let r=this.#c;if(r===void 0)throw Ke(this.#r);let i=await r.execute(e.slug,t,this.#t,n.signal);if(!i.ok){let s=i.error??"no detail supplied";if(/connected account|not connected|no connection/i.test(s)){let o=e.tags[0]??"the toolkit";throw er(e.slug,o)}throw Zn(e.slug,200,s)}return typeof i.data==="string"?i.data:JSON.stringify(i.data,null,2)}}}}var Xe=["apiKeyEnv","userId","baseUrl"];function z(e,t){let n=e[t];if(n===void 0)return;if(typeof n!=="string"||n==="")throw new _({code:"composio_config_invalid",message:`tools.providers.composio.${t} must be a non-empty string.`,hint:`Got ${n===null?"null":typeof n}. ${t==="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.${t}`});return n}function ie(e){let t=Object.keys(e.config).filter((s)=>!Xe.includes(s));if(t.length>0)throw new _({code:"composio_config_unknown",message:`tools.providers.composio has ${t.length===1?"a key":"keys"} the Composio provider does not read: ${t.join(", ")}.`,hint:`Accepted keys are ${Xe.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 n=z(e.config,"apiKeyEnv"),r=z(e.config,"userId"),i=z(e.config,"baseUrl");return new at({dir:e.dir,env:e.env,...n===void 0?{}:{apiKeyEnv:n},...r===void 0?{}:{userId:r},...i===void 0?{}:{baseUrl:i}})}var Lr="0.1.0",ct={name:"composio",version:Lr,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["backend.composio.dev"]},{kind:"env",vars:["COMPOSIO_API_KEY"]},{kind:"fs",paths:["<state>/composio"],mode:"write"}],setup(e){e.defineToolProvider("composio",ie)}};import{readFile as Pr}from"node:fs/promises";import{join as Ur}from"node:path";import{tmpdir as Zr}from"node:os";import{join as ei}from"node:path";import{mkdir as li,realpath as ui,rm as ut,stat as fi}from"node:fs/promises";import{isAbsolute as pi,resolve as he}from"node:path";import{open as Ct}from"node:fs/promises";import{existsSync as vi}from"node:fs";import{homedir as pt}from"node:os";import{isAbsolute as Nt,relative as ki,resolve as M,sep as _i}from"node:path";import{spawn as xi}from"node:child_process";import{open as Ci,readFile as Ii}from"node:fs/promises";import{mkdir as Qi,readFile as Ut,stat as Dt,writeFile as jt}from"node:fs/promises";import{dirname as Zi,isAbsolute as es,resolve as wt}from"node:path";import{isAbsolute as ts,relative as ns,resolve as rs,sep as Ft}from"node:path";import{readFile as ws}from"node:fs/promises";import{readdir as ys}from"node:fs/promises";import{join as bs,relative as vs,sep as kt}from"node:path";import{statSync as xs}from"node:fs";import{mkdir as Cs,rm as Et}from"node:fs/promises";import{delimiter as Is,join as de}from"node:path";function Dr(){return new O({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 jr(e,t){return new _({code:"exec_workdir_missing",message:`The directory to run in does not exist: ${e}`,hint:t?"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 Fr(e,t){return new O({code:"exec_pty_unavailable",message:`A terminal was requested and this machine cannot provide one: ${t}`,hint:`pty: true allocates a terminal with the system \`script\` command, which is missing or unusable on this ${e} 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 dt(e,t){return new O({code:"exec_spawn_failed",message:`The shell could not be started for: ${e}`,hint:`The operating system refused before the command ran, so nothing was executed: ${t}. This is a failure of the host rather than of the command — check that /bin/sh exists and that the directory is readable.`})}function Wr(){return new O({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 At(e){return new O({code:"file_missing",message:`There is no file at ${e}.`,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 Br(e,t,n){return new O({code:"file_too_large",message:`${e} is ${t} bytes, over the ${n}-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 Kr(e,t){return new O({code:"file_is_binary",message:`${e} is not a text file (${t} 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 Gr(e,t){return new O({code:"file_protected",message:`${e} cannot be written: ${t}.`,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 Hr(e,t){let n=t.length>120?`${t.slice(0,120)}…`:t;return new O({code:"file_edit_no_match",message:`That text does not appear in ${e}: ${JSON.stringify(n)}`,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 qr(e,t){return new O({code:"file_edit_ambiguous",message:`That text appears ${t} times in ${e}, 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 Jr(e,t){return new O({code:"grep_pattern_invalid",message:`That is not a valid regular expression: ${e}`,hint:`${t}. 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 Vr(e,t){return new O({code:"file_outside_root",message:`${e} is outside the directories this agent may change.`,hint:`Writable: ${t.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 Rt(e,t){return new O({code:"config_read_failed",message:`This agent's configuration could not be read from ${e}.`,hint:`${t}. The agent is running, so the file existed at boot — it has been moved or its permissions have changed since.`})}function Yr(e,t){return new O({code:"config_path_unknown",message:`"${e}" is not a setting config_set will change.`,hint:`Settable: ${t.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 Xr(e,t){return new O({code:"config_value_unreadable",message:`That value could not be read: ${JSON.stringify(e)}`,hint:`${t}. 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 zr(e,t,n){return new O({code:"config_invalid",message:`Setting ${e} to ${JSON.stringify(t)} would produce a configuration that does not load: ${n}`,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 ht(e,t){return new O({code:"config_refused",message:`${e} cannot be changed from inside a conversation: ${t}.`,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 Qr(e){return new O({code:"exec_too_many_background",message:`${e.length} commands are already running in the background, which is the limit.`,hint:`Wait for one to finish, or stop one yourself. Already running: ${e.map((t)=>t.length>60?`${t.slice(0,57)}...`:t).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 b="system";function fe(){return ei(Zr(),`${be.slug}-${b}`)}var ti=RA.filter((e)=>e.agentListed);function lt(e,t){let n=e.toLowerCase(),r="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",i="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",s="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(n.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(n.startsWith("tools.providers")&&E(t,"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(n.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(n==="channels"&&E(t,"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(n==="server.host"||n==="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(n==="server"&&(E(t,"host")||E(t,"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(n==="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(t!==void 0&&n==="tools.untrusted.onmutate"&&String(t).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 E(e,t){if(Array.isArray(e))return e.some((n)=>E(n,t));if(typeof e!=="object"||e===null)return!1;return Object.entries(e).some(([n,r])=>n.toLowerCase()===t||E(r,t))}function xt(e){return e.file??Ur(e.agentDir,"agent.yaml")}var ri={slug:"config_read",provider:b,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."}}}},si={slug:"config_set",provider:b,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 oi(e){try{return Dn(e)}catch(t){throw Xr(e,t instanceof Error?t.message:String(t))}}function ai(e){return async(t)=>{let n=xt(e),r;try{r=await Pr(n,"utf8")}catch(a){throw Rt(n,String(a))}let i=typeof t.path==="string"?t.path.trim():"";if(i!==""){let a=Ee(r),c=a.getIn(i.split("."),!1);if(c===void 0)return`${i} is not set in this configuration. It can be — see config_read with no path for the full list.`;return`${i}:
|
|
10
|
+
${vt(mA(c)||SA(c)?c.toJS(a):c).trimEnd()}`}let s=Ee(r),o=ti.map((a)=>{let c=s.getIn(a.path.split("."),!1),d=mA(c)||SA(c)?c.toJS(s):c,h=d===void 0||d===null?"(not set)":Array.isArray(d)?`[${d.map((l)=>typeof l==="object"&&l!==null?JSON.stringify(l):String(l)).join(", ")}]`:vt(d).trim(),u=a.toAgent===void 0?a.means:`${a.means}. ${a.toAgent}`;return`- ${a.path} = ${h}
|
|
11
|
+
${u}`}).join(`
|
|
12
|
+
`);return[`This agent is ${s.get("name")??s.get("id")}, configured at ${n}.`,"","Settings config_set can change, with their current values:",o,"","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 ${n} — read it with file_read if that tool is enabled, or ask the person to open it.`].join(`
|
|
13
|
+
`)}}function ci(e){return async(t)=>{let n=xt(e),r=typeof t.path==="string"?t.path.trim():"",i=typeof t.value==="string"?t.value:String(t.value??""),s=lt(r);if(s!==void 0)throw ht(r,s);if(!ii.includes(r))throw Yr(r,ii);let o=oi(i),a=lt(r,o);if(a!==void 0)throw ht(r,a);let c;try{c=await Sn({file:n,path:r.split("."),value:o})}catch(h){if(h instanceof Be&&h.code==="manifest_edit_unreadable")throw Rt(n,String(h.cause??h.message));if(h instanceof Be&&h.code==="manifest_edit_invalid"){let u=h.message.slice(h.message.indexOf(": ")+2);throw zr(r,i,u)}throw h}let d=c.before!==void 0;return[`Set ${r} in ${n}.`,d?`It was: ${vt(c.before).trim()}`:"It was not set before.",`It is now: ${vt(o).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.",...di(c.manifest,o)].join(`
|
|
14
|
+
`)}}function di(e,t){if(!E(t,"tokenenv")&&!E(t,"apikeyenv"))return[];let n=new Set;for(let r of e.channels??[]){let i=r.tokenEnv;if(typeof i==="string"&&i!=="")n.add(i)}if(n.size===0)return[];return["",`This will NOT start until ${[...n].join(" and ")} ${n.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 hi(e){return[{spec:ri,handler:ai(e)},{spec:si,handler:ci(e)}]}var mi=6000,gi=3000,ft=1500,wi=new TextDecoder("utf-8");async function se(e,t,n){let r=await Ct(e,"r");try{let i=new Uint8Array(n),{bytesRead:s}=await r.read(i,0,n,t);return wi.decode(i.subarray(0,s))}finally{await r.close()}}async function It(e){let t=await Ct(e,"r"),n;try{n=(await t.stat()).size}finally{await t.close()}if(n<=mi)return{head:fA(await se(e,0,n)),tail:"",bytes:n,spilled:!1};return{head:fA(await se(e,0,gi)),tail:fA(await se(e,n-ft,ft)),bytes:n,spilled:!0}}function yi(e){return e.replace(/^(?:\^[A-Z?]\s*)+/,"")}function bi(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;return`${(e/1048576).toFixed(1)} MB`}function $i(e){if(e==="~")return pt();return e.startsWith("~/")?M(pt(),e.slice(2)):e}var Si="workspace";function Ti(e,t=[]){let n=M(e),r=M(n,Si);return{primary:vi(r)?r:n,extra:t.map((i)=>Nt(i)?M(i):M(n,i))}}function Ei(e,t){if(e===t)return!0;let n=ki(t,e);return n!==""&&!n.startsWith(`..${_i}`)&&n!==".."&&!Nt(n)}function Ot(e){return[e.primary,...e.extra]}function Ai(e,t){return Ot(t).some((n)=>Ei(e,n))}function Ri(e,t){let n=e.extra.length===0?"":` Also writable: ${e.extra.join(", ")}.`;if(t==="read")return` Relative paths are resolved against ${e.primary}. Reading elsewhere is allowed — give an absolute path for it.`;if(t==="write")return` You work in ${e.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.${n}`;return` Every command starts in ${e.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.${n}`}function pe(e,t,n,r=e.mutating?"write":"read"){let i={...e.parameters.properties};for(let s of n){let o=i[s];if(o===void 0)continue;i[s]={...o,description:`${o.description??""}${Ri(t,r)}`}}return{...e,parameters:{...e.parameters,properties:i}}}var A=new Map,Ni=8;function Oi(){return[...A.entries()].map(([e,t])=>({pid:e,...t})).sort((e,t)=>t.since-e.since)}function Mi(){let e=[];for(let[t,n]of A)try{process.kill(-t,"SIGTERM"),e.push(`${t} (${n.command})`)}catch{}return A.clear(),e}function Li(){for(let e of[...A.keys()])try{process.kill(e,0)}catch{A.delete(e)}}var Pi=250,mt=2000,Ui=new Set(["sleep","git","ssh","scp","sudo","su","doas"]);function Di(e){for(let t of e.split(/\s+/)){if(/^[A-Za-z_]\w*=/.test(t))continue;return t.replace(/^.*\//,"").toLowerCase()}return""}function ji(e){let t=Sr(e);if(t.length===0)return!1;return t.every((n)=>!Ui.has(Di(n)))}function Mt(e){return`'${e.replaceAll("'","'\\''")}'`}function Fi(e,t){return[e,"__code=$?",`{ printf '%s\\n' "$__code"; pwd; } > ${Mt(t)} 2>/dev/null`,"exit $__code"].join(`
|
|
15
|
+
`)}function Wi(e,t,n=process.platform){if(!t)return{file:"/bin/sh",args:["-c",e],env:{}};if(n==="linux")return{file:"script",args:["-qec",`/bin/sh -c ${Mt(e)}`,"/dev/null"],env:{SHELL:"/bin/sh"}};return{file:"script",args:["-q","/dev/null","/bin/sh","-c",e],env:{SHELL:"/bin/sh"}}}function W(e,t){let n=e.pid;if(n===void 0)return;try{process.kill(-n,t)}catch{}}async function Bi(e){try{let[t,n]=(await Ii(e,"utf8")).split(`
|
|
16
|
+
`),r=Number.parseInt(t??"",10),i=n?.trim();return{...Number.isNaN(r)?{}:{code:r},...i===void 0||i===""?{}:{cwd:i}}}catch{return{}}}async function Lt(e){if(Li(),A.size>=Ni)throw Qr(Oi().map((d)=>d.command));let t=Fi(e.command,e.statusPath),{file:n,args:r,env:i}=Wi(t,e.pty),s=await Ci(e.outPath,"w"),o;try{o=xi(n,r,{cwd:e.cwd,env:{...e.env,...i},stdio:["ignore",s.fd,s.fd],detached:!0})}catch(d){throw await s.close(),dt(e.command,String(d))}let a=await new Promise((d,h)=>{let u=!1,l=!1,f=setTimeout(p,e.background?Pi:e.timeoutMs),y=(m)=>{if(u)return;u=!0,clearTimeout(f),e.signal.removeEventListener("abort",g),d(m)};function p(){if(e.background||ji(e.command)){if(o.unref(),o.pid!==void 0)A.set(o.pid,{command:e.command,since:Date.now(),outPath:e.outPath});y({ending:"backgrounded",...o.pid===void 0?{}:{pid:o.pid}});return}l=!0,W(o,"SIGTERM"),setTimeout(()=>W(o,"SIGKILL"),mt).unref?.()}function g(){W(o,"SIGTERM"),setTimeout(()=>W(o,"SIGKILL"),mt).unref?.()}e.signal.addEventListener("abort",g,{once:!0}),o.on("error",(m)=>{if(u)return;u=!0,clearTimeout(f),e.signal.removeEventListener("abort",g),h(e.pty&&Ki(m)?Fr(process.platform,String(m)):dt(e.command,String(m)))}),o.on("exit",(m,R)=>{y({ending:l?"killed":"finished",...m===null?{}:{code:m},...R===null?{}:{killedBy:R},...o.pid===void 0?{}:{pid:o.pid}})})}).finally(()=>s.close()),c=await Bi(e.statusPath);return{...a,...c.code===void 0?{}:{code:c.code},...c.cwd===void 0?{}:{cwdAfter:c.cwd}}}function Ki(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}var le=120000,Pt=600000,Gi=5000,Hi={slug:"exec",provider:b,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 ${le}, maximum ${Pt}.`,default:le},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 qi(e,t){let n=e===void 0||e<=0?le:e,r=Math.min(n,Pt),i=t-Gi;return Math.max(1,Math.min(r,i>0?i:Math.floor(t*0.8)))}function gt(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function Ji(e,t){let n=fe();return{out:he(n,`${e.turnId}-${t}.log`),status:he(n,`${e.turnId}-${t}.status`)}}function Vi(e){return async(t,n)=>{let r=typeof t.command==="string"?t.command.trim():"";if(r==="")throw Dr();let i=e.sessions.lastCwd(n.sessionKey),s=i??e.roots.primary,o=typeof t.workdir==="string"?t.workdir.trim():"",a=o===""?s:pi(o)?o:he(s,o),c;try{if(c=await ui(a),!(await fi(c)).isDirectory())throw Error("not a directory")}catch{let m=o===""&&i!==void 0;if(m)e.sessions.forget(n.sessionKey);throw jr(a,m)}let d=qi(gt(t.timeoutMs),n.deadlineMs),h=gt(t.timeoutMs)!==void 0&&d<Number(t.timeoutMs),u=t.background===!0,l=fe();await li(l,{recursive:!0});let f=Ji(n,Yi(r,n.turnId)),y=await Lt({command:r,cwd:c,env:e.env,timeoutMs:d,pty:t.pty===!0,background:u,signal:n.signal,outPath:f.out,statusPath:f.status});if(y.cwdAfter!==void 0)e.sessions.remember(n.sessionKey,y.cwdAfter);let p=await It(f.out),g=t.pty===!0?{...p,head:yi(p.head)}:p;if(await ut(f.status,{force:!0}),!g.spilled&&y.ending!=="backgrounded")await ut(f.out,{force:!0});return Xi({command:r,cwd:c,run:y,observation:g,clamped:h,timeoutMs:d,path:f.out})}}function Yi(e,t){let n=2166136261;for(let r of[e,t])for(let i=0;i<r.length;i+=1)n^=r.charCodeAt(i),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}function Xi(e){let t=[];if(e.clamped)t.push(`The requested timeout was longer than allowed, so this ran with ${e.timeoutMs} ms.`);if(e.run.ending==="backgrounded")return t.push(`Still running${e.run.pid===void 0?"":` as process ${e.run.pid}`}. It was left alone rather than stopped, and keeps writing to ${e.path}; read that file to see how far it has got. Nothing here is its final result.`),[...t,ce("Output so far",e.observation.head)].join(`
|
|
17
|
+
|
|
18
|
+
`);if(e.run.ending==="killed")t.push(`Stopped after ${e.timeoutMs} ms without finishing, and everything it started was stopped with it. Whatever it had already done still happened.`);else if(e.run.code!==void 0&&e.run.code!==0)t.push(`Failed with exit code ${e.run.code}.`);else if(e.run.killedBy!==void 0)t.push(`Ended on signal ${e.run.killedBy}.`);if(e.run.cwdAfter!==void 0&&e.run.cwdAfter!==e.cwd)t.push(`The working directory is now ${e.run.cwdAfter}, and the next exec call starts there.`);let n=e.run.ending==="killed"||(e.run.code??0)!==0,r=[];if(e.observation.spilled){if(t.push(`Output was ${bi(e.observation.bytes)}, too much to include. All of it is in ${e.path}; what follows is the ${n?"start and end":"start"}.`),r.push(ce("First part of the output",e.observation.head)),n)r.push(ce("End of the output",e.observation.tail))}else if(e.observation.head.trim()!=="")r.push(e.observation.head.trimEnd());else if(t.length===0)return"The command finished successfully and printed nothing.";return[...t,...r].join(`
|
|
19
|
+
|
|
20
|
+
`)}function ce(e,t){return`${e}:
|
|
21
|
+
${t.trimEnd()}`}function zi(e){return{spec:pe(Hi,e.roots,["command","workdir"],"shell"),handler:Vi(e)}}var is=["agent.yaml","agent.yml","SOUL.md","SOUL.compact.md","AGENTS.md","POLICY.md","REMINDER.md"],ss=[".ssh",".aws",".kube",".gnupg",".docker"],os=/^(?:\.env(\..+)?|\.netrc|\.npmrc|\.pypirc|id_[a-z0-9]+|.*\.pem|.*\.key)$/i;function as(e){return e.split(Ft).filter((t)=>t!=="")}function cs(e,t){let n=as(e),r=n[n.length-1]??"";for(let a of ss)if(n.includes(a))return`${a}/ holds credentials, and nothing under it is writable by an agent`;if(os.test(r))return`${r} holds secrets — the manifest names environment variables, and their values are not the agent's to edit`;let i=rs(t.agentDir),s=ns(i,e);if(s!==""&&!s.startsWith("..")&&!ts(s)){let a=s.split(Ft),c=a[a.length-1]??"";if(is.includes(c))return`${s} 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(a[0]?.startsWith(".")===!0)return`${s} is runtime state this agent depends on`}for(let a of t.extra??[])if(e.includes(a)||r===a)return`${r} is listed in tools.providerConfig.protect`;return}var yt=2000000,ue=400;function ds(e){return e.subarray(0,8000).includes(0)}var hs={slug:"file_read",provider:b,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 ${ue}.`,default:ue}},required:["path"]}},ls={slug:"file_write",provider:b,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"]}},us={slug:"file_edit",provider:b,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 B(e,t,n,r){let i=$i(typeof e==="string"?e.trim():"");if(i==="")throw Wr();let s=t.lastCwd(n)??r;return es(i)?wt(i):wt(s,i)}function Wt(e,t){if(!Ai(e,t.roots))throw Vr(e,Ot(t.roots));let n=cs(e,{agentDir:t.agentDir,...t.protect===void 0?{}:{extra:t.protect}});if(n!==void 0)throw Gr(e,n)}function bt(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function fs(e){return async(t,n)=>{let r=B(t.path,e.sessions,n.sessionKey,e.roots.primary),i;try{i=(await Dt(r)).size}catch{throw At(r)}if(i>yt)throw Br(r,i,yt);let s=await Ut(r);if(ds(s))throw Kr(r,i);let a=fA(s.toString("utf8")).split(`
|
|
22
|
+
`),c=Math.max(1,bt(t.offset)??1),d=Math.max(1,bt(t.limit)??ue),h=a.slice(c-1,c-1+d);if(h.length===0)return`${r} has ${a.length} lines, so there is nothing at line ${c}.`;let u=h.join(`
|
|
23
|
+
`),l=c-1+h.length;if(c===1&&l>=a.length)return u;return`Lines ${c}-${l} of ${a.length} in ${r}:
|
|
24
|
+
${u}`}}function ps(e){return async(t,n)=>{let r=B(t.path,e.sessions,n.sessionKey,e.roots.primary);Wt(r,e);let i=typeof t.content==="string"?t.content:String(t.content??""),s=await Dt(r).then(()=>!0,()=>!1);await Qi(Zi(r),{recursive:!0}),await jt(r,i,"utf8");let o=i===""?0:i.split(`
|
|
25
|
+
`).length;return`${s?"Replaced":"Created"} ${r} — ${o} line${o===1?"":"s"}, ${i.length} characters.`}}function ms(e){return async(t,n)=>{let r=B(t.path,e.sessions,n.sessionKey,e.roots.primary);Wt(r,e);let i=typeof t.find==="string"?t.find:"",s=typeof t.replace==="string"?t.replace:"",o;try{o=await Ut(r,"utf8")}catch{throw At(r)}let a=i===""?0:o.split(i).length-1;if(a===0)throw Hr(r,i);if(a>1&&t.all!==!0)throw qr(r,a);let c=t.all===!0?o.split(i).join(s):o.replace(i,s);await jt(r,c,"utf8");let d=t.all===!0?a:1;return`Edited ${r} — replaced ${d} occurrence${d===1?"":"s"}. The file is now ${c.split(`
|
|
26
|
+
`).length} lines.`}}function gs(e){let t=(n)=>pe(n,e.roots,["path"]);return[{spec:t(hs),handler:fs(e)},{spec:t(ls),handler:ps(e)},{spec:t(us),handler:ms(e)}]}var ks=new Set(["node_modules",".git",".hg",".svn","dist","build","out",".next",".turbo",".cache","coverage","__pycache__",".venv","venv","target","vendor"]);function Bt(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n]??"";if(r==="*"){if(e[n+1]==="*"){if(e[n+2]==="/"){t+="(?:.*/)?",n+=2;continue}t+=".*",n+=1;continue}t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=r.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${t}$`)}function _s(e){return kt==="/"?e:e.split(kt).join("/")}async function Kt(e,t){let n=[],r=[e];while(r.length>0){let i=r.shift();if(i===void 0)break;let s;try{s=await ys(i,{withFileTypes:!0})}catch{continue}for(let o of s){let a=bs(i,o.name);if(o.isDirectory()){if(ks.has(o.name))continue;if(t.hidden!==!0&&o.name.startsWith("."))continue;r.push(a);continue}if(!o.isFile())continue;if(t.hidden!==!0&&o.name.startsWith("."))continue;let c=_s(vs(e,a));if(t.accept!==void 0&&!t.accept(c))continue;if(n.length>=t.limit)return{files:n,truncated:!0};n.push(c)}}return{files:n,truncated:!1}}var _t=200,$t=100,$s=1e6,Ss={slug:"glob",provider:b,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"]}},Ts={slug:"grep",provider:b,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 Gt(e,t,n){let r=typeof e.path==="string"&&e.path.trim()!==""?e.path:".";return B(r,t.sessions,n,t.roots.primary)}function Es(e){return async(t,n)=>{let r=typeof t.pattern==="string"?t.pattern.trim():"",i=Gt(t,e,n.sessionKey),s=Bt(r),o=await Kt(i,{limit:_t,...t.hidden===!0?{hidden:!0}:{},accept:(c)=>s.test(c)});if(o.files.length===0)return`No file under ${i} matches ${r}. Directories like node_modules, .git and dist are never searched${t.hidden===!0?"":", and dot-files are skipped unless hidden is true"}.`;return`${o.truncated?`The first ${o.files.length} of more than ${_t} matches for ${r} under ${i} — narrow the pattern to see the rest:`:`${o.files.length} match${o.files.length===1?"":"es"} for ${r} under ${i}:`}
|
|
27
|
+
${o.files.join(`
|
|
28
|
+
`)}`}}function As(e){return async(t,n)=>{let r=typeof t.pattern==="string"?t.pattern:"",i=Gt(t,e,n.sessionKey),s;try{s=new RegExp(r,t.ignoreCase===!0?"i":"")}catch(l){throw Jr(r,String(l))}let o=typeof t.glob==="string"&&t.glob.trim()!==""?Bt(t.glob.trim()):void 0,a=await Kt(i,{limit:5000,...o===void 0?{}:{accept:(l)=>o.test(l)}}),c=[],d=0,h=!1;for(let l of a.files){if(c.length>=$t){h=!0;break}let f;try{let p=await ws(`${i}/${l}`);if(p.length>$s||p.subarray(0,8000).includes(0))continue;f=p.toString("utf8")}catch{continue}d+=1;let y=f.split(`
|
|
29
|
+
`);for(let p=0;p<y.length;p+=1){let g=y[p]??"";if(!s.test(g))continue;if(c.length>=$t){h=!0;break}let m=g.length>300?`${g.slice(0,300)}…`:g;c.push(`${l}:${p+1}: ${fA(m).trim()}`)}}if(c.length===0)return`Nothing under ${i} matches ${r}${o===void 0?"":` in files matching ${String(t.glob)}`}. ${d} file${d===1?"":"s"} were searched; node_modules, .git, dist and dot-files are skipped.`;return`${h?`The first ${c.length} matches for ${r} under ${i} — there are more, so narrow the pattern or pass a glob:`:`${c.length} match${c.length===1?"":"es"} for ${r} under ${i}, across ${d} file${d===1?"":"s"} searched:`}
|
|
30
|
+
${c.join(`
|
|
31
|
+
`)}`}}function Rs(e){let t=(n)=>pe(n,e.roots,["path"]);return[{spec:t(Ss),handler:Es(e)},{spec:t(Ts),handler:As(e)}]}class Ht{#e=new Map;lastCwd(e){return this.#e.get(e)}remember(e,t){this.#e.set(e,t)}forget(e){this.#e.delete(e)}}function St(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}class qt{id=b;#e=new Ht;#t;constructor(e){let t=Ti(e.dir,e.writeRoots??[]),n={sessions:this.#e,agentDir:e.dir,roots:t,...e.protect===void 0?{}:{protect:e.protect}};this.#t=[zi({sessions:this.#e,env:e.env,roots:t}),...gs(n),...Rs({sessions:this.#e,roots:t}),...hi({agentDir:e.dir})]}available(){return Promise.resolve(this.#t.map((e)=>({slug:e.spec.slug,summary:e.spec.summary})))}resolve(e){let t=new Set(e.map(St));return Promise.resolve(this.#t.filter((n)=>t.has(St(n.spec.slug))))}stop(){return Promise.resolve(Mi())}list(){return Promise.resolve(this.#t.map((e)=>e.spec.slug))}}var Tt=["protect","writeRoots"];function me(e){let t=Object.keys(e.config).filter((i)=>!Tt.includes(i));if(t.length>0)throw new _({code:"system_config_unknown",message:`tools.providerConfig has ${t.length===1?"a key":"keys"} the system provider does not read: ${t.join(", ")}.`,hint:`Accepted keys are ${Tt.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 n=e.config.protect,r=e.config.writeRoots;return new qt({env:e.env,dir:e.dir,...Array.isArray(n)?{protect:n.map((i)=>String(i))}:{},...Array.isArray(r)?{writeRoots:r.map((i)=>String(i))}:{}})}function Ns(e){return`'${e.replaceAll("'","'\\''")}'`}class K{#e;constructor(e){this.#e=e.env}has(e){let t=this.#e.PATH??process.env.PATH??"";for(let n of t.split(Is)){if(n==="")continue;try{let r=xs(de(n,e));if(r.isFile()&&(r.mode&73)!==0)return!0}catch{}}return!1}async run(e){let t=fe();await Cs(t,{recursive:!0});let n=Os([e.command,...e.args].join(" ")),r=de(t,`skill-${n}.out`),i=de(t,`skill-${n}.status`),s=[e.command,...e.args].map(Ns).join(" "),o=await Lt({command:s,cwd:e.cwd,env:this.#e,timeoutMs:e.timeoutMs,pty:!1,background:!1,signal:e.signal,outPath:r,statusPath:i}),a=await It(r);if(await Et(i,{force:!0}),!a.spilled&&o.ending!=="backgrounded")await Et(r,{force:!0});let c=o.ending==="killed"||o.ending==="backgrounded",d=a.spilled?`${a.head}
|
|
32
|
+
|
|
33
|
+
… ${a.bytes} bytes in total; the rest is at ${r}
|
|
34
|
+
|
|
35
|
+
${a.tail}`:a.head;return{ok:o.ending==="finished"&&o.code===0,output:o.ending==="backgrounded"?`${d}
|
|
36
|
+
|
|
37
|
+
Still running past ${e.timeoutMs} ms, left going rather than discarded. Output continues to accumulate at ${r}.`:d,...o.code===void 0?{}:{code:o.code},timedOut:c}}}function Os(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}var Ms="0.1.0",Jt={name:"system",version:Ms,dispachApi:"^0.2",permissions:[{kind:"exec",commands:["*"]},{kind:"fs",paths:["<workspace>"],mode:"write"}],setup(e){e.defineToolProvider("system",me),e.defineScriptRunner(new K({env:e.env}))}};import{lookup as Zs}from"node:dns/promises";function Vt(e,t){return new O({code:"web_url_unparseable",message:`That is not a URL: ${JSON.stringify(e)}`,hint:`${t}. 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 Ls(e){return new O({code:"web_scheme_refused",message:`${e} 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 Ps(){return new O({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 ge(e,t,n,r,i){let s=t===e?t:`${e} → ${t}`;return new O({code:"web_address_refused",message:`${s} is ${n}${r===void 0?"":` (${r})`} and will not be fetched${i>0?`, reached by redirect ${i}`:""}.`,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 G(e,t){return new O({code:"web_host_refused",message:`${e} is not a public hostname: ${t}.`,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 Yt(e,t){return new O({code:"web_host_unresolvable",message:`${e} could not be resolved: ${t}`,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 Xt(e,t){return new O({code:"web_request_failed",message:`The request to ${e} did not complete: ${t}`,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 Us(e,t,n){return new O({code:"web_status_failed",message:`${e} answered ${t}${n===""?"":` ${n}`}.`,hint:`${t===404?"The page is not there — check the URL against a search result rather than guessing at the path.":t===403||t===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 zt(e,t){return new O({code:"web_too_many_redirects",message:`${e} redirected more than ${t} 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 Ds(e,t){return new O({code:"web_content_unusable",message:`${e} returned ${t}, 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 js(e,t){return new _({code:"web_search_key_missing",message:`The ${e} search backend needs ${t} and it is not set.`,hint:`Set ${t} 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 Fs(e,t,n){return new O({code:"web_search_failed",message:`${e} answered ${t}: ${n}`,hint:`${t===401||t===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.":t===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 we(e,t){return new _({code:"web_config_invalid",message:`tools.providers.web.${e} ${t}`,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.${e}`})}var Qt=["tavily","brave","exa"];function w(e,t){return typeof e==="object"&&e!==null?e[t]:void 0}function v(e){return typeof e==="string"?e:""}function ve(e){return Array.isArray(e)?e:[]}var Ws={id:"tavily",defaultKeyEnv:"TAVILY_API_KEY",request(e,t,n){return{url:"https://api.tavily.com/search",init:{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({query:e,max_results:t,search_depth:"basic",include_answer:!1})}}},read(e){return ve(w(e,"results")).map((t)=>({title:v(w(t,"title")),url:v(w(t,"url")),snippet:v(w(t,"content"))}))}},Bs={id:"brave",defaultKeyEnv:"BRAVE_API_KEY",request(e,t,n){let r=new URL("https://api.search.brave.com/res/v1/web/search");return r.searchParams.set("q",e),r.searchParams.set("count",String(t)),{url:r.href,init:{method:"GET",headers:{accept:"application/json","x-subscription-token":n}}}},read(e){return ve(w(w(e,"web"),"results")).map((t)=>({title:v(w(t,"title")),url:v(w(t,"url")),snippet:v(w(t,"description"))}))}},Ks={id:"exa",defaultKeyEnv:"EXA_API_KEY",request(e,t,n){return{url:"https://api.exa.ai/search",init:{method:"POST",headers:{"x-api-key":n,"content-type":"application/json"},body:JSON.stringify({query:e,numResults:t,contents:{text:{maxCharacters:400}}})}}},read(e){return ve(w(e,"results")).map((t)=>({title:v(w(t,"title")),url:v(w(t,"url")),snippet:v(w(t,"text"))||v(w(t,"snippet"))}))}},Gs={tavily:Ws,brave:Bs,exa:Ks};function nn(e){return Gs[e]}async function Hs(e,t){let n=t.statusText;try{let r=await t.text();if(r!=="")n=r.length>300?`${r.slice(0,300)}…`:r}catch{}throw Fs(e,t.status,n)}var qs=["script","style","noscript","template","svg","canvas","iframe","head"],Js=/<\/?(?: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,Vs={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 rn(e){return e.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]{1,31});/g,(t,n)=>{if(n.startsWith("#")){let r=n.startsWith("#x")||n.startsWith("#X")?Number.parseInt(n.slice(2),16):Number.parseInt(n.slice(1),10);if(!Number.isFinite(r)||r<0||r>1114111)return t;if(r>=55296&&r<=57343)return t;return String.fromCodePoint(r)}return Vs[n.toLowerCase()]??t})}function Ys(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(e);if(t===null)return;let n=sn(rn(t[1]??""));return n===""?void 0:n}function Xs(e){let t=e;for(let n of qs)t=t.replace(new RegExp(`<${n}\\b[^>]*>[\\s\\S]*?</${n}>`,"gi")," "),t=t.replace(new RegExp(`<${n}\\b[^>]*>[\\s\\S]*$`,"i")," ");return t=t.replace(/<!--[\s\S]*?-->/g," "),t=t.replace(Js,`
|
|
38
|
+
`),t=t.replace(/<[^>]*>/g," "),t=rn(t),t.split(`
|
|
39
|
+
`).map((n)=>sn(n)).filter((n,r,i)=>n!==""||(i[r-1]??"")!=="").join(`
|
|
40
|
+
`).trim()}function sn(e){return e.replace(/\s+/g," ").trim()}function zs(e,t){let n=t.split(";")[0]?.trim().toLowerCase()??"";if(n.includes("html")||n.includes("xml")){let r=Ys(e);return{text:Xs(e),...r===void 0?{}:{title:r}}}return{text:e.trim()}}function Qs(e){let t=e.split(";")[0]?.trim().toLowerCase()??"";if(t==="")return!0;if(t.startsWith("text/"))return!0;return/^application\/(?:json|xml|xhtml\+xml|ld\+json|rss\+xml|atom\+xml|javascript|x-ndjson)$/.test(t)}var eo=new Set(["http:","https:"]),to=[".local",".localhost",".internal",".intranet",".lan",".home.arpa"];function no(e){let t=e.trim();if(t==="")throw Vt(e,"the value is empty");try{return new URL(t)}catch(n){throw Vt(e,n instanceof Error?n.message:String(n))}}function ro(e){if(!eo.has(e.protocol))throw Ls(e.protocol.replace(":",""));if(e.username!==""||e.password!=="")throw Ps();let t=e.hostname.toLowerCase();if(t==="")throw G(e.href,"there is no host in the URL");if(t==="localhost")throw G(t,"it is this machine by definition");for(let r of to)if(t.endsWith(r))throw G(t,`${r} names are resolved on the local network, not the internet`);let n=t.startsWith("[")?"":t;if(n!==""&&!n.includes(".")&&ko(t)===void 0)throw G(t,"a name with no dot in it is completed by the local search domain")}async function io(e,t,n=0){ro(e);let r=e.hostname.toLowerCase(),i=ko(r);if(i!==void 0){if(i.kind!=="public")throw ge(r,r,i.kind,i.range,n);return}let s;try{s=await t(r)}catch(o){throw Yt(r,o instanceof Error?o.message:String(o))}if(s.length===0)throw Yt(r,"it has no addresses");for(let{address:o}of s){let a=ko(o);if(a===void 0)throw ge(r,o,"an address this cannot classify",void 0,n);if(a.kind!=="public")throw ge(r,o,a.kind,a.range,n)}}var so=async(e)=>(await Zs(e,{all:!0,verbatim:!0})).map((n)=>({address:n.address})),ke="web",on=2000000,ye=6000,H=5,oo=3000,ao=20000,co={slug:"web_fetch",provider:ke,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 ho(e){return{spec:co,handler:uo(e)}}function lo(e){let t=Math.max(1000,e-oo);return Math.min(ao,t)}function uo(e){let t=e.maxBytes??on;return async(n,r)=>{let i=String(n.url??""),s=no(i),o=new AbortController,a=()=>{o.abort()};r.signal.addEventListener("abort",a,{once:!0});let c=setTimeout(a,lo(r.deadlineMs));try{for(let d=0;d<=H;d+=1){await io(s,e.lookup,d);let h;try{h=await e.fetch(s.href,{method:"GET",redirect:"manual",signal:o.signal,headers:{"user-agent":e.userAgent,accept:"text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5","accept-language":"en"}})}catch(R){throw Xt(s.href,R instanceof Error?R.message:String(R))}let u=h.headers.get("location");if(fo(h.status)&&u!==null){if(await h.body?.cancel().catch(()=>{return}),d===H)throw zt(i,H);try{s=new URL(u,s)}catch{throw Xt(s.href,`it redirected to an unusable address: ${u}`)}continue}if(!h.ok)throw await h.body?.cancel().catch(()=>{return}),Us(s.href,h.status,h.statusText);let l=h.headers.get("content-type")??"";if(!Qs(l))throw await h.body?.cancel().catch(()=>{return}),Ds(s.href,l.split(";")[0]?.trim()??"binary");let{text:f,read:y,capped:p}=await po(h,t),{title:g,text:m}=zs(f,l);return mo({url:s.href,requested:i,...g===void 0?{}:{title:g},text:m,read:y,capped:p,hops:d})}throw zt(i,H)}finally{clearTimeout(c),r.signal.removeEventListener("abort",a)}}}function fo(e){return e===301||e===302||e===303||e===307||e===308}async function po(e,t){let n=e.body;if(n===null)return{text:"",read:0,capped:!1};let r=n.getReader(),i=new TextDecoder("utf-8"),s=[],o=0,a=!1;try{for(;;){let{done:c,value:d}=await r.read();if(c)break;if(d===void 0)continue;if(o+=d.byteLength,o>=t){let h=d.byteLength-(o-t);s.push(i.decode(d.subarray(0,Math.max(0,h)),{stream:!0})),a=!0;break}s.push(i.decode(d,{stream:!0}))}}finally{await r.cancel().catch(()=>{return})}return s.push(i.decode()),{text:s.join(""),read:Math.min(o,t),capped:a}}function mo(e){let t=[];if(t.push(e.url),e.hops>0&&e.url!==e.requested)t.push(`redirected from ${e.requested} (${e.hops} hop${e.hops===1?"":"s"})`);if(e.title!==void 0)t.push(`title: ${e.title}`);let n=e.text,r=!1;if(n.length>ye)n=n.slice(0,ye),r=!0;let i=[];if(e.capped)i.push(`the download stopped at ${e.read.toLocaleString("en-US")} bytes, so the end of the page is missing`);if(r)i.push(`only the first ${ye.toLocaleString("en-US")} characters are shown`);if(i.length>0)t.push(`incomplete: ${i.join("; ")}`);return t.push(""),t.push(n===""?"(the page has no readable text)":n),t.join(`
|
|
41
|
+
`)}var an=5,cn=10,Zt=300,go=3000,wo=15000,yo={slug:"web_search",provider:ke,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 ${cn}.`,default:an}},required:["query"]}};function bo(e){return{spec:yo,handler:vo(e)}}function vo(e){let t=nn(e.backend);return async(n,r)=>{let i=String(n.query??"").trim();if(i==="")return"No query was given, so nothing was searched for. Call this again with the words you want to look up.";let s=e.env[e.apiKeyEnv]??"";if(s==="")throw js(t.id,e.apiKeyEnv);let o=_o(n.maxResults),{url:a,init:c}=t.request(i,o,s),d=new AbortController,h=()=>{d.abort()};r.signal.addEventListener("abort",h,{once:!0});let u=setTimeout(h,Math.min(wo,Math.max(1000,r.deadlineMs-go)));try{let l=await e.fetch(a,{...c,signal:d.signal});if(!l.ok)await Hs(t.id,l);let f=await l.json();return $o(i,t.read(f).slice(0,o))}finally{clearTimeout(u),r.signal.removeEventListener("abort",h)}}}function _o(e){let t=typeof e==="number"?e:Number(e);if(!Number.isFinite(t))return an;return Math.min(cn,Math.max(1,Math.trunc(t)))}function $o(e,t){if(t.length===0)return`No results for ${JSON.stringify(e)}. 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 n=t.map((r,i)=>{let s=r.snippet.length>Zt?`${r.snippet.slice(0,Zt).trimEnd()}…`:r.snippet;return[`${i+1}. ${r.title===""?"(untitled)":r.title}`,` ${r.url}`,...s===""?[]:[` ${s.replace(/\s+/g," ")}`]].join(`
|
|
42
|
+
`)});return[`${t.length} result${t.length===1?"":"s"} for ${JSON.stringify(e)}:`,"",...n].join(`
|
|
43
|
+
`)}var So="dispach-agent/0.1 (+https://github.com/moeen-mahmud/dispach)";function en(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}class dn{id=ke;#e;constructor(e){let t=e.backend??"tavily",n=nn(t),r=e.fetch??((s,o)=>fetch(s,o)),i=e.lookup??so;this.#e=[bo({backend:t,apiKeyEnv:e.apiKeyEnv??n.defaultKeyEnv,env:e.env,fetch:r}),ho({lookup:i,fetch:r,maxBytes:e.maxBytes??on,userAgent:So})]}available(){return Promise.resolve(this.#e.map((e)=>({slug:e.spec.slug,summary:e.spec.summary})))}resolve(e){let t=new Set(e.map(en));return Promise.resolve(this.#e.filter((n)=>t.has(en(n.spec.slug))))}list(){return Promise.resolve(this.#e.map((e)=>e.spec.slug))}}var tn=["backend","apiKeyEnv","maxBytes"];function _e(e){let t=Object.keys(e.config).filter((s)=>!tn.includes(s));if(t.length>0)throw new _({code:"web_config_unknown",message:`The web provider's configuration has ${t.length===1?"a key":"keys"} it does not read: ${t.join(", ")}.`,hint:`Accepted keys are ${tn.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 n=e.config.backend;if(n!==void 0&&!Qt.includes(String(n)))throw we("backend",`must be one of ${Qt.join(", ")} — got ${JSON.stringify(n)}.`);let r=e.config.apiKeyEnv;if(r!==void 0&&(typeof r!=="string"||r===""))throw we("apiKeyEnv","must be the non-empty name of an environment variable — never the key itself, which fails validation.");let i=e.config.maxBytes;if(i!==void 0&&(typeof i!=="number"||!Number.isFinite(i)||i<1000))throw we("maxBytes","must be a number of at least 1000.");return new dn({env:e.env,...n===void 0?{}:{backend:String(n)},...typeof r==="string"?{apiKeyEnv:r}:{},...typeof i==="number"?{maxBytes:i}:{}})}var To="0.1.0",hn={name:"web",version:To,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["*"]}],setup(e){e.defineToolProvider("web",_e)}};var oe={composio:ie,system:me,web:_e};function Ae(){return new K({env:process.env})}var Na=Object.keys(oe),Z={telegram:V,whatsapp:X},Oa=Object.keys(Z),ae={"@dispach/channel-telegram":Re,"@dispach/channel-whatsapp":De,"@dispach/tools-composio":ct,"@dispach/tools-system":Jt,"@dispach/tools-web":hn},ni=Object.keys(ae);
|
|
44
|
+
export{oe,Ae,Z,ae,ni};
|
|
45
|
+
|
|
46
|
+
//# debugId=D7DC67F91053F80864756E2164756E21
|
|
47
|
+
//# sourceMappingURL=index-34p39yfc.js.map
|