dispach 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -49
- package/dist/APEv2Parser-etzjd528.js +5 -0
- package/dist/{FlacParser-6jwner07.js.map → APEv2Parser-etzjd528.js.map} +1 -1
- package/dist/{AiffParser-n65syezh.js → AiffParser-y21k3fak.js} +3 -3
- package/dist/{AiffParser-n65syezh.js.map → AiffParser-y21k3fak.js.map} +1 -1
- package/dist/App-4w3qkcs4.js +11 -0
- package/dist/{App-pmqmzsb3.js.map → App-4w3qkcs4.js.map} +1 -1
- package/dist/{AsfParser-da1fqvxz.js → AsfParser-wd98k2h4.js} +3 -3
- package/dist/{AsfParser-da1fqvxz.js.map → AsfParser-wd98k2h4.js.map} +1 -1
- package/dist/{ConfigEditor-4nqbeejh.js → ConfigEditor-vk7vxaa6.js} +3 -3
- package/dist/{ConfigEditor-4nqbeejh.js.map → ConfigEditor-vk7vxaa6.js.map} +1 -1
- package/dist/{DsdiffParser-gk95sj7t.js → DsdiffParser-cbfaj500.js} +3 -3
- package/dist/{DsdiffParser-gk95sj7t.js.map → DsdiffParser-cbfaj500.js.map} +1 -1
- package/dist/{DsfParser-b0enevjw.js → DsfParser-tybrja4x.js} +3 -3
- package/dist/{DsfParser-b0enevjw.js.map → DsfParser-tybrja4x.js.map} +1 -1
- package/dist/FlacParser-7t7da7qy.js +5 -0
- package/dist/{APEv2Parser-jdp5yp24.js.map → FlacParser-7t7da7qy.js.map} +1 -1
- package/dist/{KeyProbe-rspsxpsr.js → KeyProbe-5anphmb7.js} +3 -3
- package/dist/{KeyProbe-rspsxpsr.js.map → KeyProbe-5anphmb7.js.map} +1 -1
- package/dist/{MP4Parser-ph7rv2fn.js → MP4Parser-gc94h1n9.js} +3 -3
- package/dist/{MP4Parser-ph7rv2fn.js.map → MP4Parser-gc94h1n9.js.map} +1 -1
- package/dist/{MatroskaParser-fjk1mpct.js → MatroskaParser-cy2k4fac.js} +3 -3
- package/dist/{MatroskaParser-fjk1mpct.js.map → MatroskaParser-cy2k4fac.js.map} +1 -1
- package/dist/{MpegParser-vp7cj8ts.js → MpegParser-c460fwf0.js} +3 -3
- package/dist/{MpegParser-vp7cj8ts.js.map → MpegParser-c460fwf0.js.map} +1 -1
- package/dist/{MusepackParser-v22gft1f.js → MusepackParser-8mq2eabg.js} +3 -3
- package/dist/{MusepackParser-v22gft1f.js.map → MusepackParser-8mq2eabg.js.map} +1 -1
- package/dist/OggParser-7dnc6apg.js +5 -0
- package/dist/{OggParser-as1m8xsa.js.map → OggParser-7dnc6apg.js.map} +1 -1
- package/dist/Picker-j7txnm7w.js +5 -0
- package/dist/{Picker-jkmd5xnx.js.map → Picker-j7txnm7w.js.map} +1 -1
- package/dist/SessionPicker-hpv2ncsb.js +5 -0
- package/dist/{SessionPicker-3712ke3k.js.map → SessionPicker-hpv2ncsb.js.map} +3 -3
- package/dist/SkillBrowser-qc542n71.js +5 -0
- package/dist/{SkillBrowser-qhsyszt4.js.map → SkillBrowser-qc542n71.js.map} +1 -1
- package/dist/{WavPackParser-b4qqavzg.js → WavPackParser-kt7cds9c.js} +3 -3
- package/dist/{WavPackParser-b4qqavzg.js.map → WavPackParser-kt7cds9c.js.map} +1 -1
- package/dist/{WaveParser-fqs1h38f.js → WaveParser-g47ja0vy.js} +3 -3
- package/dist/{WaveParser-fqs1h38f.js.map → WaveParser-g47ja0vy.js.map} +1 -1
- package/dist/WizardApp-q4p979d1.js +5 -0
- package/dist/{WizardApp-qrq36nv8.js.map → WizardApp-q4p979d1.js.map} +3 -3
- package/dist/{channels-gf31stv7.js → channels-4t89qpdt.js} +18 -18
- package/dist/{channels-gf31stv7.js.map → channels-4t89qpdt.js.map} +1 -1
- package/dist/client.d.ts +242 -1
- package/dist/client.js +11 -11
- package/dist/client.js.map +5 -5
- package/dist/config-35r6n1gh.js +24 -0
- package/dist/{config-z2cd0c5f.js.map → config-35r6n1gh.js.map} +1 -1
- package/dist/credential-dpdgg4j6.js +19 -0
- package/dist/{credential-h0wmsjsw.js.map → credential-dpdgg4j6.js.map} +1 -1
- package/dist/{index-3s2q0m64.js → index-0444sh6x.js} +4 -4
- package/dist/{index-3s2q0m64.js.map → index-0444sh6x.js.map} +1 -1
- package/dist/{index-v271gbaz.js → index-095hrkyr.js} +6 -6
- package/dist/{index-v271gbaz.js.map → index-095hrkyr.js.map} +1 -1
- package/dist/index-1x8mzvz7.js +6 -0
- package/dist/{index-rhv6gqpt.js.map → index-1x8mzvz7.js.map} +1 -1
- package/dist/index-2bsardvh.js +5 -0
- package/dist/{index-tny7c703.js.map → index-2bsardvh.js.map} +2 -2
- package/dist/{index-9m6b14b4.js → index-2zjh5zd5.js} +4 -4
- package/dist/{index-9m6b14b4.js.map → index-2zjh5zd5.js.map} +1 -1
- package/dist/{index-t6xnecdx.js → index-323jvr1g.js} +4 -4
- package/dist/{index-t6xnecdx.js.map → index-323jvr1g.js.map} +1 -1
- package/dist/{index-gace5ac7.js → index-3826kf9t.js} +5 -5
- package/dist/{index-gace5ac7.js.map → index-3826kf9t.js.map} +1 -1
- package/dist/index-38gs9anh.js +9 -0
- package/dist/{index-b7qc21s7.js.map → index-38gs9anh.js.map} +1 -1
- package/dist/index-3c5jt6by.js +5 -0
- package/dist/{index-3mvenfbg.js.map → index-3c5jt6by.js.map} +2 -2
- package/dist/{index-k2q76dhw.js → index-3vzf253k.js} +7 -7
- package/dist/{index-k2q76dhw.js.map → index-3vzf253k.js.map} +1 -1
- package/dist/{index-t5d8ey5t.js → index-42e29zs4.js} +4 -4
- package/dist/{index-t5d8ey5t.js.map → index-42e29zs4.js.map} +1 -1
- package/dist/{index-v7mz396x.js → index-4fj1k64j.js} +4 -4
- package/dist/{index-v7mz396x.js.map → index-4fj1k64j.js.map} +1 -1
- package/dist/{index-gqbny9gy.js → index-51x0n5z0.js} +6 -6
- package/dist/{index-gqbny9gy.js.map → index-51x0n5z0.js.map} +1 -1
- package/dist/index-664xcamy.js +110 -0
- package/dist/index-664xcamy.js.map +13 -0
- package/dist/index-7mn8ack9.js +6 -0
- package/dist/{index-qe3ybzh6.js.map → index-7mn8ack9.js.map} +2 -2
- package/dist/index-8edck2pr.js +6 -0
- package/dist/{index-kktaw552.js.map → index-8edck2pr.js.map} +1 -1
- package/dist/index-8h6kewy1.js +9 -0
- package/dist/{index-s4a28ctb.js.map → index-8h6kewy1.js.map} +1 -1
- package/dist/index-8tmv33mr.js +6 -0
- package/dist/{index-v6taf4vn.js.map → index-8tmv33mr.js.map} +1 -1
- package/dist/index-9914wh1d.js +6 -0
- package/dist/index-9914wh1d.js.map +10 -0
- package/dist/{index-y6r1k2yd.js → index-a2eh8dnk.js} +7 -7
- package/dist/{index-y6r1k2yd.js.map → index-a2eh8dnk.js.map} +1 -1
- package/dist/{index-81vj1bxe.js → index-bqdkm3de.js} +4 -4
- package/dist/{index-81vj1bxe.js.map → index-bqdkm3de.js.map} +1 -1
- package/dist/{index-rfa0ztab.js → index-dzy19wtf.js} +4 -4
- package/dist/{index-rfa0ztab.js.map → index-dzy19wtf.js.map} +1 -1
- package/dist/{index-c2qjdz4q.js → index-eqqd4k4f.js} +9 -9
- package/dist/{index-c2qjdz4q.js.map → index-eqqd4k4f.js.map} +1 -1
- package/dist/{index-g1d06ct5.js → index-ew997be5.js} +7 -7
- package/dist/{index-g1d06ct5.js.map → index-ew997be5.js.map} +1 -1
- package/dist/{index-0v2gw4mk.js → index-fa9wvpyw.js} +3 -3
- package/dist/{index-0v2gw4mk.js.map → index-fa9wvpyw.js.map} +1 -1
- package/dist/{index-rvq7t636.js → index-fbsrhcga.js} +4 -4
- package/dist/{index-rvq7t636.js.map → index-fbsrhcga.js.map} +1 -1
- package/dist/index-fcsg95m5.js +11 -0
- package/dist/{index-5nprb9px.js.map → index-fcsg95m5.js.map} +1 -1
- package/dist/{index-dgrwpzz9.js → index-gbkma7ds.js} +4 -4
- package/dist/{index-dgrwpzz9.js.map → index-gbkma7ds.js.map} +1 -1
- package/dist/{index-0m0x1454.js → index-gq1npngp.js} +4 -4
- package/dist/{index-0m0x1454.js.map → index-gq1npngp.js.map} +1 -1
- package/dist/index-haypwvzd.js +308 -0
- package/dist/index-haypwvzd.js.map +21 -0
- package/dist/{index-g8n8rhtr.js → index-jc4kmfwa.js} +4 -4
- package/dist/{index-g8n8rhtr.js.map → index-jc4kmfwa.js.map} +1 -1
- package/dist/index-kjqksgch.js +429 -0
- package/dist/index-kjqksgch.js.map +12 -0
- package/dist/{index-es4bgkbh.js → index-m6fqx0ch.js} +7 -7
- package/dist/{index-es4bgkbh.js.map → index-m6fqx0ch.js.map} +1 -1
- package/dist/{index-60jxyzbe.js → index-ma6p7bt4.js} +4 -4
- package/dist/{index-60jxyzbe.js.map → index-ma6p7bt4.js.map} +1 -1
- package/dist/index-nvc24414.js +6 -0
- package/dist/{index-2yj11ykt.js.map → index-nvc24414.js.map} +1 -1
- package/dist/index-nxhqf597.js +6 -0
- package/dist/{index-m5rmhcez.js.map → index-nxhqf597.js.map} +1 -1
- package/dist/{index-jmnjcw61.js → index-p1zy871m.js} +4 -4
- package/dist/{index-jmnjcw61.js.map → index-p1zy871m.js.map} +1 -1
- package/dist/{index-2pzgta33.js → index-p6ya59m6.js} +5 -5
- package/dist/{index-2pzgta33.js.map → index-p6ya59m6.js.map} +1 -1
- package/dist/{index-6c4p19m1.js → index-pszmnhgq.js} +2 -2
- package/dist/index-qg9bn980.js +1213 -0
- package/dist/{index-1h9pqnec.js.map → index-qg9bn980.js.map} +28 -25
- package/dist/index-qgsdgbk8.js +5 -0
- package/dist/{index-ak304afj.js.map → index-qgsdgbk8.js.map} +2 -2
- package/dist/index-r4ax3x4d.js +74 -0
- package/dist/index-r4ax3x4d.js.map +13 -0
- package/dist/{index-m01mb74d.js → index-snz49ndn.js} +4 -4
- package/dist/{index-m01mb74d.js.map → index-snz49ndn.js.map} +1 -1
- package/dist/index-twn9bfm2.js +8 -0
- package/dist/{index-dwxmy0kx.js.map → index-twn9bfm2.js.map} +2 -2
- package/dist/{index-0p9p6fvc.js → index-wc4entme.js} +10 -10
- package/dist/{index-0p9p6fvc.js.map → index-wc4entme.js.map} +3 -3
- package/dist/{index-wxmqyv4c.js → index-ynsvkqgb.js} +4 -4
- package/dist/{index-wxmqyv4c.js.map → index-ynsvkqgb.js.map} +1 -1
- package/dist/index-ytxbw8py.js +63 -0
- package/dist/{index-fcqy46mh.js.map → index-ytxbw8py.js.map} +2 -2
- package/dist/index-yw3fby4n.js +6 -0
- package/dist/{index-dh2g58s1.js.map → index-yw3fby4n.js.map} +2 -2
- package/dist/{index-ccpq4k6r.js → index-z157at3s.js} +28 -28
- package/dist/{index-ccpq4k6r.js.map → index-z157at3s.js.map} +1 -1
- package/dist/{index-s78sq9g1.js → index-zce9gy22.js} +64 -64
- package/dist/{index-s78sq9g1.js.map → index-zce9gy22.js.map} +1 -1
- package/dist/{index-jv7egrh2.js → index-zw6wyas6.js} +4 -4
- package/dist/{index-jv7egrh2.js.map → index-zw6wyas6.js.map} +1 -1
- package/dist/index.js +308 -292
- package/dist/index.js.map +15 -12
- package/dist/init.d.ts.map +1 -1
- package/dist/lib/agent-template.d.ts +5 -0
- package/dist/lib/agent-template.d.ts.map +1 -1
- package/dist/lib/commands.d.ts.map +1 -1
- package/dist/lib/init-flow.d.ts +7 -30
- package/dist/lib/init-flow.d.ts.map +1 -1
- package/dist/lib/owner.d.ts +49 -0
- package/dist/lib/owner.d.ts.map +1 -0
- package/dist/lib/presets.d.ts +44 -0
- package/dist/lib/presets.d.ts.map +1 -0
- package/dist/lib/provision.d.ts +8 -1
- package/dist/lib/provision.d.ts.map +1 -1
- package/dist/lib/relay-client.d.ts +17 -0
- package/dist/lib/relay-client.d.ts.map +1 -0
- package/dist/lib/schema.d.ts +2 -0
- package/dist/lib/schema.d.ts.map +1 -1
- package/dist/lib/sessions-view.d.ts +2 -0
- package/dist/lib/sessions-view.d.ts.map +1 -1
- package/dist/lib/source.d.ts +17 -0
- package/dist/lib/source.d.ts.map +1 -1
- package/dist/lib/wizard.d.ts.map +1 -1
- package/dist/owner.d.ts +16 -0
- package/dist/owner.d.ts.map +1 -0
- package/dist/run.d.ts.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/transcript.d.ts.map +1 -1
- package/dist/web-zph4h3p9.js +14 -0
- package/dist/{web-stkkwyka.js.map → web-zph4h3p9.js.map} +1 -1
- package/dist/wire.d.ts +31 -0
- package/dist/wire.js +2 -2
- package/dist/wire.js.map +4 -4
- package/dist/wrapper-f662ny3r.js +5 -0
- package/dist/{wrapper-bwxbqa53.js.map → wrapper-f662ny3r.js.map} +1 -1
- package/package.json +5 -2
- package/dist/APEv2Parser-jdp5yp24.js +0 -5
- package/dist/App-pmqmzsb3.js +0 -11
- package/dist/FlacParser-6jwner07.js +0 -5
- package/dist/OggParser-as1m8xsa.js +0 -5
- package/dist/Picker-jkmd5xnx.js +0 -5
- package/dist/SessionPicker-3712ke3k.js +0 -5
- package/dist/SkillBrowser-qhsyszt4.js +0 -5
- package/dist/WizardApp-qrq36nv8.js +0 -5
- package/dist/config-z2cd0c5f.js +0 -24
- package/dist/credential-h0wmsjsw.js +0 -19
- package/dist/index-026q0y3a.js +0 -6
- package/dist/index-026q0y3a.js.map +0 -10
- package/dist/index-1h9pqnec.js +0 -1194
- package/dist/index-1wxw30j1.js +0 -74
- package/dist/index-1wxw30j1.js.map +0 -13
- package/dist/index-2yj11ykt.js +0 -6
- package/dist/index-358nsn9t.js +0 -65
- package/dist/index-358nsn9t.js.map +0 -21
- package/dist/index-3mvenfbg.js +0 -5
- package/dist/index-5nprb9px.js +0 -11
- package/dist/index-ak304afj.js +0 -5
- package/dist/index-b7qc21s7.js +0 -9
- package/dist/index-dh2g58s1.js +0 -6
- package/dist/index-dwxmy0kx.js +0 -8
- package/dist/index-fcqy46mh.js +0 -63
- package/dist/index-kktaw552.js +0 -6
- package/dist/index-m5rmhcez.js +0 -6
- package/dist/index-qe3ybzh6.js +0 -6
- package/dist/index-rhv6gqpt.js +0 -6
- package/dist/index-s4a28ctb.js +0 -9
- package/dist/index-tny7c703.js +0 -5
- package/dist/index-v6taf4vn.js +0 -6
- package/dist/index-y605a1rj.js +0 -429
- package/dist/index-y605a1rj.js.map +0 -11
- package/dist/index-z88f35vs.js +0 -96
- package/dist/index-z88f35vs.js.map +0 -13
- package/dist/web-stkkwyka.js +0 -14
- package/dist/wrapper-bwxbqa53.js +0 -5
- /package/dist/{index-6c4p19m1.js.map → index-pszmnhgq.js.map} +0 -0
package/dist/index-2yj11ykt.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{i,D}from"./index-rfa0ztab.js";import{Re}from"./index-t5d8ey5t.js";import{No,Mo,To,De}from"./index-3s2q0m64.js";import{Box as M,Text as u}from"ink";import{jsx as s,jsxs as a}from"react/jsx-runtime";function _n({rows:e,index:t,chosen:r,window:n,width:c}){let{from:o,to:d}=De(e.length,t,n),k=new Set(r),b=e.reduce((l,m)=>m.kind==="item"?Math.max(l,m.label.length):l,0),g=No(c,b);return a(M,{flexDirection:"column",children:[o>0?a(u,{dimColor:!0,wrap:"truncate",children:[" ",D.ellipsis," ",o," above"]}):null,e.slice(o,d).map((l,m)=>{let p=o+m;if(l.kind!=="item"){let S=l.kind==="source";return a(u,{wrap:"truncate",bold:S,color:S?i.accent:i.muted,children:[S?" ":" ",To(l.label,c-(S?2:4))]},p)}let y=p===t,f=k.has(p),x=Mo({name:l.label,meta:l.meta??"",description:l.description??""},g);return a(u,{wrap:"truncate",children:[s(u,{color:i.accent,children:y?D.pointer:" "}),s(u,{color:f?i.success:i.muted,children:f?D.checked:D.unchecked}),s(u,{bold:y,...f?{color:i.success}:{},children:x.name})," ",s(u,{color:i.muted,children:x.meta}),x.description===""?"":" ",s(u,{dimColor:!0,children:x.description})]},p)}),d<e.length?a(u,{dimColor:!0,wrap:"truncate",children:[" ",D.ellipsis," ",e.length-d," below"]}):null]})}function h(e,t,r){let n=e;for(let c=0;c<=t.length;c+=1){if(t[n.index]===!0)return n;let o=Re(n,{kind:r?"down":"up"});if(o.index===n.index)return;n=o}return}function T(e,t,r,n){if(r.length===0)return e;return h(t,r,n)??h(t,r,!n)??e}function Qt(e,t,r){switch(t.kind){case"move":{if(!r.includes(!0))return e;let n=Re(e.cursor,t.move),c=n.index>=e.cursor.index;return{...e,cursor:T(e.cursor,n,r,c)}}case"toggle":{let n=e.cursor.index;if(r[n]!==!0)return e;let c=e.chosen.includes(n)?e.chosen.filter((o)=>o!==n):[...e.chosen,n].sort((o,d)=>o-d);return{...e,chosen:c}}case"all":{let n=r.flatMap((c,o)=>c?[o]:[]);return{...e,chosen:n}}case"none":return{...e,chosen:[]}}}function kn(e){let t=e.indexOf(!0);return t===-1?0:t}
|
|
3
|
-
export{_n,Qt,kn};
|
|
4
|
-
|
|
5
|
-
//# debugId=85332673F36B8B6D64756E2164756E21
|
|
6
|
-
//# sourceMappingURL=index-2yj11ykt.js.map
|
package/dist/index-358nsn9t.js
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{re,R,ee,B,rA,S,Ge,jA,no,oo,Jr,io,ys,Qs,qA,ms,so,rt,Wr,Br}from"./index-1wxw30j1.js";import{bA,OA,W,Cn}from"./index-1h9pqnec.js";import{randomUUID as mt}from"node:crypto";import{randomUUID as K}from"node:crypto";var Q="1.0",E={parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,taskNotFound:-32001,taskNotCancelable:-32002,unsupportedOperation:-32004,contentTypeNotSupported:-32005,versionNotSupported:-32009},fi=["TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED"],pi=3600000,mi=3000;class k extends Error{code;status;constructor(e,t,n=200){super(t);this.code=e,this.status=n}}class wt{#e;#n;#t=new Map;#r=new Map;#o=new Map;#i=new Map;#a;constructor(e,t){this.#e=e,this.#n=t}transport(e){return{id:e,type:"a2a",limits:{maxMessageChars:1e6,idempotentSend:!0},alwaysAllow:this.#e.peers.flatMap((n)=>n.key===void 0?[]:[n.name]),start:async(n)=>{this.#a=n,n.status("connected")},stop:async()=>{this.#a=void 0},send:async(n)=>this.#y(n)}}observe(e){if(e.type!=="turn.end"||e.agentId!==this.#n)return;let t=e.sessionKey?.startsWith("a2a:")===!0?e.sessionKey.slice(4):void 0;if(t===void 0)return;let n=e.data.reason;if(n!=="final"&&n!=="stopped"){let s=this.#m(t);if(s!==void 0)this.#g(s,"TASK_STATE_FAILED",`The turn ended: ${n??"unknown"}.`);return}let r=this.#m(t);if(r===void 0)return;setTimeout(()=>{if(r.endedAt===void 0&&this.#m(t)===r)this.#g(r,"TASK_STATE_COMPLETED",void 0)},mi).unref?.()}card(e){let t=this.#e.publicUrl??`${e.url.origin}/v1/agents/${encodeURIComponent(this.#n)}/plugins/a2a/`;return Response.json({name:this.#e.card.name,description:this.#e.card.description,version:Q,supportedInterfaces:[{url:t,protocolBinding:"JSONRPC",protocolVersion:Q}],capabilities:{streaming:!0,pushNotifications:!1},defaultInputModes:["text/plain"],defaultOutputModes:["text/plain"],skills:this.#e.card.skills,securitySchemes:{bearer:{httpAuthSecurityScheme:{scheme:"Bearer"}}},securityRequirements:[{schemes:{bearer:{list:[]}}}]})}async rpc(e){let t=null;try{let n=e.request.headers.get("a2a-version");if(n!==null&&n!==""&&!n.startsWith("1."))throw new k(E.versionNotSupported,`A2A-Version ${n} is not supported; this agent speaks ${Q}.`);let r=this.#s(e.caller),i;try{i=await e.request.json()}catch{throw new k(E.parse,"The body is not JSON.")}let s=typeof i==="object"&&i!==null?i:{};if(t=s.id??null,s.jsonrpc!=="2.0"||typeof s.method!=="string")throw new k(E.invalidRequest,"Not a JSON-RPC 2.0 request.");this.#d(r);let o=typeof s.params==="object"&&s.params!==null?s.params:{};switch(s.method){case"SendMessage":return gt(t,await this.#c(r,o));case"SendStreamingMessage":return this.#u(t,await this.#l(r,o));case"GetTask":return gt(t,this.#p(r,o.id).task);case"CancelTask":{let a=this.#p(r,o.id);throw new k(E.taskNotCancelable,a.endedAt===void 0?"A running turn is finished, not cancelled: this agent's turns do not stop when a caller leaves.":"The task has already ended.")}default:throw new k(s.method.startsWith("SendMessage")||s.method.includes("PushNotification")?E.unsupportedOperation:E.methodNotFound,`${s.method} is not supported here.`)}}catch(n){if(n instanceof k)return wi(t,n.code,n.message,n.status);throw n}}#s(e){let t=e.kind==="key"?this.#e.peers.find((n)=>n.key===e.label):void 0;if(t===void 0)throw new k(E.invalidRequest,"This credential is not a peer of this agent. Each peer calls with the operator key its `key` names.",403);return t}#d(e){let t=Date.now(),n=(this.#i.get(e.name)??[]).filter((r)=>t-r<60000);if(n.length>=e.ratePerMinute)throw this.#i.set(e.name,n),new k(E.invalidRequest,`Peer ${e.name} is over ${e.ratePerMinute} requests a minute.`,429);this.#i.set(e.name,[...n,t])}async#c(e,t){let n=await this.#l(e,t);if(t.configuration?.returnImmediately===!0||n.endedAt!==void 0)return this.#f(n);return{task:await this.#h(n,this.#e.waitMs)}}async#l(e,t){this.#b();let n=typeof t.message==="object"&&t.message!==null?t.message:{},r=Array.isArray(n.parts)?n.parts:[];if(r.length===0)throw new k(E.invalidParams,"The message has no parts.");if(r.some((h)=>typeof h.text!=="string"))throw new k(E.contentTypeNotSupported,"Only text parts are accepted.");let i=r.map((h)=>String(h.text)).join(`
|
|
3
|
-
`);if(i.length>e.maxChars)throw new k(E.invalidParams,`The message is ${i.length} characters; ${e.name} may send ${e.maxChars}.`);let s=typeof n.messageId==="string"&&n.messageId!==""?n.messageId:K(),o=this.#o.get(`${e.name}\x1F${s}`),a=o===void 0?void 0:this.#t.get(o);if(a!==void 0)return a;let d=this.#a;if(d===void 0)throw new k(E.unsupportedOperation,"This agent has no running a2a channel. Add `channels: [{type: a2a, id: a2a}]`.",503);let c=typeof n.contextId==="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(n.contextId)?n.contextId:K(),l=`${e.name}:${c}`,u={task:{id:K(),contextId:c,status:{state:"TASK_STATE_WORKING",timestamp:new Date().toISOString()},artifacts:[]},peer:e.name,recipient:l,messageId:s,text:"",waiters:[]};return this.#t.set(u.task.id,u),this.#o.set(`${e.name}\x1F${s}`,u.task.id),this.#r.set(l,[...this.#r.get(l)??[],u.task.id]),d.receive({peerId:l,senderHandle:e.name,senderName:e.name,senderKind:"agent",providerMessageId:s,receivedAt:new Date().toISOString(),text:i}),u}#u(e,t){let n=new TextEncoder,r=(s)=>n.encode(`data: ${JSON.stringify({jsonrpc:"2.0",id:e,result:s})}
|
|
4
|
-
|
|
5
|
-
`),i=new ReadableStream({start:async(s)=>{s.enqueue(r(this.#f(t)));let o=await this.#h(t,this.#e.waitMs);s.enqueue(r({statusUpdate:{taskId:o.id,contextId:o.contextId,status:o.status}})),s.close()}});return new Response(i,{headers:{"content-type":"text/event-stream","cache-control":"no-cache"}})}#h(e,t){if(e.endedAt!==void 0)return Promise.resolve(e.task);return new Promise((n)=>{let r=setTimeout(()=>n(e.task),t);r.unref?.(),e.waiters.push((i)=>{clearTimeout(r),n(i)})})}#p(e,t){this.#b();let n=typeof t==="string"?this.#t.get(t):void 0;if(n===void 0||n.peer!==e.name)throw new k(E.taskNotFound,"No such task.");return n}#f(e){return{task:e.task}}#m(e){let t=this.#r.get(e)?.[0];return t===void 0?void 0:this.#t.get(t)}#y(e){let t=this.#m(e.recipient);if(t===void 0)return{ok:!0};if(t.text+=e.text,e.chunkIndex+1>=e.chunkTotal)this.#g(t,"TASK_STATE_COMPLETED",t.text);return{ok:!0,providerMessageId:t.task.id}}#g(e,t,n){if(e.endedAt!==void 0)return;let r=n===void 0||n===""?void 0:{messageId:K(),role:"ROLE_AGENT",parts:[{text:n}],contextId:e.task.contextId,taskId:e.task.id};e.task={...e.task,status:{state:t,...r===void 0?{}:{message:r},timestamp:new Date().toISOString()},artifacts:r===void 0||t!=="TASK_STATE_COMPLETED"?[]:[{artifactId:K(),parts:r.parts}]},e.endedAt=Date.now(),this.#r.set(e.recipient,(this.#r.get(e.recipient)??[]).filter((i)=>i!==e.task.id));for(let i of e.waiters.splice(0))i(e.task)}#b(){let e=Date.now()-pi;for(let[t,n]of this.#t)if(n.endedAt!==void 0&&n.endedAt<e)this.#t.delete(t),this.#o.delete(`${n.peer}\x1F${n.messageId}`)}}function gi(e){return fi.includes(e)}function gt(e,t){return Response.json({jsonrpc:"2.0",id:e,result:t})}function wi(e,t,n,r){return Response.json({jsonrpc:"2.0",id:e,error:{code:t,message:n}},{status:r})}function yi(e){let t=typeof e==="object"&&e!==null?e:{},n=(s)=>(s??[]).flatMap((o)=>typeof o.text==="string"?[o.text]:[]).join(`
|
|
6
|
-
`);if(t.message!==void 0)return n(t.message.parts);let r=t.task;if(r===void 0)return"The peer answered with nothing readable.";if(!gi(r.status.state))return`The peer is still working on it (task ${r.id}, ${r.status.state}). It has not answered yet.`;let i=n(r.status.message?.parts)||r.artifacts.map((s)=>n(s.parts)).join(`
|
|
7
|
-
`);if(r.status.state!=="TASK_STATE_COMPLETED")return`The peer's task ended ${r.status.state}${i===""?"":`: ${i}`}.`;return i===""?"The peer finished without saying anything.":i}function bi(e,t=fetch){let n=e.peers.filter((i)=>i.url!==void 0),r=new Map;return(i)=>{let s={spec:{slug:"a2a_send",provider:"a2a",summary:"Sends a message to another agent and returns its answer.",whenToUse:`a task needs another agent's help and that agent is one of: ${n.map((o)=>o.name).join(", ")||"(none configured)"}`,whenNotToUse:"for anything you can answer yourself, or to reach anyone not in the peer list",mutating:!0,trust:"untrusted",policyArg:"peer",tags:["a2a","agent"],parameters:{type:"object",properties:{peer:{type:"string",enum:n.map((o)=>o.name),description:"Which agent to ask, by the name the manifest gives it."},text:{type:"string",description:"The message, as you would write it to a colleague."}},required:["peer","text"]}},async handler(o,a){let d=n.find((p)=>p.name===o.peer);if(d?.url===void 0)throw new ee({code:"a2a_peer_unknown",message:`No peer "${String(o.peer)}" to send to.`,hint:`The peers this agent may call are: ${n.map((p)=>p.name).join(", ")||"none"}. Another needs a url in the plugin's peers.`});let c=d.tokenEnv===void 0?void 0:i.env[d.tokenEnv];if(d.tokenEnv!==void 0&&(c===void 0||c===""))throw new ee({code:"a2a_peer_token_missing",message:`Peer ${d.name} needs ${d.tokenEnv}, which is not set.`,hint:`Put the key ${d.name} issued to this agent in ${d.tokenEnv}, in the .env beside the manifest.`});let l=`${a.sessionKey}\x1F${d.name}`,u=AbortSignal.timeout(Math.max(1000,Math.min(60000,a.deadlineMs-5000))),h;try{h=await t(d.url,{method:"POST",headers:{"content-type":"application/json","a2a-version":Q,...c===void 0?{}:{authorization:`Bearer ${c}`}},body:JSON.stringify({jsonrpc:"2.0",id:mt(),method:"SendMessage",params:{message:{messageId:mt(),role:"ROLE_USER",parts:[{text:String(o.text??"")}],...r.has(l)?{contextId:r.get(l)}:{}}}}),signal:AbortSignal.any([a.signal,u])})}catch(p){throw new ee({code:"a2a_peer_unreachable",message:`Peer ${d.name} did not answer: ${p instanceof Error?p.message:String(p)}`,hint:`Check ${d.url} is reachable from this runtime; a timeout is 60 seconds at most.`})}let f=await h.json().catch(()=>({}));if(f.error!==void 0||!h.ok)throw new ee({code:"a2a_peer_refused",message:`Peer ${d.name} refused: ${f.error?.message??`HTTP ${h.status}`}`,hint:"A 401 or 403 means the token in the peer's tokenEnv is wrong; anything else is the peer's own error, quoted."});let g=f.result?.task?.contextId??f.result?.message?.contextId;if(typeof g==="string")r.set(l,g);return yi(f.result)}};return{id:"a2a",resolve:async(o)=>o.includes("a2a_send")?[s]:[]}}}var N=(e)=>typeof e==="string"&&e.trim()!==""?e.trim():void 0,$e=(e,t,n)=>{if(e===void 0)return t;if(typeof e==="number"&&Number.isInteger(e)&&e>0)return e;throw j(`${n} must be a positive whole number.`,n)};function j(e,t){return new B({code:"a2a_config_invalid",message:e,hint:"See @dispach/channel-a2a's config: `card` describes this agent, and `peers` maps each name to the key it calls with (`key`), the URL it is called at (`url` and `tokenEnv`), or both.",field:`plugins[channel-a2a].${t}`})}function vi(e){let t=typeof e==="object"&&e!==null?e:{},n=typeof t.card==="object"&&t.card!==null?t.card:{},r=typeof t.peers==="object"&&t.peers!==null?t.peers:{},i=Object.entries(r).map(([d,c])=>{if(!/^[a-z0-9][a-z0-9-]*$/.test(d))throw j(`Peer "${d}" needs a lowercase slug name; it becomes part of a session key.`,`peers.${d}`);let l=typeof c==="object"&&c!==null?c:{},u=N(l.key),h=N(l.url),f=N(l.tokenEnv);if(u===void 0&&h===void 0)throw j(`Peer "${d}" names neither a key (inbound) nor a url (outbound).`,`peers.${d}`);if(h!==void 0&&!/^https?:\/\//.test(h))throw j(`Peer "${d}"'s url must be absolute http(s).`,`peers.${d}.url`);return{name:d,...u===void 0?{}:{key:u},...h===void 0?{}:{url:h},...f===void 0?{}:{tokenEnv:f},ratePerMinute:$e(l.ratePerMinute,30,`peers.${d}.ratePerMinute`),maxChars:$e(l.maxChars,20000,`peers.${d}.maxChars`)}}),s=i.flatMap((d)=>d.key===void 0?[]:[d.key]);if(new Set(s).size!==s.length)throw j("Two peers name the same key; a key identifies exactly one peer.","peers");let o=Array.isArray(n.skills)?n.skills:[],a=N(t.publicUrl);return{card:{name:N(n.name)??"Agent",description:N(n.description)??"",skills:o.map((d,c)=>{let l=typeof d==="object"&&d!==null?d:{},u=N(l.id);if(u===void 0)throw j("A card skill needs an id.",`card.skills.${c}`);return{id:u,name:N(l.name)??u,description:N(l.description)??"",tags:Array.isArray(l.tags)?l.tags.map(String):[]}})},peers:i,...a===void 0?{}:{publicUrl:a},waitMs:$e(t.waitMs,60000,"waitMs")}}var ki="0.1.0",yt={name:"a2a",version:ki,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["*"]}],setup(e){let t=vi(e.config),n=new wt(t,e.agentId);e.defineChannel("a2a",(r)=>n.transport(r.id)),e.defineRoute({method:"POST",path:"/",capability:"peer",handler:(r)=>n.rpc(r)}),e.defineRoute({method:"GET",path:"/.well-known/agent-card.json",capability:"open",root:"/.well-known/agent-card.json",handler:async(r)=>n.card(r)}),e.defineToolProvider("a2a",bi(t)),e.events.on("turn.end",(r)=>n.observe(r))}};import{readFile as _i}from"node:fs/promises";import{basename as $i}from"node:path";function vt(e){return e.files?.find((t)=>t.url_private_download!==void 0&&(t.subtype==="slack_audio"||t.mimetype?.startsWith("audio/")===!0))}function kt(e){return(e.files??[]).filter((t)=>t.url_private_download!==void 0&&t.mimetype?.startsWith("image/")===!0)}var Si={"&":"&","<":"<",">":">"};function Ti(e,t){return(t===void 0?e.replace(/^\s*<@[A-Z0-9]+>/,""):e.replaceAll(`<@${t}>`,"")).replace(/&(amp|lt|gt);/g,(r)=>Si[r]??r).replace(/\s+/g," ").trim()}function Ei(e,t){if(e.subtype!==void 0&&e.subtype!=="file_share")return;if(e.bot_id!==void 0)return;if(e.user===void 0||e.user===t)return;if(e.channel===void 0||e.ts===void 0)return;let n=e.type==="message"&&e.channel_type==="im";if(!n&&e.type!=="app_mention")return;let r=Ti(e.text??"",t);if(r===""&&vt(e)===void 0&&kt(e).length===0)return;let i=n?e.thread_ts:e.thread_ts??e.ts;return{providerMessageId:`${e.channel}:${e.ts}`,peerId:e.channel,senderId:e.user,senderHandle:e.user,...i===void 0?{}:{thread:i},text:r,receivedAt:new Date(Number(e.ts)*1000).toISOString()}}var Ai="https://slack.com/api/",Ii="https://files.slack.com/",Ci=[1000,2000,5000,15000,30000];class te extends Error{detail;constructor(e){super(e.message);this.detail=e}}class _t{id;type="slack";limits={maxMessageChars:12000,idempotentSend:!1,minSendIntervalMs:1000,attachments:!0,voiceNotes:!0};#e;#n;#t;#r;#o;#i;#a;#s;#d;constructor(e){this.id=e.id,this.#e=e.appToken,this.#n=e.botToken,this.#t=e.fetch??((t,n)=>fetch(t,n)),this.#r=e.socket??((t)=>new WebSocket(t)),this.#o=e.backoffMs??Ci,this.#i=e.apiBase??Ai}async start(e){if(this.#s!==void 0)return;this.#a=e,this.#s=new AbortController,this.#d=this.#c(e,this.#s.signal)}async stop(){this.#s?.abort(),await this.#d?.catch(()=>{}),this.#s=void 0,this.#d=void 0,this.#a?.status("disconnected"),this.#a=void 0}async#c(e,t){let n=0,r=!1;while(!t.aborted)try{let i=await this.#l(t),s=await this.#u(e,i,t,()=>{if(n=0,!r)e.status("connected","Socket Mode");r=!0});if(t.aborted)return;if(s)continue;throw new te({code:"slack_socket_closed",message:"Slack closed the Socket Mode connection before it was established.",hint:"Usually transient and retried. If it persists, check that Socket Mode is enabled for the app (Settings → Socket Mode)."})}catch(i){if(t.aborted)return;if(n+=1,r=!1,n===1||n%8===0){let o=i instanceof te?i.detail:{code:"slack_unreachable",message:`Cannot reach Slack: ${i instanceof Error?i.message:String(i)}`,hint:"Allow outbound HTTPS to slack.com and wss to *.slack.com. Retried with backoff."};e.status("error",o.message),e.error(o)}let s=this.#o[Math.min(n,this.#o.length)-1]??30000;await Oi(s,t)}}async#l(e){let t=await this.#t(`${this.#i}apps.connections.open`,{method:"POST",headers:{authorization:`Bearer ${this.#e}`},signal:e}),n=await t.json().catch(()=>({}));if(n.ok===!0&&typeof n.url==="string")return n.url;let r=n.error??`HTTP ${t.status}`;throw new te({code:"slack_app_token_refused",message:`Slack would not open a Socket Mode connection: ${r}.`,hint:r==="not_allowed_token_type"?"That is not an app-level token. appTokenEnv must hold the xapp-… token from Basic Information → App-Level Tokens, with the connections:write scope.":"Check the app-level token (xapp-…, scope connections:write) and that Socket Mode is enabled for the app. Retried with backoff."})}#u(e,t,n,r){return new Promise((i)=>{let s=this.#r(t),o=!1,a=()=>s.close();n.addEventListener("abort",a,{once:!0}),s.addEventListener("message",(d)=>{let c;try{c=JSON.parse(String(d.data))}catch{return}if(c.envelope_id!==void 0)s.send(JSON.stringify({envelope_id:c.envelope_id}));if(c.type==="hello")o=!0,r();else if(c.type==="disconnect")s.close();else if(c.type==="events_api"&&c.payload?.event){let l=c.payload.event,u=c.payload.authorizations?.[0]?.user_id,h=Ei(l,u),f=vt(l),g=f?.url_private_download;if(h===void 0)return;let p=kt(l).map((m)=>({...m.size===void 0?{}:{sizeBytes:m.size},fetch:(w)=>this.#f(m.url_private_download??"",w)}));e.receive({...h,...p.length===0?{}:{images:p},...f===void 0||g===void 0?{}:{audio:{mimeType:f.mimetype??"audio/webm",...f.duration_ms===void 0?{}:{durationS:f.duration_ms/1000},...f.size===void 0?{}:{sizeBytes:f.size},fetch:(m)=>this.#f(g,m)}}})}}),s.addEventListener("close",()=>{n.removeEventListener("abort",a),i(o)})})}async send(e,t){try{if(e.attachment!==void 0)return await this.#h(e,t);let n=await this.#p("chat.postMessage",{channel:e.recipient,text:e.text,blocks:[{type:"markdown",text:e.text}],...e.thread===void 0?{}:{thread_ts:e.thread}},t);return{ok:!0,...typeof n.ts==="string"?{providerMessageId:n.ts}:{}}}catch(n){if(n instanceof H)return n.result(e.recipient);return{ok:!1,retryable:!0,error:{code:"slack_unreachable",message:`Cannot reach Slack: ${n instanceof Error?n.message:String(n)}`,hint:"Allow outbound HTTPS to slack.com and files.slack.com. Retried."}}}}async#h(e,t){let n=e.attachment,r=await _i(n.path),i=$i(n.path),s=await this.#p("files.getUploadURLExternal",new URLSearchParams({filename:i,length:String(r.byteLength)}),t),{upload_url:o,file_id:a}=s;if(typeof o!=="string"||typeof a!=="string")throw new H(200,"no_upload_url",void 0);let d=await this.#t(o,{method:"POST",headers:{"content-type":n.mimeType},body:r,...t===void 0?{}:{signal:t}});if(!d.ok)throw new H(d.status,`upload_${d.status}`,void 0);return await this.#p("files.completeUploadExternal",{files:[{id:a,title:i}],channel_id:e.recipient,...e.thread===void 0?{}:{thread_ts:e.thread},...e.text===""?{}:{initial_comment:e.text}},t),{ok:!0,providerMessageId:a}}async#p(e,t,n){let r=await this.#t(`${this.#i}${e}`,{method:"POST",headers:{authorization:`Bearer ${this.#n}`,...t instanceof URLSearchParams?{}:{"content-type":"application/json; charset=utf-8"}},body:t instanceof URLSearchParams?t:JSON.stringify(t),...n===void 0?{}:{signal:n}}),i=await r.json().catch(()=>({}));if(i.ok===!0)return i;let s=Number(r.headers.get("retry-after"));throw new H(r.status,typeof i.error==="string"?i.error:`HTTP ${r.status}`,Number.isFinite(s)&&s>0?s*1000:void 0)}async#f(e,t){let n=Ri(e);if(n===void 0)throw Error(`refused to fetch ${e.slice(0,80)} with the bot token: not an https files.slack.com address. Slack serves private files only from there; an event naming anything else is not one to trust.`);let r=await this.#t(`https://files.slack.com/${n}`,{method:"GET",headers:{authorization:`Bearer ${this.#n}`},signal:t});if(!r.ok||r.headers.get("content-type")?.startsWith("text/html")===!0)throw Error(`Slack would not serve the file (${r.status}); the bot token needs the files:read scope`);return new Uint8Array(await r.arrayBuffer())}}function Ri(e){try{let t=new URL(e);if(`${t.protocol}//${t.host}/`!==Ii)return;let n=t.pathname.slice(1);if(!n.startsWith("files-pri/")||n.split("/").some((r)=>r===".."||r===""))return;return`${n}${t.search}`}catch{return}}class H extends Error{status;code;retryAfterMs;constructor(e,t,n){super(t);this.status=e,this.code=t,this.retryAfterMs=n}result(e){return{ok:!1,retryable:this.status===429||this.status>=500||xi.has(this.code),...this.retryAfterMs===void 0?{}:{retryAfterMs:this.retryAfterMs},error:{code:"slack_send_failed",message:`Slack refused the reply to ${e}: ${this.code}.`,hint:Mi[this.code]??"Slack's own error code is above. Rate limits and server errors are retried; anything else is not."}}}}var xi=new Set(["ratelimited","internal_error","fatal_error","service_unavailable","request_timeout"]),Mi={not_in_channel:"The app is not a member of that channel. Invite it (/invite @<app>) and message it again.",channel_not_found:"No channel with that id is visible to the bot: it was deleted, or it is private and the app was never added.",is_archived:"The channel is archived. Unarchive it or deliver somewhere else.",missing_scope:"The bot token lacks chat:write. Add the scope under OAuth & Permissions and reinstall the app.",invalid_auth:"The bot token (xoxb-…) is wrong. Check the env var botTokenEnv names.",token_revoked:"The bot token was revoked, usually by uninstalling the app. Reinstall it and update the token.",account_inactive:"The bot token belongs to an app that was uninstalled. Reinstall it and update the token."};function Oi(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}function bt(e,t,n,r,i){let s=e.config[t],o=typeof s==="string"&&s!==""?s:n,a=e.env[o],d=`channels[${e.id}].${t}`;if(a===void 0||a==="")throw new B({code:"slack_token_missing",message:`Channel "${e.id}" needs ${o}, which is not set.`,hint:`Put the ${i} in ${o}, in the environment or the .env beside the manifest. The agent starts either way, with this channel reported broken.`,field:d});if(!a.startsWith(r))throw new B({code:"slack_token_wrong_kind",message:`${o} does not hold a Slack ${i}; those start with ${r}.`,hint:"Slack issues two tokens and Socket Mode needs both: the app-level token (xapp-…, Basic Information → App-Level Tokens) opens the socket, the bot token (xoxb-…, OAuth & Permissions) sends replies. They are easy to swap.",field:d});return a}var Te=(e)=>new _t({id:e.id,appToken:bt(e,"appTokenEnv","SLACK_APP_TOKEN","xapp-","app-level token"),botToken:bt(e,"botTokenEnv","SLACK_BOT_TOKEN","xoxb-","bot token")}),Ni="0.1.0",$t={name:"channel-slack",version:Ni,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["slack.com","*.slack.com"]},{kind:"env",vars:["SLACK_APP_TOKEN","SLACK_BOT_TOKEN"]}],setup(e){e.defineChannel("slack",Te)}};import{createPublicKey as Pi,verify as Li}from"node:crypto";import{mkdirSync as Fi,readFileSync as Bi,renameSync as Wi,writeFileSync as Ki}from"node:fs";import{dirname as Hi,join as Gi}from"node:path";var Ui="https://login.botframework.com/v1/.well-known/openidconfiguration",ji="https://api.botframework.com",St=300,Di=86400000;class _ extends Error{}function Tt(e){return JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}class It{#e;#n;#t;#r;#o;constructor(e){this.#e=e,this.#n=e.fetch??((t,n)=>fetch(t,n)),this.#t=e.now??Date.now}async verify(e,t){let n=e?.startsWith("Bearer ")?e.slice(7):void 0;if(n===void 0)throw new _("no bearer token");let[r,i,s]=n.split(".");if(r===void 0||i===void 0||s===void 0)throw new _("malformed token");let o,a;try{o=Tt(r),a=Tt(i)}catch{throw new _("unreadable token")}if(o.alg!=="RS256")throw new _(`unexpected algorithm ${String(o.alg)}`);let d=await this.#i(String(o.kid??""));if(d===void 0)throw new _("signed by a key the connector does not publish");if(d.endorsements!==void 0&&t.channelId!==void 0&&!d.endorsements.includes(t.channelId))throw new _(`key not endorsed for channel ${t.channelId}`);if(!Li("RSA-SHA256",Buffer.from(`${r}.${i}`),Pi({key:{kty:d.kty??"RSA",n:d.n??"",e:d.e??""},format:"jwk"}),Buffer.from(s,"base64url")))throw new _("bad signature");let l=this.#t()/1000;if(a.iss!==ji)throw new _(`issuer ${String(a.iss)}`);if(a.aud!==this.#e.appId)throw new _("token is for another bot");if(typeof a.exp!=="number"||a.exp<l-St)throw new _("token expired");if(typeof a.nbf==="number"&&a.nbf>l+St)throw new _("token not yet valid");if(typeof a.serviceUrl!=="string"||a.serviceUrl!==t.serviceUrl)throw new _("serviceUrl is not the one the token was issued for")}async token(e){if(this.#o!==void 0&&this.#o.until>this.#t())return this.#o.value;let t=this.#e.tenantId??"botframework.com",n=await this.#n(`https://login.microsoftonline.com/${encodeURIComponent(t)}/oauth2/v2.0/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.#e.appId,client_secret:this.#e.password,scope:"https://api.botframework.com/.default"}).toString(),...e===void 0?{}:{signal:e}}),r=await n.json().catch(()=>({}));if(!n.ok||typeof r.access_token!=="string")throw new Ae(n.status,r.error_description??`status ${n.status}`);let i=(r.expires_in??3600)*1000;return this.#o={value:r.access_token,until:this.#t()+i-300000},r.access_token}async#i(e){let n=this.#r!==void 0&&this.#t()-this.#r.at<Di?this.#r?.keys.find((s)=>s.kid===e):void 0;if(n!==void 0)return n;let r=await(await this.#n(Ui)).json();if(typeof r.jwks_uri!=="string")return;let i=await(await this.#n(r.jwks_uri)).json();return this.#r={at:this.#t(),keys:i.keys??[]},this.#r.keys.find((s)=>s.kid===e)}}class Ae extends Error{status;constructor(e,t){super(t);this.status=e}}var Et={m4a:"audio/mp4",mp4:"audio/mp4",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"audio/webm",aac:"audio/aac"};function Ct(e){for(let t of e.attachments??[]){let n=t.content?.fileType?.toLowerCase(),r=t.content?.downloadUrl;if(t.contentType==="application/vnd.microsoft.teams.file.download.info"&&r!==void 0&&n!==void 0&&Et[n]!==void 0)return{url:r,mimeType:Et[n],signed:!0};if(t.contentType.startsWith("audio/")&&t.contentUrl!==void 0)return{url:t.contentUrl,mimeType:t.contentType,signed:!1}}return}var zi=new Set(["png","jpg","jpeg","gif","webp"]);function Rt(e){let t=[];for(let n of e.attachments??[]){let r=n.content?.fileType?.toLowerCase(),i=n.content?.downloadUrl;if(n.contentType==="application/vnd.microsoft.teams.file.download.info"&&i!==void 0&&r!==void 0&&zi.has(r))t.push({url:i,signed:!0});else if(n.contentType.startsWith("image/")&&n.contentUrl!==void 0)t.push({url:n.contentUrl,signed:!1})}return t}var Ji={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"};function qi(e){let t=e.recipient?.id,n=e.text??"";for(let r of e.entities??[]){if(r.type!=="mention"||r.text===void 0)continue;n=n.replace(r.text,r.mentioned?.id===t?"":r.mentioned?.name??"")}return n.replace(/<[^<>]*>/g,"").replace(/&(nbsp|amp|lt|gt|quot|#39);/g,(r)=>Ji[r]??r).replace(/\s+/g," ").trim()}function Vi(e){let t=e.recipient?.id;return(e.entities??[]).some((n)=>n.type==="mention"&&n.mentioned?.id===t)}function Yi(e){return e.channelData?.tenant?.id??e.conversation?.tenantId}function Xi(e){if(e.type!=="message"||e.conversation===void 0)return;if(e.from===void 0||e.from.id===e.recipient?.id)return;if((e.conversation.conversationType??"personal")!=="personal"&&!Vi(e))return;let n=qi(e);if(n===""&&Ct(e)===void 0&&Rt(e).length===0)return;let r=e.from.aadObjectId??e.from.id;return{...e.id===void 0?{}:{providerMessageId:`${e.conversation.id}:${e.id}`},peerId:e.conversation.id,senderId:r,senderHandle:r,...e.from.name===void 0?{}:{senderName:e.from.name},text:n,receivedAt:e.timestamp??new Date().toISOString()}}class xt{id;type="teams";limits={maxMessageChars:4000,idempotentSend:!1};#e;#n;#t;#r;#o;#i;#a;constructor(e){this.id=e.id,this.#e=e.auth,this.#n=e.tenantId,this.#r=e.agentId,this.#t=e.fetch??((t,n)=>fetch(t,n)),this.#o=Gi(e.dir,re.stateDir,`teams-${e.id}.json`),this.#a=Zi(this.#o)}async start(e){this.#i=e,e.status("connected",`webhook — POST /v1/channels/${this.id}/webhook/${this.#r??"<agent>"}`)}async stop(){this.#i?.status("disconnected"),this.#i=void 0}async webhook(e){let t=e.body;if(t===void 0||typeof t!=="object"||typeof t.type!=="string")return{status:400,detail:"not an activity"};try{await this.#e.verify(e.headers.authorization,t)}catch(o){if(o instanceof _)return{status:401,detail:o.message};return this.#i?.status("error",`cannot verify activities: ${String(o)}`),{status:503,detail:"cannot verify right now"}}let n=this.#i;if(n===void 0)return{status:503,detail:"channel not started"};if(this.#n!==void 0&&Yi(t)!==this.#n)return{status:200,detail:"other tenant"};if(t.serviceUrl?.startsWith("https://")===!0&&t.conversation!==void 0)this.#c(t.conversation.id,t.serviceUrl);let r=Xi(t);if(r===void 0)return{status:200};let i=Ct(t),s=Rt(t).map((o)=>({fetch:(a)=>this.#d(o.url,o.signed,a)}));return n.receive({...r,...s.length===0?{}:{images:s},...i===void 0?{}:{audio:{mimeType:i.mimeType,fetch:(o)=>this.#d(i.url,i.signed,o)}}}),{status:200}}async send(e,t){return this.#s(e.recipient,{type:"message",text:e.text,textFormat:"markdown"},t)}async typing(e){await this.#s(e,{type:"typing"})}async#s(e,t,n){let r=this.#a[e];if(r===void 0)return{ok:!1,retryable:!1,error:{code:"teams_conversation_unknown",message:`No Teams message has arrived from conversation ${e}, so there is no service address to reply to.`,hint:"Teams gives a bot the address of a conversation only when a message arrives from it. Have someone message the bot in that chat once; a schedule can deliver there afterwards."}};let i;try{i=await this.#e.token(n)}catch(c){let l=c instanceof Ae?c.status:0;return{ok:!1,retryable:l===0||l>=500,error:{code:"teams_token_refused",message:`Entra ID did not issue the bot a token: ${c instanceof Error?c.message:String(c)}`,hint:"Check the app id, the password in the env var the channel names, and tenantId (the bot's own tenant for a single-tenant registration). A wrong secret is permanent; an outage is retried."}}}let s=`${r.replace(/\/?$/,"/")}v3/conversations/${encodeURIComponent(e)}/activities`,o;try{o=await this.#t(s,{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify(t),...n===void 0?{}:{signal:n}})}catch(c){return{ok:!1,retryable:!0,error:{code:"teams_unreachable",message:`Cannot reach ${r}: ${c instanceof Error?c.message:String(c)}`,hint:"Allow outbound HTTPS to smba.trafficmanager.net (the Teams service URLs) and login.microsoftonline.com. Retried."}}}if(o.ok){let c=await o.json().catch(()=>({}));return{ok:!0,...c.id===void 0?{}:{providerMessageId:c.id}}}let a=(await o.text().catch(()=>"")).slice(0,300),d=Number(o.headers.get("retry-after"));return{ok:!1,retryable:o.status===429||o.status>=500,...Number.isFinite(d)&&d>0?{retryAfterMs:d*1000}:{},error:{code:"teams_send_failed",message:`Teams refused the reply (${o.status}): ${a}`,hint:o.status===403?"The bot is not a member of that conversation any more (removed from the chat or team), or its registration does not allow this tenant.":"Teams' own words are above. 429 and 5xx are retried; anything else is not."}}}async#d(e,t,n){let r=t?{}:{authorization:`Bearer ${await this.#e.token(n)}`},i=await this.#t(e,{method:"GET",headers:r,signal:n});if(!i.ok)throw Error(`Teams would not serve the file (${i.status})`);return new Uint8Array(await i.arrayBuffer())}#c(e,t){if(this.#a[e]===t)return;this.#a={...this.#a,[e]:t},Fi(Hi(this.#o),{recursive:!0});let n=`${this.#o}.partial`;Ki(n,`${JSON.stringify(this.#a,null,2)}
|
|
8
|
-
`),Wi(n,this.#o)}}function Zi(e){try{let t=JSON.parse(Bi(e,"utf8"));if(typeof t!=="object"||t===null)return{};return Object.fromEntries(Object.entries(t).filter((n)=>typeof n[1]==="string"))}catch{return{}}}var At=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ee(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var Ce=(e)=>{let t=(o)=>`channels[${e.id}].${o}`,n=Ee(e.config,"appId");if(n===void 0||!At.test(n))throw new B({code:"teams_app_id_invalid",message:`Channel "${e.id}" needs appId, the bot's Entra application id.`,hint:"It is the GUID on the Azure Bot resource (Configuration → Microsoft App ID). Not a secret, so it is written here; the password goes in an env var named by passwordEnv. The agent starts either way, with this channel reported broken.",field:t("appId")});let r=Ee(e.config,"passwordEnv")??"TEAMS_APP_PASSWORD",i=e.env[r];if(i===void 0||i==="")throw new B({code:"teams_password_missing",message:`Channel "${e.id}" needs ${r}, which is not set.`,hint:`Put the bot's client secret in ${r}, in the environment or the .env beside the manifest. It is refused here rather than at the first reply, because an unset variable needs no round trip to Microsoft to discover.`,field:t("passwordEnv")});let s=Ee(e.config,"tenantId");if(s!==void 0&&!At.test(s))throw new B({code:"teams_tenant_invalid",message:`Channel "${e.id}" declares tenantId "${s}", which is not a tenant id.`,hint:"The Entra tenant (directory) id, a GUID. Omit it only for a legacy multi-tenant bot registration.",field:t("tenantId")});return new xt({id:e.id,agentId:e.agentId,dir:e.dir,auth:new It({appId:n,password:i,...s===void 0?{}:{tenantId:s}}),...s===void 0?{}:{tenantId:s}})},Qi="0.1.0",Mt={name:"channel-teams",version:Qi,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["login.botframework.com","login.microsoftonline.com","smba.trafficmanager.net"]},{kind:"env",vars:["TEAMS_APP_PASSWORD"]}],setup(e){e.defineChannel("teams",Ce)}};import{readFile as Ot}from"node:fs/promises";import{basename as Nt}from"node:path";class M 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 es="https://api.telegram.org";class xe{#e;#n;#t;constructor(e){this.#e=e.token,this.#n=e.fetch??((t,n)=>fetch(t,n)),this.#t=io(e.baseUrl??es)}async call(e,t,n){let r;try{r=await this.#n(`${this.#t}/bot${this.#e}/${e}`,{method:"POST",...t instanceof FormData?{body:t}:{headers:{"content-type":"application/json"},body:JSON.stringify(t??{})},...n===void 0?{}:{signal:n}})}catch(s){throw new M({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 ts(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)}sendPhoto(e,t){let n=new FormData;if(n.set("chat_id",e.chatId),n.set("photo",e.photo,e.filename),e.caption!==void 0&&e.caption!=="")n.set("caption",e.caption);if(e.threadId!==void 0)n.set("message_thread_id",String(e.threadId));return this.call("sendPhoto",n,t)}sendVoice(e,t){let n=new FormData;if(n.set("chat_id",e.chatId),n.set("voice",e.voice,e.filename),e.threadId!==void 0)n.set("message_thread_id",String(e.threadId));return this.call("sendVoice",n,t)}getFile(e,t){return this.call("getFile",{file_id:e},t)}async download(e,t){let n=await this.#n(`${this.#t}/file/bot${this.#e}/${e}`,{...t===void 0?{}:{signal:t}});if(!n.ok)throw new M({message:`Downloading ${e} failed with HTTP ${n.status}`,status:n.status,retryable:n.status>=500,detail:{code:"telegram_download_failed",message:`Telegram would not serve ${e} (${n.status}).`,hint:"Bots may download files up to 20 MB; a larger voice note cannot be fetched through the Bot API."}});return new Uint8Array(await n.arrayBuffer())}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 ts(e,t,n){let r=n.description??`HTTP ${t}`,i=n.error_code??t,s=n.parameters?.retry_after;if(i===429)return new M({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 M({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 M({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 M({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 M({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 ns=4096,rs=30,Pt=[1000,2000,5000,15000,30000],is=350;class Ut{id;type="telegram";limits={maxMessageChars:ns,idempotentSend:!1,minSendIntervalMs:is,attachments:!0,voiceNotes:!0};#e;#n;#t;#r;#o;#i=0;#a=!1;#s;#d;constructor(e){this.id=e.id,this.#e=e.api??new xe({token:e.token}),this.#n=e.mode,this.#t=e.webhookUrl,this.#r=e.secretToken}async start(e){if(this.#a)return;if(this.#a=!0,this.#o=e,this.#s=new AbortController,this.#n==="webhook"){let t=this.#t;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.#r===void 0?{}:{secretToken:this.#r}}),e.status("connected",`webhook at ${t}`)}catch(n){e.status("error",n instanceof Error?n.message:String(n)),e.error(Re(n,`registering the webhook for channel "${this.id}"`))}return}this.#d=this.#c(e,this.#s.signal)}async stop(){if(!this.#a)return;this.#a=!1,this.#s?.abort(),await this.#d?.catch(()=>{}),this.#d=void 0,this.#o?.status("disconnected"),this.#o=void 0}async send(e,t){let n=Lt(e.thread);try{let r=e.attachment,i=r===void 0?await this.#e.sendMessage({chatId:e.recipient,text:e.text,...n===void 0?{}:{threadId:n}},t):r.mimeType.startsWith("audio/")?await this.#e.sendVoice({chatId:e.recipient,voice:new Blob([await Ot(r.path)],{type:"audio/ogg"}),filename:Nt(r.path),...n===void 0?{}:{threadId:n}},t):await this.#e.sendPhoto({chatId:e.recipient,photo:new Blob([await Ot(r.path)],{type:r.mimeType}),filename:Nt(r.path),caption:e.text,...n===void 0?{}:{threadId:n}},t);return{ok:!0,providerMessageId:String(i.message_id)}}catch(r){if(r instanceof M)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=Lt(t);await this.#e.sendChatAction({chatId:e,...n===void 0?{}:{threadId:n}})}async webhook(e){if(this.#r!==void 0){let r=e.headers["x-telegram-bot-api-secret-token"]??"";if(!as(r,this.#r))return{status:401,detail:"bad secret token"}}let t=this.#o;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.#l(t,n),{status:200}}async#c(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(Re(i,`checking the bot token for channel "${this.id}"`))}while(this.#a&&!t.aborted)try{let i=await this.#e.getUpdates({offset:this.#i,timeout:rs},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.#i=Math.max(this.#i,s.update_id+1),this.#l(e,s)}catch(i){if(t.aborted)return;let s=Pt[Math.min(n,Pt.length-1)]??1000;if(n+=1,n===1||n%8===0)e.status("error",i instanceof Error?i.message:String(i)),e.error(Re(i,`polling channel "${this.id}"`));await ds(s,t)}}#l(e,t){let n=t.message;if(n===void 0)return;let r=n.text??n.caption??"",i=n.voice??n.audio,s=ss(n);if(r.trim()===""&&i===void 0&&s===void 0)return;if(n.from?.is_bot===!0)return;let o=os(n,r),a=s===void 0?[]:[{...s.file_size===void 0?{}:{sizeBytes:s.file_size},fetch:(d)=>this.#u(s.file_id,"photo",d)}];e.receive({...o,...a.length===0?{}:{images:a},...i===void 0?{}:{audio:{mimeType:i.mime_type??"audio/ogg",...i.duration===void 0?{}:{durationS:i.duration},...i.file_size===void 0?{}:{sizeBytes:i.file_size},fetch:(d)=>this.#u(i.file_id,"voice note",d)}}})}async#u(e,t,n){let r=await this.#e.getFile(e,n);if(r.file_path===void 0)throw Error(`Telegram returned no file path for the ${t}`);return this.#e.download(r.file_path,n)}}function ss(e){let t=e.photo??[];if(t.length>0)return t.findLast((r)=>(r.file_size??0)<=oo)??t[0];let n=e.document;return n?.mime_type?.startsWith("image/")===!0?n:void 0}function os(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),...e.from===void 0?{}:{senderId:String(e.from.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 Lt(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function Re(e,t){if(e instanceof M)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 as(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 ds(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}var Me=(e)=>{let t=e.config,n=G(t,"tokenEnv")??"TELEGRAM_BOT_TOKEN",r=e.env[n];if(r===void 0||r==="")throw new B({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=G(t,"mode")??"longpoll";if(i!=="longpoll"&&i!=="webhook")throw new B({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=G(t,"secretTokenEnv"),o=s===void 0?void 0:e.env[s];if(s!==void 0&&(o===void 0||o===""))throw new B({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=G(t,"apiBaseUrl"),d=G(t,"webhookUrl");return new Ut({id:e.id,token:r,mode:i,...d===void 0?{}:{webhookUrl:d},...o===void 0||o===""?{}:{secretToken:o},...a===void 0?{}:{api:new xe({token:r,baseUrl:a})}})};function G(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var cs="0.1.0",jt={name:"telegram",version:cs,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["api.telegram.org"]},{kind:"env",vars:["TELEGRAM_BOT_TOKEN"]}],setup(e){e.defineChannel("telegram",Me)}};import{isAbsolute as ls,resolve as us}from"node:path";import{chmodSync as Dt,mkdirSync as hs,readdirSync as fs,rmSync as ps}from"node:fs";import{readFile as Ft}from"node:fs/promises";import{join as gs}from"node:path";var ws=65536,bs=1000,Bt=[1000,2000,5000,15000,30000,60000],vs=3,ks=512,Wt=60000,_s=180000,$s=3000,Ss=401,Ts=515,Es={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 Kt(e){let t=e.authState?.creds;if(t===void 0)return!0;return t.registered===!0||t.account!==void 0&&t.account!==null}function Ht(){return typeof globalThis.Bun<"u"}class Jt{id;type="whatsapp";limits={maxMessageChars:ws,idempotentSend:!1,attachments:!0,voiceNotes:!0,minSendIntervalMs:bs};alwaysAllow;#e;#n;#t;#r;#o;#i;#a;#s;#d=!1;#c=0;#l=!1;#u=!0;#h=0;#p=!1;#f=new Set;#m=[];#y;#g=!1;constructor(e){this.id=e.id,this.#e=e.authDir,this.#n=e.pairWith,this.#t=e.deviceName,this.alwaysAllow=e.pairWith===void 0||e.pairWith===""?[]:[e.pairWith],this.#r=e.pairingDelayMs??$s,this.#o=e.api}async start(e){if(this.#d)return;if(this.#d=!0,this.#a=e,Ht())e.error(Es);this.#y=this.#b(e)}async stop(){if(!this.#d)return;this.#d=!1;try{this.#s?.end()}catch{}this.#s=void 0,this.#w?.(),this.#w=void 0,await this.#y?.catch(()=>{}),this.#y=void 0,this.#a?.status("disconnected"),this.#a=void 0}async send(e){let t=this.#s;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 n=e.attachment,i=(await t.sendMessage(Gt(e.recipient),n===void 0?{text:e.text}:n.mimeType.startsWith("audio/")?{audio:await Ft(n.path),mimetype:"audio/ogg; codecs=opus",ptt:!0}:{image:await Ft(n.path),mimetype:n.mimeType,...e.text===""?{}:{caption:e.text}}))?.key?.id;if(i!==void 0&&i!==null){if(this.#m.push(i),this.#m.length>ks)this.#m.shift()}return i===void 0||i===null?{ok:!0}:{ok:!0,providerMessageId:i}}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.#k();try{this.#s?.end()}catch{}this.#s=void 0,this.#c=0,this.#a?.status("disconnected","unpaired — scan the next QR to link a device"),this.#w?.(),this.#w=void 0}async typing(e){await this.#s?.sendPresenceUpdate("composing",Gt(e))}async#b(e){while(this.#d&&!this.#p){try{let n=this.#o??await xs();this.#i=n,hs(this.#e,{recursive:!0,mode:448}),this.#l=this.#n!==void 0&&this.#n!=="";let r=await n.connect({authDir:this.#e,...this.#t===void 0?{}:{deviceName:this.#t},onUpdate:(i)=>this.#S(e,i),onCreds:()=>this.#A(),onMessages:(i)=>this.#T(e,i)});this.#s=r,this.#u=Kt(r),await this.#_(e,r),await this.#$()}catch(n){if(!this.#d)return;this.#v(e,n)}if(!this.#d)return;let t=this.#g;if(this.#g=!1,!t)await zt(this.#E())}}async#_(e,t){let n=this.#n;if(n===void 0||n==="")return;if(Kt(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()+Wt).toISOString()});return}try{if(await zt(this.#r),!this.#d)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()+_s).toISOString()})}catch(r){this.#l=!1,this.#v(e,r)}}#$(){if(!this.#d)return Promise.resolve();return new Promise((e)=>{this.#w=e})}#w;#S(e,t){if(t.qr!==void 0&&t.qr!==""&&!this.#l){e.status("needs_input",`scan to pair channel "${this.id}"`,{kind:"qr",payload:t.qr,expiresAt:new Date(Date.now()+Wt).toISOString()});return}if(t.connection==="open"){this.#h=0,this.#c=0;let n=this.#s?.user;if(this.#f.clear(),n?.id!==void 0)this.#f.add(ne(n.id));if(n?.lid!==void 0)this.#f.add(ne(n.lid));e.status("connected","paired");return}if(t.connection==="close"){let n=t.lastDisconnect?.error?.output?.statusCode;if(n===Ss)if(this.#k(),this.#u)this.#h=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.#h+=1,this.#c+=1,this.#h>=vs)this.#p=!0,e.status("error",`pairing refused ${this.#h} times — not asking again`),e.error({code:"whatsapp_pairing_refused",message:`WhatsApp refused ${this.#h} pairing attempts for channel "${this.id}" and none completed.`,hint:Ht()?"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.#t!==void 0?`deviceName is set ("${this.#t}"), 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(n===Ts)this.#g=!0;else if(this.#c+=1,this.#c===1||this.#c%8===0)e.status("disconnected",t.lastDisconnect?.error?.message??"connection closed");this.#s=void 0,this.#w?.(),this.#w=void 0}}#T(e,t){if(t.type!=="notify")return;for(let n of t.messages){let r=Is(n,{ownJids:this.#f,sentIds:this.#m});if(r===void 0)continue;let i=Cs(n),s=qt(n),o=this.#i,a=async()=>{if(o?.download===void 0)throw Error("this Baileys build cannot download media");return o.download(n)};e.receive({...r,...i===void 0?{}:{audio:{...i,fetch:a}},...s===void 0?{}:{images:[{...s,fetch:a}]}})}}#v(e,t){if(this.#c+=1,this.#c!==1&&this.#c%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."})}#E(){let e=Math.min(this.#c,Bt.length-1);return Bt[e]??1000}#k(){ps(this.#e,{recursive:!0,force:!0})}#A(){try{Dt(this.#e,448);for(let e of fs(this.#e))Dt(gs(this.#e,e),384)}catch{}}}var As={ownJids:new Set,sentIds:[]};function Is(e,t=As){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 l=ne(n),u=e.key?.remoteJidAlt,h=u===null||u===void 0?void 0:ne(u);if(!(t.ownJids.has(l)||h!==void 0&&t.ownJids.has(h)))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()===""&&(i?.audioMessage??void 0)===void 0&&qt(e)===void 0)return;let o=e.messageTimestamp,a=typeof o==="number"?o:typeof o?.toNumber==="function"?o.toNumber():void 0,d=Rs(n,e.key?.remoteJidAlt),c=e.pushName;return{...r===null||r===void 0?{}:{providerMessageId:r},peerId:d,senderHandle:Yt(d),...c===null||c===void 0||c===""?{}:{senderName:c},text:s,receivedAt:new Date(a===void 0?Date.now():a*1000).toISOString()}}function Cs(e){let t=e.message?.audioMessage;if(t===null||t===void 0)return;let n=Vt(t.fileLength);return{mimeType:t.mimetype??"audio/ogg",...typeof t.seconds==="number"?{durationS:t.seconds}:{},...n===void 0?{}:{sizeBytes:n}}}function qt(e){let t=e.message,n=t?.documentMessage,r=t?.imageMessage??(n?.mimetype?.startsWith("image/")===!0?n:void 0);if(r===null||r===void 0)return;let i=Vt(r.fileLength);return i===void 0?{}:{sizeBytes:i}}function Vt(e){return typeof e==="number"?e:typeof e?.toNumber==="function"?e.toNumber():void 0}function Rs(e,t){if(e.endsWith("@s.whatsapp.net"))return e;if(t?.endsWith("@s.whatsapp.net")===!0)return t;return e}function ne(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 Yt(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 Gt(e){return e.includes("@")?e:`${Yt(e)}@s.whatsapp.net`}async function xs(){let e=await import("./index-y6r1k2yd.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),s=e.downloadMediaMessage??(typeof t==="function"?t.downloadMediaMessage:void 0);if(typeof r!=="function"||typeof i!=="function")throw Error("the installed baileys package does not export makeWASocket and useMultiFileAuthState");return{...s===void 0?{}:{download:(o)=>s(o,"buffer",{})},connect:async({authDir:o,deviceName:a,onUpdate:d,onCreds:c,onMessages:l})=>{let{state:u,saveCreds:h}=await i(o),f=r({auth:u,printQRInTerminal:!1,browser:[a??"Ubuntu","Chrome","22.04.4"],logger:Ms(),markOnlineOnConnect:!1});return f.ev.on("connection.update",d),f.ev.on("creds.update",async()=>{await h(),await c()}),f.ev.on("messages.upsert",l),f}}}function Ms(){let e=()=>{},t={level:"silent",trace:e,debug:e,info:e,warn:e,error:e,fatal:e};return t.child=()=>t,t}function zt(e){return new Promise((t)=>setTimeout(t,e))}var Os="./.whatsapp",Ne=(e)=>{let t=Oe(e.config,"authDir")??Os,n=ls(t)?t:us(e.dir,t),r=e.config.api,i=Oe(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=Oe(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 Jt({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 Ns="0.1.0",Xt={name:"whatsapp",version:Ns,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["web.whatsapp.com","*.whatsapp.net"]},{kind:"fs",paths:["<agent>/.whatsapp"],mode:"write"}],setup(e){e.defineChannel("whatsapp",Ne)}};function Oe(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}import{spawn as wo}from"node:child_process";import{readFile as Ps}from"node:fs/promises";class ie extends Error{name="CredentialsRefusedError";status;code;detail;constructor(e,t,n){super(`The credentials endpoint ${e>=500?"failed":"refused"} with status ${e}${t===void 0?"":` (${t})`}${n===void 0?"":`: ${n}`}`);this.status=e,this.code=t,this.detail=n}}var Ls=new Set(["127.0.0.1","localhost","[::1]","169.254.170.2","169.254.170.23","[fd00:ec2::23]"]),Us=300000;function Le(e,t=fetch){let n=e.AWS_CONTAINER_CREDENTIALS_FULL_URI;if(n===void 0||n==="")return;let r;try{r=new URL(n)}catch{return}if(r.protocol!=="https:"&&!(r.protocol==="http:"&&Ls.has(r.hostname)))return;let i;return async()=>{if(i?.expiration!==void 0&&i.expiration.getTime()-Date.now()>Us)return i;let s=e.AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE,o=s!==void 0&&s!==""?(await Ps(s,"utf8")).trim():e.AWS_CONTAINER_AUTHORIZATION_TOKEN,a=await t(r,{headers:o===void 0||o===""?{}:{authorization:o},signal:AbortSignal.timeout(5000)}),d=await a.text(),c={};try{let p=JSON.parse(d);if(typeof p==="object"&&p!==null)c=p}catch{}let l=(...p)=>{for(let m of p)if(typeof c[m]==="string")return c[m];return};if(a.status>=400)throw new ie(a.status,l("code","Code"),l("message","Message"));let u=l("AccessKeyId"),h=l("SecretAccessKey");if(!a.ok||u===void 0||h===void 0)throw Error(`The credentials endpoint answered ${a.status} without AccessKeyId and SecretAccessKey.`);let f=l("Token"),g=l("Expiration");return i={accessKeyId:u,secretAccessKey:h,...f===void 0?{}:{sessionToken:f},...g===void 0?{}:{expiration:new Date(g)}},i}}var js={ThrottlingException:429,ServiceUnavailableException:503,InternalServerException:500,ModelNotReadyException:503,ModelStreamErrorException:500,ModelTimeoutException:408},Ds=/ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|socket hang up|TimeoutError/;function Fs(e){if(typeof e!=="object"||e===null)return{name:"Error",message:String(e),status:void 0};let t=e,n=t.$metadata?.httpStatusCode;return{name:typeof t.name==="string"?t.name:"Error",message:typeof t.message==="string"?t.message:String(e),status:typeof n==="number"?n:void 0}}function Bs(e,t,n,r){let{name:i,message:s,status:o}=Fs(e),a=js[i];if(a!==void 0){let l=o??a;return{retryable:!0,status:l,error:new rA({code:"model_http_error",message:`Bedrock ${i} for ${t} in ${n}.`,detail:s,hint:i==="ThrottlingException"?"Bedrock is throttling this account or model. Retries were spent; raise the model's quota in Service Quotas, spread load across a cross-region inference profile (eu., us., global.), or add a fallback.":"Bedrock reported a service-side failure and retries were spent. It is usually transient; a fallback under model.<role>.fallbacks covers it.",field:r,status:l,cause:e})}}if(i==="CredentialsRefusedError"){let l=e,u=typeof l.status==="number"?l.status:403,h=typeof l.code==="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(l.code)?l.code:void 0;if(u>=500)return{retryable:!0,status:u,error:new rA({code:h??"bedrock_credentials_unavailable",message:`The AWS credentials endpoint could not issue credentials for Bedrock (${t} in ${n}): status ${u}${h===void 0?"":`, ${h}`}${typeof l.detail==="string"?` — ${l.detail}`:""}.`,hint:"The container-credentials endpoint failed rather than declined: the service vending credentials is down or could not reach its own source. It is usually temporary; Dispach retried, and the next turn asks again.",field:r,status:u,cause:e})};return{retryable:!1,status:u,error:new rA({code:h??"bedrock_credentials_refused",message:`The AWS credentials endpoint refused to issue credentials for Bedrock (${t} in ${n}): status ${u}${h===void 0?"":`, ${h}`}${typeof l.detail==="string"?` — ${l.detail}`:""}.`,hint:"The container-credentials endpoint answered and declined: the decision of the service vending credentials (a budget or credit stop, a revoked user), not a missing configuration. Its own code is this error's code. Dispach does not retry it.",field:r,status:u,cause:e})}}let d=/responded with status: (\d{3})/.exec(s);if(i==="CredentialsProviderError"&&d!==null)return{retryable:!1,status:Number(d[1]),error:new rA({code:"bedrock_credentials_refused",message:`The AWS credentials endpoint refused to issue credentials for Bedrock (${t} in ${n}): status ${d[1]}.`,hint:"The container-credentials endpoint answered and declined, which is the endpoint's decision rather than a missing configuration — a vending service may refuse once a budget is spent. Check that service; Dispach does not retry it.",field:r,status:Number(d[1]),cause:e})};if(i==="CredentialsProviderError"||/Could not load credentials/i.test(s))return{retryable:!1,status:void 0,error:new rA({code:"bedrock_credentials_missing",message:`No AWS credentials were found for Bedrock (${t} in ${n}).`,hint:"Credentials come from the default AWS chain: AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY in the process environment, a container-credentials endpoint (AWS_CONTAINER_CREDENTIALS_FULL_URI), EKS Pod Identity, or the instance role. Never a manifest field. For a named profile, set options.profile.",field:r,cause:e})};if(i==="AccessDeniedException"||o===403)return{retryable:!1,status:403,error:new rA({code:"model_access_denied",message:`Bedrock refused ${t} in ${n}: these credentials may not invoke it.`,detail:s,hint:/being verified/i.test(s)?"The AWS account is new and AWS is still verifying it, which it says takes under two hours. Nothing in the manifest or the IAM policy changes this; retry once the account is verified.":'Either the credential is invalid or expired (Bedrock says "security token … invalid"), or it is not allowed to invoke this model. For the second, check the IAM policy grants bedrock:InvokeModelWithResponseStream on the model or inference profile, and that model access is enabled in the Bedrock console for this region. An embedder that revokes credentials as a budget stop lands here on purpose, which is why this never falls back.',field:r,status:403,cause:e})};if(i==="ResourceNotFoundException"||o===404)return{retryable:!1,status:404,error:new rA({code:"model_not_found",message:`Bedrock has no model ${t} in ${n}.`,detail:s,hint:/use case details/i.test(s)?"Anthropic models on Bedrock need a one-time use-case form per AWS account: Bedrock console → Model catalog → an Anthropic model → submit the use case details. It applies about 15 minutes after submission.":"Check the model id and region together: a cross-region profile id starts with its geography (eu., us., apac., global.), and a base model id needs on-demand access in that exact region.",field:r,status:404,cause:e})};if(Ds.test(`${i} ${s}`))return{retryable:!0,status:void 0,error:new rA({code:"model_unreachable",message:`Cannot reach Bedrock in ${n}.`,detail:s,hint:"Check outbound HTTPS to bedrock-runtime.<region>.amazonaws.com from this host; a default-deny network policy needs that endpoint listed.",field:r,cause:e})};let c=o??400;return{retryable:!1,status:c,error:new rA({code:"model_http_error",message:`Bedrock ${i} for ${t}.`,detail:s,hint:i==="ValidationException"?"Bedrock refused the request as malformed. Its own words, in `detail`, name the field; a model that does not support a feature asked for (tools, thinking, prompt caching) is the usual cause.":"Bedrock refused the request. Its own words are in `detail`.",field:r,status:c,cause:e})}}var Pe={cachePoint:{type:"default"}},Ws={"image/png":"png","image/jpeg":"jpeg","image/gif":"gif","image/webp":"webp"};function Zt(e){return/(^|[./])anthropic\.claude|(^|[./])amazon\.nova/.test(e)}function Qt(e){let t=/anthropic\.claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d+))?/.exec(e);if(t!==null){let r=Number(t[3]??"0");return{family:t[1]??"",version:Number(t[2])+(r<100?r/10:0)}}let n=/anthropic\.claude-(\d+)(?:-(\d+))?-(opus|sonnet|haiku)/.exec(e);if(n!==null)return{family:n[3]??"",version:Number(n[1])+Number(n[2]??"0")/10};return/anthropic\.claude/.test(e)?{family:"",version:0}:void 0}function se(e){if(/(^|[./])openai\./.test(e))return"openai";let t=Qt(e);if(t===void 0)return;if(t.family==="fable"||t.family==="mythos")return"adaptive";if(t.family==="haiku")return t.version>=5.5?"adaptive":"budget";return t.version>=4.7?"adaptive":"budget"}function en(e){let t=Qt(e);if(t===void 0)return"disabled";if(t.family==="fable"||t.family==="mythos")return"low";if(t.family==="opus"&&t.version>=5.5)return"low";if(t.family==="sonnet"&&t.version>=5.5)return"between_tools";return"disabled"}function tn(e){return se(e)==="adaptive"||/(^|[./])openai\.gpt-6/.test(e)}function Ks(e,t){let n=[];if(se(e.id)==="adaptive"&&e.reasoningEffort==="none"&&en(e.id)==="low")n.push({code:"model_thinking_always_on",message:`${e.id} cannot turn thinking off, so ${t}.reasoningEffort: none runs at low effort.`,hint:`Set ${t}.reasoningEffort: low to say so explicitly, which also silences this.`,field:`${t}.reasoningEffort`});if(tn(e.id)&&(e.temperature!==void 0||e.topP!==void 0))n.push({code:"model_sampling_unsupported",message:`${e.id} does not accept temperature or topP, so ${t} sends neither.`,hint:`Remove temperature and topP from ${t}; steer this model with reasoningEffort instead.`,field:t});return n}var Hs=32768,Gs=16384,zs={minimal:1024,low:2048,medium:8192,high:16384};function Js(e){try{let t=JSON.parse(e===""?"{}":e);return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:{value:t}}catch{return{raw:e}}}function qs(e){let t=[];for(let n of e.thinking??[])t.push(n.redacted!==void 0?{reasoningContent:{redactedContent:Uint8Array.from(Buffer.from(n.redacted,"base64"))}}:{reasoningContent:{reasoningText:{text:n.text,...n.signature===void 0?{}:{signature:n.signature}}}});if(e.content!=="")t.push({text:e.content});for(let n of e.toolCalls??[])t.push({toolUse:{toolUseId:n.id,name:n.name,input:Js(n.arguments)}});return t}function Vs(e){if(e.role==="assistant")return{role:"assistant",content:qs(e)};if(e.role==="tool")return{role:"user",content:[{toolResult:{toolUseId:e.toolCallId??"",content:[{text:e.content===""?"(no output)":e.content}]}}]};let t=e.role==="system"&&e.content!==""?`<system>
|
|
9
|
-
${e.content}
|
|
10
|
-
</system>`:e.content,n=t===""?[]:[{text:t}];for(let r of e.images??[])n.push({image:{format:Ws[r.mediaType],source:{bytes:Uint8Array.from(Buffer.from(r.data,"base64"))}}});return{role:"user",content:n}}function Ys(e){let t=e.findIndex((i)=>i.role!=="system");if(t===-1||e[t]?.role==="user")return e;let n=e.findIndex((i)=>i.turnInput===!0);if(n===-1||n<t)return e;let r=e[n];return[...e.slice(0,t),r,...e.slice(t,n),...e.slice(n+1)]}function Xs(e,t){let n=Zt(e.model)&&t.capabilities?.promptCache!=="none",r=[],i=[],s=!0;for(let m of Ys(e.messages)){if(s&&m.role==="system"){if(m.content!=="")r.push({text:m.content});if(n&&m.cacheBreakpoint===!0)r.push(Pe);continue}s=!1;let{role:w,content:v}=Vs(m);if(n&&m.cacheBreakpoint===!0&&v.length>0)v.push(Pe);if(v.length===0)continue;let Z=i.at(-1);if(Z!==void 0&&Z.role===w)Z.content=[...Z.content??[],...v];else i.push({role:w,content:v})}let o=i.at(-1),a=/(^|[./])amazon\.nova/.test(e.model)&&(o?.content??[]).some((m)=>m.toolResult!==void 0);if(n&&o!==void 0&&!a&&o.content?.at(-1)?.cachePoint===void 0)o.content=[...o.content??[],Pe];let d=se(e.model),c=e.reasoningEffort,l=d==="budget"&&c!==void 0?zs[c==="xhigh"||c==="max"?"high":c]:void 0,u=d==="adaptive"?Zs(e.model,c):void 0,h=l===void 0&&!tn(e.model),f=l!==void 0?Math.max(e.maxTokens??0,l+Gs):u?.thinking===!0?e.maxTokens??Hs:e.maxTokens,g={...f===void 0?{}:{maxTokens:f},...!h||e.temperature===void 0?{}:{temperature:e.temperature},...!h||e.topP===void 0?{}:{topP:e.topP}},p=l!==void 0?{thinking:{type:"enabled",budget_tokens:l}}:u!==void 0?u.fields:d==="openai"&&c!==void 0&&c!=="none"?{reasoning:{effort:c==="minimal"?"low":c}}:void 0;return{modelId:e.model,messages:i,...r.length===0?{}:{system:r},...Object.keys(g).length===0?{}:{inferenceConfig:g},...e.tools===void 0||e.tools.length===0?{}:{toolConfig:{tools:e.tools.map((m)=>({toolSpec:{name:m.name,description:m.description,inputSchema:{json:m.parameters}}}))}},...p===void 0?{}:{additionalModelRequestFields:p}}}function Zs(e,t){if(t===void 0)return;if(t==="none"){let n=en(e);if(n==="low")return{fields:{thinking:{type:"adaptive"},output_config:{effort:"low"}},thinking:!0};return{fields:{thinking:{type:n}},thinking:!1}}return{fields:{thinking:{type:"adaptive"},output_config:{effort:t==="minimal"?"low":t}},thinking:!0}}var eo={end_turn:"stop",stop_sequence:"stop",tool_use:"tool_calls",max_tokens:"length",model_context_window_exceeded:"length",content_filtered:"content_filter",guardrail_intervened:"content_filter",refusal:"content_filter"},to="<thinking>",ro="</thinking>";function ao(e,t){for(let n=Math.min(t.length-1,e.length);n>0;n-=1)if(t.startsWith(e.slice(-n)))return n;return 0}class nn{#e="";#n=!1;#t=!1;push(e){let t=[],n=this.#e+e;this.#e="";for(;;){let r=this.#n?ro:to,i=n.indexOf(r);if(i===-1){let s=ao(n,r);return this.#e=n.slice(n.length-s),t.push(...this.#r(n.slice(0,n.length-s))),t}if(t.push(...this.#r(n.slice(0,i))),this.#n=!this.#n,!this.#n)this.#t=!0;n=n.slice(i+r.length)}}flush(){let e=this.#e;return this.#e="",this.#r(e)}#r(e){if(this.#n)return e===""?[]:[{type:"reasoning",delta:e}];let t=this.#t?e.trimStart():e;if(t==="")return[];return this.#t=!1,[{type:"text",delta:t}]}}async function*co(e,t={}){let n=new Map,r=t.thinkingTags===!0?new nn:void 0;for await(let i of e){if(i.contentBlockStart!==void 0){let a=i.contentBlockStart.start?.toolUse;if(a!==void 0)n.set(i.contentBlockStart.contentBlockIndex??0,{kind:"tool",id:a.toolUseId??"",name:a.name??"",input:""});continue}if(i.contentBlockDelta!==void 0){let a=i.contentBlockDelta.contentBlockIndex??0,d=i.contentBlockDelta.delta;if(d?.text!==void 0){if(r!==void 0)yield*r.push(d.text);else if(d.text!=="")yield{type:"text",delta:d.text}}else if(d?.toolUse!==void 0){let c=n.get(a);if(c?.kind==="tool")c.input+=d.toolUse.input??""}else if(d?.reasoningContent!==void 0){let c=n.get(a);if(c?.kind!=="reasoning")c={kind:"reasoning",text:""},n.set(a,c);let l=d.reasoningContent;if(l.text!==void 0&&l.text!=="")c.text+=l.text,yield{type:"reasoning",delta:l.text};if(l.signature!==void 0)c.signature=l.signature;if(l.redactedContent!==void 0)c.redacted=Buffer.from(l.redactedContent).toString("base64")}continue}if(i.contentBlockStop!==void 0){let a=i.contentBlockStop.contentBlockIndex??0,d=n.get(a);if(n.delete(a),d?.kind==="tool")yield{type:"tool_call",call:{id:d.id,name:d.name,arguments:d.input}};else if(d?.kind==="reasoning")yield{type:"thinking_block",block:{text:d.text,...d.signature===void 0?{}:{signature:d.signature},...d.redacted===void 0?{}:{redacted:d.redacted}}};continue}if(i.messageStop!==void 0){if(r!==void 0)yield*r.flush();let a=i.messageStop.stopReason??"end_turn";yield{type:"finish",reason:eo[a]??a};continue}let s=i.metadata?.usage;if(s!==void 0){let{cacheReadInputTokens:a,cacheWriteInputTokens:d}=s;yield{type:"usage",promptTokens:(s.inputTokens??0)+(a??0)+(d??0),completionTokens:s.outputTokens??0,...a===void 0?{}:{cachedPromptTokens:a,cacheSource:"metadata.usage.cacheReadInputTokens"},...d===void 0?{}:{cacheWriteTokens:d}};continue}let o=i.throttlingException??i.serviceUnavailableException??i.internalServerException??i.modelStreamErrorException??i.validationException;if(o!==void 0)throw o}}var lo=async(e)=>{let t=await import("./index-ak304afj.js"),n=e.profile===void 0?Le(process.env):void 0,r=new t.BedrockRuntimeClient({region:e.region,maxAttempts:1,...e.profile===void 0?{}:{profile:e.profile},...n===void 0?{}:{credentials:n}});return async(i,s)=>{let o=await r.send(new t.ConverseStreamCommand(i),{abortSignal:s});if(o.stream===void 0)throw Error("Bedrock returned a ConverseStream response with no stream.");return o.stream}};function uo(e){return e instanceof Error&&/bound to a different conversation/i.test(e.message)}function ho(e){let t=!1,n=(e.messages??[]).map((r)=>{let i=(r.content??[]).filter((s)=>{let o=s.reasoningContent!==void 0;return t||=o,!o});return{...r,content:i}}).filter((r)=>r.content.length>0);return t?{...e,messages:n}:void 0}var fo=/(^|[./])amazon\.nova/,po={safeParse(e){let t=typeof e==="object"&&e!==null?e:{},n=Object.keys(t).find((r)=>r!=="region"&&r!=="profile");if(n!==void 0)return{success:!1,error:{issues:[{message:`unknown option "${n}" (takes region, profile)`}]}};if(typeof t.region!=="string"||t.region==="")return{success:!1,error:{issues:[{message:"region is required, e.g. eu-west-1"}]}};if(t.profile!==void 0&&typeof t.profile!=="string")return{success:!1,error:{issues:[{message:"profile must be a string"}]}};return{success:!0,data:t}}};function mo(e,t){let n=Math.min(e.baseDelayMs*2**(t-1),e.maxDelayMs);return Math.round(n*(0.5+Math.random()/2))}function go(e,t){return new Promise((n)=>{if(t.aborted)return n();let r=setTimeout(()=>{t.removeEventListener("abort",i),n()},e),i=()=>{clearTimeout(r),n()};t.addEventListener("abort",i,{once:!0})})}function Ue(e=lo){return{optionsSchema:po,capabilities:(t,n)=>{let r=n.capabilities?.promptCache===void 0&&Zt(n.id)?{...t,promptCache:"bedrock"}:t;return se(n.id)==="openai"?{...r,traceAfterInput:!0}:r},warnings:(t,n)=>Ks(t,n),create(t){let n=t.options;if(n===void 0)throw new B({code:"model_transport_options_invalid",message:`${t.field}.options are required for the bedrock-converse transport.`,hint:"Set options.region to the Bedrock region, e.g. eu-west-1, and options.profile for a named AWS profile.",field:`${t.field}.options`});let r=t.retry??ys,i;return{id:t.id,async*chat(s,o){i??=e(n);let a=await i,d=Xs(s,t.config),c=!1;for(let l=1;;l+=1){let u=!1;try{for await(let h of co(await a(d,o),{thinkingTags:fo.test(t.config.id)}))u=!0,yield h;return}catch(h){if(o.aborted)return;if(!u&&!c&&uo(h)){let p=ho(d);if(p!==void 0){d=p,c=!0,t.onRetry?.({status:400,attempt:l,delayMs:0});continue}}let f=Bs(h,s.model,n.region,t.field);if(u||!f.retryable||l>=r.attempts)throw f.error;let g=mo(r,l);if(t.onRetry?.({status:f.status??0,attempt:l,delayMs:g}),await go(g,o),o.aborted)return}}}}}}}var rn={name:"model-bedrock",version:Ge,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["bedrock-runtime.*.amazonaws.com"]},{kind:"env",vars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_PROFILE","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"]}],setup(e){e.defineModelTransport("bedrock-converse",Ue())}};var an=16000,yo=(e,t)=>new Promise((n,r)=>{let i=wo("ffmpeg",["-hide_banner","-loglevel","error","-i","pipe:0"].concat(["-f","s16le","-ac","1","-ar",String(an),"pipe:1"]),{stdio:["pipe","pipe","pipe"]}),s=[],o=[],a=()=>i.kill("SIGKILL");t.addEventListener("abort",a,{once:!0}),i.stdout.on("data",(d)=>s.push(d)),i.stderr.on("data",(d)=>o.push(d)),i.on("error",(d)=>{t.removeEventListener("abort",a),r(d)}),i.on("close",(d)=>{if(t.removeEventListener("abort",a),d===0)n(new Uint8Array(Buffer.concat(s)));else r(Error(Buffer.concat(o).toString("utf8").trim()||`ffmpeg exited ${d}`))}),i.stdin.on("error",()=>{}),i.stdin.end(Buffer.from(e))});function je(e){if(e.profile!==void 0)return{profile:e.profile};let t=Le(process.env);return t===void 0?{}:{credentials:t}}var bo={async transcribe(e){let t=await import("./index-3mvenfbg.js"),n=new t.TranscribeStreamingClient({region:e.region,...je(e)});return async(r,i)=>{let s=await n.send(new t.StartStreamTranscriptionCommand(r),{abortSignal:i});if(s.TranscriptResultStream===void 0)throw Error("Transcribe returned no result stream.");return s.TranscriptResultStream}},async invoke(e){let t=await import("./index-ak304afj.js"),n=new t.BedrockRuntimeClient({region:e.region,...je(e)});return async(r,i)=>{let s=await n.send(new t.InvokeModelCommand({modelId:r.modelId,contentType:"application/json",accept:"application/json",body:r.body}),{abortSignal:i});return new TextDecoder().decode(s.body)}},async speak(e){let t=await import("./index-tny7c703.js"),n=new t.PollyClient({region:e.region,...je(e)});return async(r,i)=>{let s=await n.send(new t.SynthesizeSpeechCommand({Text:r.text,OutputFormat:"ogg_opus",VoiceId:r.voiceId,Engine:r.engine,...r.languageCode===void 0?{}:{LanguageCode:r.languageCode}}),{abortSignal:i});if(s.AudioStream===void 0)throw Error("Polly returned no audio.");return{bytes:await s.AudioStream.transformToByteArray(),...s.RequestCharacters===void 0?{}:{characters:s.RequestCharacters}}}},decode:yo},sn=new Set(["region","profile","languageCode","sampleRate","voiceId","engine"]),vo={safeParse(e){let t=typeof e==="object"&&e!==null?e:{},n=(i)=>({success:!1,error:{issues:[{message:i}]}}),r=Object.keys(t).find((i)=>!sn.has(i));if(r!==void 0)return n(`unknown option "${r}" (takes ${[...sn].join(", ")})`);if(typeof t.region!=="string"||t.region==="")return n("region is required, e.g. eu-west-2");if(t.sampleRate!==void 0&&typeof t.sampleRate!=="number")return n("sampleRate is a number of hertz");for(let i of["voiceId","engine","languageCode"])if(t[i]!==void 0&&typeof t[i]!=="string")return n(`${i} is text, e.g. ${i==="engine"?"neural":i==="voiceId"?"Joanna":"en-GB"}`);return{success:!0,data:t}}};function ko(e){let t=e.split(";")[0]?.trim().toLowerCase()??"";if(t==="audio/ogg"||t==="audio/opus")return"ogg-opus";if(t==="audio/flac"||t==="audio/x-flac")return"flac";return}var on=8192;async function*_o(e){for(let t=0;t<e.byteLength;t+=on)yield{AudioEvent:{AudioChunk:e.subarray(t,t+on)}}}function $o(e){let[t,n]=e==="media.transcription"?["voice notes","transcribe:StartStreamTranscription"]:e==="media.speech"?["spoken replies","polly:SynthesizeSpeech"]:["image generation","bedrock:InvokeModel on the image model"];return`This agent's AWS credentials do not allow ${t}. Whoever runs the agent grants ${n} to its AWS role.`}function De(e,t){if(e instanceof ie){let i=e.code!==void 0&&/^[a-z][a-z0-9_]{1,63}$/.test(e.code)?e.code:void 0;return new qA({code:i??"media_credentials_unavailable",message:`The AWS credentials endpoint ${e.status>=500?"could not issue":"refused"} credentials (status ${e.status}${i===void 0?"":`, ${i}`})${e.detail===void 0?"":`: ${e.detail.replace(/\.$/,"")}`}.`,hint:e.status>=500?"The service vending credentials failed rather than declined; it is usually temporary.":"The container-credentials endpoint declined. Its own words are above; nothing here can override it.",field:t})}let n=e instanceof Error?e.name:"",r=e instanceof Error?e.message:String(e);return new qA({code:"media_provider_refused",message:`AWS refused the request (${n||"error"}): ${r}`,hint:n==="AccessDeniedException"||n==="UnrecognizedClientException"?$o(t):n==="ValidationException"?"Nova Canvas takes a prompt of at most 1,024 characters and a size whose sides are multiples of 16 between 320 and 4096.":n==="TextLengthExceededException"?"Lower media.speech.maxCharacters; each voice note is one Polly request.":"AWS's own words are above.",field:t})}function Fe(e=bo){return{optionsSchema:vo,create(t){if(t.options===void 0)throw new B({code:"media_aws_region_missing",message:`${t.field}.options.region is required for the aws provider.`,hint:"Name the region, e.g. options: { region: eu-west-2 }. Nova Canvas is in us-east-1, eu-west-1 and ap-northeast-1.",field:`${t.field}.options`});let n=t.options,r,i,s;return{async transcribe(a,d){let c=ko(a.mimeType),l=a.bytes;if(c===void 0)try{l=await e.decode(a.bytes,d)}catch(u){let h=u.code==="ENOENT";throw new qA({code:"media_audio_unsupported",message:h?`Amazon Transcribe streaming cannot read ${a.mimeType}, and ffmpeg, which would convert it, is not installed.`:`${a.mimeType} could not be converted for Amazon Transcribe: ${u instanceof Error?u.message:String(u)}`,hint:h?"Install ffmpeg on the PATH (the container image carries it), or use the openai provider in media.transcription.":"The file is probably not audio, or is damaged. Ogg/Opus and FLAC are sent as they are.",field:`${t.field}.provider`})}r??=e.transcribe(n);try{let h=await(await r)({LanguageCode:n.languageCode??"en-US",MediaEncoding:c??"pcm",MediaSampleRateHertz:c===void 0?an:n.sampleRate??48000,AudioStream:_o(l)},d),f=[],g;for await(let p of h)for(let m of p.TranscriptEvent?.Transcript?.Results??[]){if(m.IsPartial===!0)continue;let w=m.Alternatives?.[0]?.Transcript;if(w!==void 0&&w!=="")f.push(w);if(m.EndTime!==void 0)g=m.EndTime}return{text:f.join(" "),...g===void 0?{}:{durationS:g}}}catch(u){if(u instanceof qA)throw u;throw De(u,t.field)}},async synthesize(a,d){s??=e.speak(n);try{let l=await(await s)({text:a.text,voiceId:n.voiceId??"Joanna",engine:n.engine??"neural",...n.languageCode===void 0?{}:{languageCode:n.languageCode}},d);return{bytes:l.bytes,mimeType:"audio/ogg; codecs=opus",...l.characters===void 0?{}:{characters:l.characters}}}catch(c){throw De(c,t.field)}},async generateImage(a,d){let[c,l]=a.size.split("x").map(Number);i??=e.invoke(n);let u;try{u=await(await i)({modelId:t.config.model??"amazon.nova-canvas-v1:0",body:JSON.stringify({taskType:"TEXT_IMAGE",textToImageParams:{text:a.prompt},imageGenerationConfig:{numberOfImages:1,width:c,height:l}})},d)}catch(g){throw De(g,t.field)}let h=JSON.parse(u),f=h.images?.[0];if(f===void 0)throw new qA({code:"media_provider_empty",message:`Nova Canvas returned no image${h.error===void 0?"":`: ${h.error}`}.`,hint:"A prompt its content filter refused comes back this way. Rephrasing it is usually what works.",field:t.field});return{bytes:Buffer.from(f,"base64"),mimeType:"image/png"}}}}}}var So="0.1.0",dn={name:"media-aws",version:So,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["transcribestreaming.*.amazonaws.com","bedrock-runtime.*.amazonaws.com","polly.*.amazonaws.com"]}],setup(e){e.defineMediaProvider("aws",Fe())}};import{mkdirSync as To,readFileSync as Eo,renameSync as Ao,writeFileSync as Io}from"node:fs";import{dirname as Co,isAbsolute as Ro,join as cn,resolve as xo}from"node:path";import{mkdirSync as ra,readFileSync as Tn,renameSync as ia,writeFileSync as sa}from"node:fs";import{dirname as oa,isAbsolute as aa,join as wn,resolve as da}from"node:path";var ae=1,ln="tools.cache.json";function le(e){return Ro(e)?cn(e,re.stateDir,ln):cn(xo(e),re.stateDir,ln)}function Mo(e){return typeof e==="object"&&e!==null&&typeof e.slug==="string"}function un(e){let t={version:ae,provider:"composio",fetchedAt:"",baseUrl:"",tools:{}},n;try{n=Eo(le(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!==ae)return t;let s={};for(let[o,a]of Object.entries(i.tools??{}))if(Mo(a))s[o]=a;return{version:ae,provider:"composio",fetchedAt:typeof i.fetchedAt==="string"?i.fetchedAt:"",baseUrl:typeof i.baseUrl==="string"?i.baseUrl:"",tools:s}}catch{return t}}function Oo(e,t,n,r){let i=le(e);To(Co(i),{recursive:!0});let s={version:ae,provider:"composio",fetchedAt:r().toISOString(),baseUrl:n,tools:t},o=`${i}.${process.pid}.tmp`;return Io(o,`${JSON.stringify(s,null,2)}
|
|
11
|
-
`,"utf8"),Ao(o,i),i}function hn(e){return new B({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 No(e,t,n){return new B({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 Po(e,t){return new B({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 \`${re.slug} tools <manifest> --warm\` once to populate it, then start again.`,field:"tools.pinned"})}function D(e,t){return new S({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 Lo(e,t,n){return new S({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 Uo(e,t){return new S({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 fn(e){return new S({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 pn(e){return new S({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 jo="https://backend.composio.dev/api/v3";function mn(e){return/\/v3$/.test(e)?e.replace(/\/v3$/,"/v3.1"):e}var Do=100;function F(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}async function z(e){let t;try{t=await e.json()}catch{return e.statusText===""?"no detail in the response body":e.statusText}let n=F(F(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 vn{#e;#n;#t;constructor(e){this.#e=e.apiKey,this.#n=io(e.baseUrl??jo),this.#t=e.fetch??((t,n)=>globalThis.fetch(t,n))}#r(e,t){return this.#t(`${this.#n}${e}`,{method:"GET",headers:{"x-api-key":this.#e,accept:"application/json"},...t===void 0?{}:{signal:t}})}async#o(e,t){let n=await this.#r(e,t);if(!n.ok)throw D(n.status,await z(n));return n.json()}async tool(e,t){let n=await this.#r(`/tools/${encodeURIComponent(e)}`,t);if(n.status===404)return;if(!n.ok)throw D(n.status,await z(n));let r=F(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(Do)});if(n!==void 0)i.set("cursor",n);let s=await this.#o(`/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.#i(`${this.#n}/tools/execute/${encodeURIComponent(e)}`,{user_id:n,arguments:t},r);if(!i.ok)throw D(i.status,await z(i));let s=F(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}}}#i(e,t,n){return this.#t(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.#i(`${mn(this.#n)}/tool_router/session`,{user_id:e},t);if(!n.ok)throw D(n.status,await z(n));let r=F(await n.json())??{},i=r.session_id;if(typeof i!=="string"||i==="")throw D(n.status,"no session_id in the response body");return r}async executeMeta(e,t,n,r){let i=await this.#i(`${mn(this.#n)}/tool_router/session/${encodeURIComponent(e)}/execute_meta`,{slug:t,arguments:n},r);if(i.status===404)return{notFound:!0};if(!i.ok)throw D(i.status,await z(i));let s=F(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}}}}function Fo(e){return no(e.input_parameters,{unsupported:(t,n)=>No(e.slug,t,n),rootPath:"input_parameters"})}function We(e){let t=new Set(e.tags??[]);if(t.has("destructiveHint"))return!0;return!t.has("readOnlyHint")}function kn(e){let t=new Set(e.tags??[]);return!t.has("readOnlyHint")&&!t.has("destructiveHint")}function Bo(e){let t=e.replace(/\s+/g," ").trim(),n=t.search(/\.\s|\.$/);return n===-1?t:t.slice(0,n+1)}function _n(e){let t=(e.description??e.human_description??"").trim(),n=t===""?`The ${e.slug} tool.`:Bo(t),r=e.toolkit?.slug;return{slug:e.slug,provider:"composio",summary:n,whenToUse:t===""?`the task needs ${e.slug}`:t,mutating:We(e),tags:[...r===void 0?[]:[r],...We(e)?["write"]:["read"]],parameters:Fo(e)}}var Wo=8,gn=100,ue="composio_search",fe="composio_connect",ze="composio_workbench",Ko=[ue,fe,ze];function L(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Ke(e){return Array.isArray(e)?e:[]}function P(e){return typeof e==="string"&&e!==""?e:void 0}function Ho(e){let t=e.replace(/\s+/g," ").trim();return t.length<=gn?t:`${t.slice(0,gn-1)}…`}var $n={slug:ue,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 Go(e){let t=[];for(let n of Ke(e.results)){let r=L(n);if(r===void 0)continue;for(let i of[r.primary_tool_slugs,r.related_tool_slugs])for(let s of Ke(i))if(typeof s==="string"&&!t.includes(s))t.push(s)}return t.slice(0,Wo)}function zo(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??"",o;try{_n(i)}catch(a){if(!R(a))throw a;o=a.message}n.push({...o===void 0?{}:{unavailable:o},slug:r,summary:s===""?"no description supplied":Ho(s),toolkit:i.toolkit?.slug??"",mutating:We(i),assumed:kn(i)})}return n}function Jo(e){let t=[];for(let n of Ke(e.toolkit_connection_statuses)){let r=L(n),i=P(r?.toolkit);if(i===void 0)continue;t.push({toolkit:i,connected:r?.has_active_connection===!0})}return t}function qo(e,t,n){let r=[`Tools that can "${e}":`,""];for(let o of t){if(o.unavailable!==void 0){r.push(` n/a ${o.slug}`),r.push(` unavailable — do not pin it: ${o.unavailable}`);continue}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.`);if(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. "+"config_set says which become usable in this conversation; the rest work from the person's next message, with no restart. Pin only what the task needs."),t.some((o)=>o.unavailable!==void 0))r.push("Those marked n/a cannot be loaded by this runtime as Composio describes them today; a pinned one is left out with a warning. Choose another tool, or tell the person it is unavailable.");return r.join(`
|
|
12
|
-
`)}function Vo(e){return{spec:$n,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=L(i.data)??{},o=Go(s);if(o.length===0)throw pn(r);let a=await e.fetchSchemas(o,n.signal),d=zo(o,a);if(d.length===0)throw pn(r);return qo(r,d,Jo(s))}}}var Sn={slug:fe,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 He(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(L(e)??{})){let r=He(n,t+1);if(r!==void 0)return r}return}function Yo(e,t){let n=L(L(t.results)?.[e]),r=P(n?.status)?.toLowerCase(),i=P(n?.redirect_url)??He(t.results)??He(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})`}. ${P(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(`
|
|
13
|
-
`)}function Xo(e){return{spec:Sn,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 Yo(r,L(i.data)??{})}}}var Zo={slug:ze,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"]}},Qo="code_to_execute";function ea(e){let t=L(e);if(t===void 0)return typeof e==="string"?e:JSON.stringify(e,null,2);let n=[],r=P(t.stdout),i=P(t.stderr),s=P(t.error),o=P(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:
|
|
14
|
-
${i.trimEnd()}`);if(s!==void 0)n.push(`error:
|
|
15
|
-
${s.trimEnd()}`);return n.length===0?"The code ran and printed nothing.":n.join(`
|
|
16
|
-
`)}function ta(e){return{spec:Zo,handler:async(t,n)=>{let r=await e.call("COMPOSIO_REMOTE_WORKBENCH",{[Qo]:String(t.code??"")},n.signal);if(!r.ok)return`The workbench failed: ${r.error??"no detail supplied"}`;return ea(r.data)}}}function na(e){return{[ue]:Vo(e),[fe]:Xo(e),[ze]:ta(e)}}var yn="composio.session.json";function En(e){return aa(e)?wn(e,re.stateDir,yn):wn(da(e),re.stateDir,yn)}function ca(e,t){let n;try{n=Tn(En(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 la(e,t,n){let r=En(e);ra(oa(r),{recursive:!0});let i={};try{let d=JSON.parse(Tn(r,"utf8"))?.sessions;if(typeof d==="object"&&d!==null){for(let[c,l]of Object.entries(d))if(typeof l==="string")i[c]=l}}catch{i={}}let s={sessions:{...i,[t]:n}},o=`${r}.${process.pid}.tmp`;return sa(o,`${JSON.stringify(s,null,2)}
|
|
17
|
-
`,"utf8"),ia(o,r),r}var ua="COMPOSIO_API_KEY";class An{id="composio";#e;#n;#t;#r;#o;#i;#a;#s;#d;#c=[];#l=[];#u;constructor(e){this.#e=e.dir,this.#n=e.userId??"default",this.#t=e.now??(()=>new Date),this.#i=e.apiKeyEnv??ua,this.#a=e.personal??!0;let t=e.env[this.#i];this.#r=e.baseUrl??"https://backend.composio.dev/api/v3",this.#o=t===void 0||t===""?void 0:new vn({apiKey:t,baseUrl:this.#r,...e.fetch===void 0?{}:{fetch:e.fetch}});let n=un(this.#e);this.#s=n.tools,this.#d=n.fetchedAt}async resolve(e){let t=[],n=[],r=[],i=na(this.#p());for(let s of e){let o=i[s];if(o!==void 0){t.push(o);continue}let a=this.#s[s];if(a===void 0)continue;let d;try{d=_n(a)}catch(c){if(!R(c))throw c;r.push({slug:s,detail:c.toDetail()});continue}if(kn(a))n.push(s);t.push(this.#f(d))}if(this.#c=n,this.#l=r,!this.#a)return t;return t.map((s)=>({...s,spec:{...s.spec,personal:!0}}))}refused(){return this.#l}async list(){return[...Ko,...Object.keys(this.#s)]}async available(){return[{slug:ue,summary:$n.summary},{slug:fe,summary:Sn.summary}]}uncached(e){return e.filter((t)=>this.#s[t]===void 0)}explainUnresolved(e){if(Object.keys(this.#s).length>0||e.length===0)return;return Po(e,le(this.#e))}describe(){return{cached:Object.keys(this.#s).length,fetchedAt:this.#d,cachePath:le(this.#e),assumedMutating:this.#c}}async refresh(e,t){let n=this.#o;if(n===void 0)throw hn(this.#i);let r={},i=[],s=[];for(let a of e){let d=await n.tool(a,t);if(d===void 0){i.push(a);continue}r[a]=d;let c=this.#s[a];if(c===void 0||JSON.stringify(c)!==JSON.stringify(d))s.push(a)}this.#s={...this.#s,...r};let o=Oo(this.#e,this.#s,this.#r,this.#t);return this.#d=un(this.#e).fetchedAt,{fetched:Object.keys(r).length,missing:i,changed:s,cachePath:o}}async#h(e,t=!1){let n=this.#o;if(n===void 0)throw fn(this.#i);if(!t){let i=this.#u??ca(this.#e,this.#n);if(i!==void 0)return this.#u=i,i}let r=await n.createSession(this.#n,e);return this.#u=r.session_id,la(this.#e,this.#n,r.session_id),r.session_id}#p(){return{call:async(e,t,n)=>{let r=this.#o;if(r===void 0)throw fn(this.#i);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.#s[r];if(i!==void 0)n[r]=i}return n}}}#f(e){return{spec:e,handler:async(t,n)=>{let r=this.#o;if(r===void 0)throw hn(this.#i);let i=await r.execute(e.slug,t,this.#n,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 Uo(e.slug,o)}throw Lo(e.slug,200,s)}return typeof i.data==="string"?i.data:JSON.stringify(i.data,null,2)}}}}var bn=["apiKeyEnv","userId","baseUrl","personal"];function Be(e,t){let n=e[t];if(n===void 0)return;if(typeof n!=="string"||n==="")throw new B({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 Je(e){let t=Object.keys(e.config).filter((o)=>!bn.includes(o));if(t.length>0)throw new B({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 ${bn.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=Be(e.config,"apiKeyEnv"),r=Be(e.config,"userId"),i=Be(e.config,"baseUrl"),s=e.config.personal;if(s!==void 0&&typeof s!=="boolean")throw new B({code:"composio_config_invalid",message:"tools.providers.composio.personal must be true or false.",hint:"Leave it out to keep the default, true: every tool acts as the agent's owner. Write false only for a Composio entity a whole team shares on purpose.",field:"tools.providers.composio.personal"});return new An({dir:e.dir,env:e.env,...n===void 0?{}:{apiKeyEnv:n},...r===void 0?{}:{userId:r},...i===void 0?{}:{baseUrl:i},...s===void 0?{}:{personal:s}})}var ha="0.1.0",In={name:"composio",version:ha,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",Je)}};import{mkdirSync as fa,readFileSync as pa,renameSync as ma,writeFileSync as ga}from"node:fs";import{dirname as wa,join as ya,resolve as ba}from"node:path";var Pn=1;function Ve(e){return ya(ba(e),re.stateDir,"mcp.cache.json")}function va(e){try{let t=JSON.parse(pa(Ve(e),"utf8"));if(t.version!==Pn||typeof t.servers!=="object")return{};let n={};for(let[r,i]of Object.entries(t.servers??{}))if(typeof i?.url==="string"&&Array.isArray(i.tools))n[r]=i;return n}catch{return{}}}function ka(e,t){let n=Ve(e);fa(wa(n),{recursive:!0});let r=`${n}.partial`;return ga(r,`${JSON.stringify({version:Pn,servers:t},null,2)}
|
|
18
|
-
`),ma(r,n),n}var Ln="tools.providers.mcp";function A(e,t,n=Ln){return new B({code:"mcp_config_invalid",message:e,hint:t,field:n})}function _a(e,t,n){return new B({code:"mcp_cache_miss",message:`${t.length===1?"A pinned MCP tool is":`${t.length} pinned MCP tools are`} not in the cache: ${t.join(", ")}. Nothing is cached yet for ${e.join(", ")}.`,hint:`Boot resolves MCP tools from ${n} and contacts no server, because nothing may touch the network before runtime.ready, and a server that is down must not stop an agent booting. Run \`${re.slug} tools <manifest> --warm\` once with the server running to fill it, then start again.`,field:"tools.pinned"})}function $a(e,t,n){return new S({code:"mcp_header_env_missing",message:`The MCP server "${e}" needs the ${t} header from ${n}, which is not set.`,hint:`Set ${n} in the environment or in the .env beside the manifest. The manifest names the variable (${Ln}.servers.${e}.headersEnv), never the value.`})}function Un(e,t,n){return new S({code:"mcp_request_failed",message:`The MCP server "${e}" at ${t} did not answer: ${n}`,hint:"Check the server is running and reachable from this host (a loopback URL means the same machine or pod). If it needs a token, headersEnv names the variable that holds it. An agent keeps serving the tools it cached; only calls fail while the server is down."})}function Sa(e,t,n){return new S({code:"mcp_tool_failed",message:`The MCP tool "${t}" on "${e}" reported an error: ${n}`,hint:"The server's own words above say what went wrong. If they say the failure is temporary, retry up to twice. Otherwise a tool outside the server's allowlist, a missing upstream credential or an invalid argument are the usual causes, and retrying the same call will not fix those."})}var Rn="2025-06-18";class jn{#e;#n;#t;#r;#o=1;constructor(e){this.#e=e,this.#n=e.fetch??((t,n)=>fetch(t,n))}async listTools(e){let t=[],n;for(let r=0;r<100;r+=1){let i=await this.#i("tools/list",n===void 0?{}:{cursor:n},{},e);for(let s of i.tools??[])if(typeof s?.name==="string")t.push(s);if(n=i.nextCursor,n===void 0||n==="")return t}return t}async callTool(e,t,n,r){return await this.#i("tools/call",{name:e,arguments:t},n,r)}async#i(e,t,n,r){await this.#a(r);let i=await this.#d(e,t,n,r);if(i.status!==404||this.#t===void 0)return this.#l(i,e);return this.#t=void 0,await this.#a(r),this.#l(await this.#d(e,t,n,r),e)}#a(e){if(this.#t!==void 0)return Promise.resolve();return this.#r??=this.#s(e).finally(()=>{this.#r=void 0}),this.#r}async#s(e){let t=await this.#d("initialize",{protocolVersion:Rn,capabilities:{},clientInfo:{name:re.slug,version:Ge}},{},e);await this.#l(t,"initialize"),this.#t=t.headers.get("mcp-session-id")??"",await(await this.#c({jsonrpc:"2.0",method:"notifications/initialized"},{},e)).body?.cancel()}#d(e,t,n,r){let i=this.#o;return this.#o+=1,this.#c({jsonrpc:"2.0",id:i,method:e,params:t},n,r)}async#c(e,t,n){let r=AbortSignal.timeout(this.#e.timeoutMs);try{return await this.#n(this.#e.url,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream","mcp-protocol-version":Rn,...this.#t===void 0||this.#t===""?{}:{"mcp-session-id":this.#t},...this.#e.headers(),...t},body:JSON.stringify(e),signal:n===void 0?r:AbortSignal.any([n,r])})}catch(i){throw this.#u(r.aborted?`no response within ${this.#e.timeoutMs} ms`:i instanceof Error?i.message:String(i))}}async#l(e,t){let n=await e.text();if(!e.ok)throw this.#u(`${t} answered ${e.status}: ${n.slice(0,300)}`);let i=(e.headers.get("content-type")??"").includes("text/event-stream")?Ta(n):[n];for(let s of i){let o;try{o=JSON.parse(s)}catch{continue}if(o.error!==void 0)throw this.#u(`${t} failed (${o.error.code??"?"}): ${o.error.message??"no message"}`);if(o.result!==void 0)return o.result}throw this.#u(`${t} returned no JSON-RPC result`)}#u(e){return Un(this.#e.server,this.#e.url,e)}}function Ta(e){let t=[];for(let n of e.split(/\r?\n\r?\n/)){let r=n.split(/\r?\n/).filter((i)=>i.startsWith("data:")).map((i)=>i.slice(5).replace(/^ /,""));if(r.length>0)t.push(r.join(`
|
|
19
|
-
`))}return t}var pe="__";function J(e,t){return`${e}${pe}${t.replace(/[^A-Za-z0-9_-]/g,"_")}`}function Ea(e){let t=e.annotations;return t?.readOnlyHint!==!0||t.destructiveHint===!0}function Aa(e){let t=e.replace(/\s+/g," ").trim(),n=t.search(/\.\s|\.$/);return n===-1?t:t.slice(0,n+1)}function Dn(e,t){let n=(t.description??t.title??"").trim();return n===""?`The ${t.name} tool on ${e}.`:Aa(n)}function Ia(e,t,n){let r=J(e,t.name),i=(t.description??t.title??"").trim(),s=Ea(t);return{slug:r,provider:"mcp",summary:Dn(e,t),whenToUse:i===""?`the task needs ${t.name} from ${e}`:i,mutating:s,tags:[e,s?"write":"read"],...n===void 0?{}:{policyArg:n},parameters:no(t.inputSchema,{untyped:"object",rootPath:"inputSchema",unsupported:(o,a)=>A(`The MCP tool "${r}" declares "${a}" at ${o}, which this runtime's schema subset cannot express.`,"Refused rather than dropped: that keyword decides which arguments are valid, so ignoring it would hand the model a schema the server disagrees with. Unpin this tool, or ask the server for a flatter one.","tools.pinned")})}}var xn=["url","headersEnv","participantHeader","turnHeader","policyArgs","timeoutMs","personal"],Mn=30000,Ca=40;function qe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function On(e,t,n){if(e===void 0)return{};let r=qe(e),i=r===void 0?void 0:Object.entries(r),s=i?.every(([,o])=>typeof o==="string"&&(n===void 0||n.test(o)));if(i===void 0||s!==!0)throw A(`${t} must map names to ${n===void 0?"strings":"environment variable names"}.`,n===void 0?"Write it as a map, e.g. { invoke_tool: toolName }.":"Write it as { Authorization: TRACKER_MCP_TOKEN }: the header name, then the variable holding its value. A value never goes in the manifest.",t);return Object.fromEntries(i)}function Ra(e){let t=Object.keys(e).filter((r)=>r!=="servers");if(t.length>0)throw A(`tools.providers.mcp has keys the MCP provider does not read: ${t.join(", ")}.`,"Everything goes under servers.<name>: url, headersEnv, participantHeader, turnHeader, policyArgs, timeoutMs. Refused rather than ignored, because a setting that looks applied and is not is worse than a rejected manifest.");let n=qe(e.servers);if(n===void 0||Object.keys(n).length===0)throw A("tools.providers.mcp names no servers.","Add servers.<name>.url, e.g. servers: { tracker: { url: http://127.0.0.1:3000/mcp } }.","tools.providers.mcp.servers");return Object.entries(n).map(([r,i])=>{let s=`tools.providers.mcp.servers.${r}`;if(!/^[a-z][a-z0-9-]{0,23}$/.test(r))throw A(`The MCP server name "${r}" is not usable in a tool slug.`,"Use lowercase letters, digits and hyphens, starting with a letter, at most 24 characters. It prefixes every tool: tracker → tracker__search_tools.",s);let o=qe(i)??{},a=Object.keys(o).filter((h)=>!xn.includes(h));if(a.length>0)throw A(`${s} has keys the MCP provider does not read: ${a.join(", ")}.`,`Accepted keys are ${xn.join(", ")}.`,s);let d;try{d=new URL(String(o.url))}catch{throw A(`${s}.url is not a URL.`,"Give the server's Streamable HTTP endpoint, e.g. http://127.0.0.1:3000/mcp.",`${s}.url`)}if(d.protocol!=="http:"&&d.protocol!=="https:")throw A(`${s}.url is ${d.protocol} — only HTTP servers are supported.`,"Streamable HTTP is the one transport this provider speaks. A stdio server needs an HTTP front (most servers have an MCP_TRANSPORT=http mode).",`${s}.url`);if(d.username!==""||d.password!=="")throw A(`${s}.url carries a credential.`,"A manifest never holds a secret. Put it in an env var and name it in headersEnv, e.g. { Authorization: TRACKER_MCP_TOKEN }.",`${s}.url`);let c=o.timeoutMs===void 0?Mn:o.timeoutMs;if(typeof c!=="number"||!Number.isInteger(c)||c<=0)throw A(`${s}.timeoutMs must be a positive whole number of milliseconds.`,`Omit it for ${Mn} ms.`,`${s}.timeoutMs`);let l=o.participantHeader;if(l!==void 0&&typeof l!=="string")throw A(`${s}.participantHeader must be a header name.`,"e.g. X-Acting-Participant. Each call then carries the id of the person the turn acts for, and none on a schedule or peer-agent turn.",`${s}.participantHeader`);let u=o.turnHeader;if(u!==void 0&&(typeof u!=="string"||!/^[A-Za-z0-9-]+$/.test(u)))throw A(`${s}.turnHeader must be a header name.`,"e.g. X-Dispach-Turn. Each call then carries the turn id there, and the call id in <name>-Call.",`${s}.turnHeader`);if(o.personal!==void 0&&typeof o.personal!=="boolean")throw A(`${s}.personal must be true or false.`,"true when the server acts as the agent's owner (their mailbox, their account), so only the owner's turns get its tools.",`${s}.personal`);return{name:r,url:d.toString(),...o.personal===!0?{personal:!0}:{},...u===void 0?{}:{turnHeader:u},headersEnv:On(o.headersEnv,`${s}.headersEnv`,/^[A-Za-z_][A-Za-z0-9_]*$/),...l===void 0?{}:{participantHeader:l},policyArgs:On(o.policyArgs,`${s}.policyArgs`),timeoutMs:c}})}function Nn(e){let t=(e.content??[]).map((n)=>n.type==="text"&&typeof n.text==="string"?n.text:`[${n.type} content omitted]`);if(t.length>0)return t.join(`
|
|
20
|
-
`);return e.structuredContent===void 0?"(no content)":JSON.stringify(e.structuredContent,null,2)}class Fn{id="mcp";#e;#n;#t;#r;#o=new Map;#i;constructor(e){this.#e=e.dir,this.#n=e.env,this.#t=new Map(e.servers.map((t)=>[t.name,t])),this.#r=e.fetch,this.#i=va(e.dir)}#a(e){let t=this.#i[e.name];return t===void 0||t.url!==e.url?void 0:t.tools}async resolve(e){let t=[],n=[];for(let r of this.#t.values())for(let i of this.#a(r)??[]){let s=J(r.name,i.name);if(!e.includes(s))continue;try{t.push(this.#c(r,i))}catch(o){if(!R(o))throw o;n.push({slug:s,detail:o.toDetail()})}}return this.#s=n,t}refused(){return this.#s}#s=[];async list(){return[...this.#t.values()].flatMap((e)=>(this.#a(e)??[]).map((t)=>J(e.name,t.name)))}async available(){let e=[];for(let t of this.#t.values())for(let n of this.#a(t)??[]){if(e.length>=Ca)return e;e.push({slug:J(t.name,n.name),summary:Dn(t.name,n)})}return e}explainUnresolved(e){let t=new Set,n=[];for(let r of e){let i=this.#t.get(r.split(pe)[0]??"");if(i===void 0||!r.includes(pe))continue;if(this.#a(i)!==void 0)continue;t.add(i.name),n.push(r)}return n.length===0?void 0:_a([...t],n,Ve(this.#e))}async refresh(e,t){let n={...this.#i},r=[],i=[],s=0;for(let d of this.#t.values())try{let c=await this.#d(d).listTools(t),l=new Map((this.#a(d)??[]).map((u)=>[u.name,JSON.stringify(u)]));for(let u of c){let h=J(d.name,u.name);if(!e.includes(h))continue;if(s+=1,l.get(u.name)!==JSON.stringify(u))i.push(h)}n[d.name]={url:d.url,fetchedAt:new Date().toISOString(),tools:c}}catch(c){r.push({server:d,detail:c instanceof Error?c.message:String(c)})}if(this.#i=n,ka(this.#e,n),r.length>0)throw Un(r.map((d)=>d.server.name).join(", "),r.map((d)=>d.server.url).join(", "),r.map((d)=>d.detail).join("; "));let o=new Set(await this.list()),a=e.filter((d)=>this.#t.has(d.split(pe)[0]??"")&&!o.has(d));return{fetched:s,missing:a,changed:i}}#d(e){let t=this.#o.get(e.name);if(t===void 0)t=new jn({server:e.name,url:e.url,timeoutMs:e.timeoutMs,...this.#r===void 0?{}:{fetch:this.#r},headers:()=>{let n={};for(let[r,i]of Object.entries(e.headersEnv)){let s=this.#n[i];if(s===void 0||s==="")throw $a(e.name,r,i);n[r]=s}return n}}),this.#o.set(e.name,t);return t}#c(e,t){return{spec:{...Ia(e.name,t,e.policyArgs[t.name]),...e.personal===!0?{personal:!0}:{}},handler:async(n,r)=>{let i=r.actingParticipant,s={...e.participantHeader===void 0||i==null?{}:{[e.participantHeader]:i.id},...e.turnHeader===void 0?{}:{[e.turnHeader]:r.turnId,...r.callId===void 0?{}:{[`${e.turnHeader}-Call`]:r.callId}}},o=await this.#d(e).callTool(t.name,n,s,r.signal);if(o.isError===!0)throw Sa(e.name,t.name,Nn(o));return Nn(o)}}}}function Ye(e,t){return new Fn({dir:e.dir,env:e.env,servers:Ra(e.config),...t===void 0?{}:{fetch:t}})}var xa="0.1.0",Bn={name:"mcp",version:xa,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["<tools.providers.mcp.servers.*.url>"]},{kind:"fs",paths:["<state>/mcp.cache.json"],mode:"write"}],setup(e){e.defineToolProvider("mcp",(t)=>Ye(t))}};import{readFile as Ma}from"node:fs/promises";import{join as Oa}from"node:path";import{tmpdir as Ya}from"node:os";import{join as Xa}from"node:path";import{mkdir as hd,realpath as fd,rm as Jn,stat as pd}from"node:fs/promises";import{isAbsolute as md,resolve as tt}from"node:path";import{open as hr}from"node:fs/promises";import{existsSync as kd,realpathSync as _d}from"node:fs";import{homedir as Vn}from"node:os";import{isAbsolute as pr,relative as $d,resolve as q,sep as Sd}from"node:path";import{spawn as Rd}from"node:child_process";import{open as xd,readFile as Md}from"node:fs/promises";import{mkdir as Qd,readFile as vr,realpath as ec,stat as kr,writeFile as _r}from"node:fs/promises";import{dirname as tc,isAbsolute as nc,resolve as Qn}from"node:path";import{isAbsolute as rc,relative as ic,resolve as sc,sep as $r}from"node:path";import{readFile as gc}from"node:fs/promises";import{readdir as wc}from"node:fs/promises";import{join as yc,relative as bc,sep as nr}from"node:path";import{statSync as Ic}from"node:fs";import{mkdir as Cc,rm as ar}from"node:fs/promises";import{delimiter as Rc,join as et}from"node:path";function Na(){return new S({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 Pa(e,t){return new B({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 La(e,t){return new S({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 Wn(e,t){return new S({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 Ua(){return new S({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 dr(e){return new S({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 ja(e,t,n){return new S({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 Da(e,t){return new S({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 Fa(e,t){return new S({code:"file_secret",message:`Refused to read ${e}: ${t}.`,hint:"Credentials are never read into a conversation. If a task needs a key, it is configured by name in the manifest and the tool that needs it reads it; ask the person rather than looking for the value."})}function Ba(e,t){return new S({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 Wa(e,t){let n=t.length>120?`${t.slice(0,120)}…`:t;return new S({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 Ka(e,t){return new S({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 Ha(e,t){return new S({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 Ga(e,t){return new S({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 za(e,t){return new S({code:"file_read_outside_root",message:`${e} is outside the directories this agent may read.`,hint:`Readable: ${t.join(", ")}. Reads are confined on this agent (tools.providers.system.confineReads), so other agents' files and the rest of the machine are out of reach. A person can add a directory with writeRoots; nothing said in a conversation can.`,field:"path"})}function cr(e,t){return new S({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 Ja(e,t){return new S({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 qa(e,t){return new S({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 Kn(e,t,n){return new S({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 Hn(e,t){return new S({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 Va(e){return new S({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 O="system";function st(){return Xa(Ya(),`${re.slug}-${O}`)}var Za=rt.filter((e)=>e.agentListed),Gn="(hidden by the operator)",Qa=new Set(["id","api","baseurl","options","apikeyenv"]),ed=new Set(["model","provider","baseurl","options","apikeyenv"]);function Xe(e){return e.getIn(["context","modelIdentity"])==="hidden"}function ge(e,t){let n=e.map((r)=>r.toLowerCase());if(n[0]==="model"&&n.slice(2).some((r)=>Qa.has(r)))return Gn;if(n[0]==="media"&&n[2]!==void 0&&ed.has(n[2]))return Gn;if(Array.isArray(t))return t.map((r,i)=>ge([...e,String(i)],r));if(typeof t==="object"&&t!==null)return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,ge([...e,r],i)]));return t}function zn(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")&&I(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";let o="what your commands can see of the environment is not yours to widen. The scrub keeps the runtime's credentials out of anything you run; a person lists a variable your commands need",a="where a provider sends its requests, and so its credentials, is not yours to decide. A person sets a provider's baseUrl";if(n.startsWith("tools.providers")&&n.split(".").includes("baseurl"))return a;if(n.startsWith("tools.providers")&&I(t,"baseurl"))return a;let d="which skills may run code is not yours to decide. A person lists them in skills.trusted";if(n==="skills.trusted"||n==="skills"&&I(t,"trusted"))return d;let c="which files you may read is not yours to widen. A person sets tools.providers.system.confineReads";if(n.startsWith("tools.providers")&&n.split(".").includes("confinereads"))return c;if(n.startsWith("tools.providers")&&I(t,"confinereads"))return c;let l="who may use your owner's connected accounts is not yours to widen. A person sets a provider's personal flag";if(n.startsWith("tools.providers")&&n.split(".").includes("personal"))return l;if(n.startsWith("tools.providers")&&I(t,"personal"))return l;if(n.startsWith("tools.providers")&&n.split(".").includes("env"))return o;if(n.startsWith("tools.providers")&&I(t,"env"))return o;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"&&I(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"&&(I(t,"host")||I(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 I(e,t){if(Array.isArray(e))return e.some((n)=>I(n,t));if(typeof e!=="object"||e===null)return!1;return Object.entries(e).some(([n,r])=>n.toLowerCase()===t||I(r,t))}function lr(e){return e.file??Oa(e.agentDir,"agent.yaml")}var td={slug:"config_read",provider:O,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."}}}},nd={slug:"config_set",provider:O,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 rd(e){try{return so(e)}catch(t){throw qa(e,t instanceof Error?t.message:String(t))}}function id(e){return async(t)=>{let n=lr(e),r;try{r=await Ma(n,"utf8")}catch(a){throw cr(n,String(a))}let i=typeof t.path==="string"?t.path.trim():"";if(i!==""){let a=W(r),d=a.getIn(i.split("."),!1);if(d===void 0)return`${i} is not set in this configuration. It can be — see config_read with no path for the full list.`;let c=bA(d)||OA(d)?d.toJS(a):d,l=Xe(a)?ge(i.split("."),c):c;return`${i}:
|
|
21
|
-
${Cn(l).trimEnd()}`}let s=W(r),o=Za.map((a)=>{let d=s.getIn(a.path.split("."),!1),c=bA(d)||OA(d)?d.toJS(s):d,l=Xe(s)?ge(a.path.split("."),c):c,u=l===void 0||l===null?"(not set)":Array.isArray(l)?`[${l.map((f)=>typeof f==="object"&&f!==null?JSON.stringify(f):String(f)).join(", ")}]`:Cn(l).trim(),h=a.toAgent===void 0?a.means:`${a.means}. ${a.toAgent}`;return`- ${a.path} = ${u}
|
|
22
|
-
${h}`}).join(`
|
|
23
|
-
`);return[`This agent is ${s.get("name")??s.get("id")}, configured at ${n}.`,"","Settings config_set can change, with their current values:",o,"",...sd(s),"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, the system provider's env, any provider's baseUrl or personal flag, 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.","",...Xe(s)?[]:[`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(`
|
|
24
|
-
`)}}function sd(e){let t=(r)=>{let i=e.getIn(r,!1),s=bA(i)||OA(i)?i.toJS(e):i;if(Array.isArray(s))return s.map(String);return typeof s==="string"&&s!==""?[s]:[]},n=[["context.soul.file",t(["context","soul","file"])],["context.static",t(["context","static"])],["context.files",t(["context","files"])],["context.volatile",t(["context","volatile"])],["context.reminder",t(["context","reminder"])]].filter(([,r])=>r.length>0).map(([r,i])=>`- ${r} = [${i.join(", ")}]`);if(n.length===0)return[];return["Context files (read-only here). These files are loaded into my instructions every turn, under their names, so I never need to read them; volatile ones only in private conversations:",...n,""]}function od(e){return async(t,n)=>{let r=lr(e),i=typeof t.path==="string"?t.path.trim():"",s=typeof t.value==="string"?t.value:String(t.value??""),o=zn(i);if(o!==void 0)throw Hn(i,o);if(!Wr.includes(i))throw Ja(i,Wr);let a=rd(s),d=zn(i,a);if(d!==void 0)throw Hn(i,d);let c;try{c=await ms({file:r,path:i.split("."),value:a,...e.providers===void 0?{}:{providers:e.providers},...e.mediaProviders===void 0?{}:{mediaProviders:e.mediaProviders}})}catch(f){if(R(f)&&f.code==="manifest_edit_unreadable")throw cr(r,String(f.cause??f.message));if(R(f)&&f.code==="manifest_edit_invalid"){let g=f.message.slice(f.message.indexOf(": ")+2);throw Kn(i,s,g)}if(R(f))throw Kn(i,s,`${f.message} ${f.hint??""}`.trim());throw f}let l=c.before!==void 0,u=i==="tools.pinned"&&Array.isArray(a)&&n.pinTools!==void 0?await n.pinTools(a.map(String)):void 0,h=u===void 0?"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.":u.length>0?`The configuration still validates. Usable now, in this conversation: ${u.join(", ")}. Anything else listed here works from the person's next message, once the agent reloads after this turn.`:"The configuration still validates. The new tools work from the person's next message: the agent reloads once this turn ends, with no restart. Tell them it is ready for their next message; do not try the tool in this turn.";return[`Set ${i} in ${r}.`,l?`It was: ${Cn(c.before).trim()}`:"It was not set before.",`It is now: ${Cn(a).trim()}`,"",h,...ad(c.manifest,a)].join(`
|
|
25
|
-
`)}}function ad(e,t){if(!I(t,"tokenenv")&&!I(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 dd(e){return[{spec:td,handler:id(e)},{spec:nd,handler:od(e)}]}var cd=["PATH","HOME","USER","LOGNAME","SHELL","LANG","LANGUAGE","TZ","TERM","TMPDIR"],ld=/^[A-Za-z_][A-Za-z0-9_]*$/;function ud(e){if(e===void 0||e==="inherit")return"inherit";if(e==="scrub")return{scrub:!0,pass:[]};if(Array.isArray(e)&&e.every((t)=>typeof t==="string"&&ld.test(t)))return{scrub:!0,pass:e};throw new B({code:"system_env_invalid",message:`tools.providers.system.env is ${JSON.stringify(e)}, which is none of inherit, scrub or a list of variable names.`,hint:"Write `env: scrub` to give commands only PATH, HOME, the locale and the like, or `env: [GITHUB_TOKEN]` to scrub and pass those names too. Omit it (or `inherit`) to keep handing commands the whole environment.",field:"tools.providers.system.env"})}function ur(e,t){if(t==="inherit")return e;let n=new Set([...cd,...t.pass]);return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)||r.startsWith("LC_")))}var gd=6000,wd=3000,qn=1500,yd=new TextDecoder("utf-8");async function Ze(e,t,n){let r=await hr(e,"r");try{let i=new Uint8Array(n),{bytesRead:s}=await r.read(i,0,n,t);return yd.decode(i.subarray(0,s))}finally{await r.close()}}async function fr(e){let t=await hr(e,"r"),n;try{n=(await t.stat()).size}finally{await t.close()}if(n<=gd)return{head:jA(await Ze(e,0,n)),tail:"",bytes:n,spilled:!1};return{head:jA(await Ze(e,0,wd)),tail:jA(await Ze(e,n-qn,qn)),bytes:n,spilled:!0}}function bd(e){return e.replace(/^(?:\^[A-Z?]\s*)+/,"")}function vd(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Td(e){if(e==="~")return Vn();return e.startsWith("~/")?q(Vn(),e.slice(2)):e}var Ed="workspace";function Ad(e,t=[],n=!1){let r=q(e),i=q(r,Ed);return{primary:kd(i)?i:r,extra:t.map((s)=>pr(s)?q(s):q(r,s)),confineReads:n}}function Yn(e){try{return _d(e)}catch{return e}}function mr(e,t){if(!t.confineReads)return;let n=Yn(e);if(V(t).some((r)=>gr(n,Yn(r))))return;throw za(e,V(t))}function gr(e,t){if(e===t)return!0;let n=$d(t,e);return n!==""&&!n.startsWith(`..${Sd}`)&&n!==".."&&!pr(n)}function V(e){return[e.primary,...e.extra]}function Id(e,t){return V(t).some((n)=>gr(e,n))}function Cd(e,t){let n=e.extra.length===0?"":` Also writable: ${e.extra.join(", ")}.`;if(t==="read")return e.confineReads?` Relative paths are resolved against ${e.primary}. Only ${V(e).join(", ")} can be read; anything elsewhere is refused.`:` 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 ot(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??""}${Cd(t,r)}`}}return{...e,parameters:{...e.parameters,properties:i}}}var U=new Map,Od=8;function Nd(){return[...U.entries()].map(([e,t])=>({pid:e,...t})).sort((e,t)=>t.since-e.since)}function Pd(){let e=[];for(let[t,n]of U)try{process.kill(-t,"SIGTERM"),e.push(`${t} (${n.command})`)}catch{}return U.clear(),e}function Ld(){for(let e of[...U.keys()])try{process.kill(e,0)}catch{U.delete(e)}}var Ud=250,Xn=2000,jd=new Set(["sleep","git","ssh","scp","sudo","su","doas"]);function Dd(e){for(let t of e.split(/\s+/)){if(/^[A-Za-z_]\w*=/.test(t))continue;return t.replace(/^.*\//,"").toLowerCase()}return""}function Fd(e){let t=Qs(e);if(t.length===0)return!1;return t.every((n)=>!jd.has(Dd(n)))}function wr(e){return`'${e.replaceAll("'","'\\''")}'`}function Bd(e,t){return[e,"__code=$?",`{ printf '%s\\n' "$__code"; pwd; } > ${wr(t)} 2>/dev/null`,"exit $__code"].join(`
|
|
26
|
-
`)}function Wd(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 ${wr(e)}`,"/dev/null"],env:{SHELL:"/bin/sh"}};return{file:"script",args:["-q","/dev/null","/bin/sh","-c",e],env:{SHELL:"/bin/sh"}}}function me(e,t){let n=e.pid;if(n===void 0)return;try{process.kill(-n,t)}catch{}}async function Kd(e){try{let[t,n]=(await Md(e,"utf8")).split(`
|
|
27
|
-
`),r=Number.parseInt(t??"",10),i=n?.trim();return{...Number.isNaN(r)?{}:{code:r},...i===void 0||i===""?{}:{cwd:i}}}catch{return{}}}async function yr(e){if(Ld(),U.size>=Od)throw Va(Nd().map((c)=>c.command));let t=Bd(e.command,e.statusPath),{file:n,args:r,env:i}=Wd(t,e.pty),s=await xd(e.outPath,"w"),o;try{o=Rd(n,r,{cwd:e.cwd,env:{...e.env,...i},stdio:["ignore",s.fd,s.fd],detached:!0})}catch(c){throw await s.close(),Wn(e.command,String(c))}let a=await new Promise((c,l)=>{let u=!1,h=!1,f=setTimeout(p,e.background?Ud:e.timeoutMs),g=(w)=>{if(u)return;u=!0,clearTimeout(f),e.signal.removeEventListener("abort",m),c(w)};function p(){if(e.background||Fd(e.command)){if(o.unref(),o.pid!==void 0)U.set(o.pid,{command:e.command,since:Date.now(),outPath:e.outPath});g({ending:"backgrounded",...o.pid===void 0?{}:{pid:o.pid}});return}h=!0,me(o,"SIGTERM"),setTimeout(()=>me(o,"SIGKILL"),Xn).unref?.()}function m(){me(o,"SIGTERM"),setTimeout(()=>me(o,"SIGKILL"),Xn).unref?.()}e.signal.addEventListener("abort",m,{once:!0}),o.on("error",(w)=>{if(u)return;u=!0,clearTimeout(f),e.signal.removeEventListener("abort",m),l(e.pty&&Hd(w)?La(process.platform,String(w)):Wn(e.command,String(w)))}),o.on("exit",(w,v)=>{g({ending:h?"killed":"finished",...w===null?{}:{code:w},...v===null?{}:{killedBy:v},...o.pid===void 0?{}:{pid:o.pid}})})}).finally(()=>s.close()),d=await Kd(e.statusPath);return{...a,...d.code===void 0?{}:{code:d.code},...d.cwd===void 0?{}:{cwdAfter:d.cwd}}}function Hd(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}var we=120000,br=600000,Gd=5000,zd={slug:"exec",provider:O,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 ${we}, maximum ${br}.`,default:we},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 Jd(e,t){let n=e===void 0||e<=0?we:e,r=Math.min(n,br),i=t-Gd;return Math.max(1,Math.min(r,i>0?i:Math.floor(t*0.8)))}function Zn(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function qd(e,t){let n=st();return{out:tt(n,`${e.turnId}-${t}.log`),status:tt(n,`${e.turnId}-${t}.status`)}}function Vd(e){return async(t,n)=>{let r=typeof t.command==="string"?t.command.trim():"";if(r==="")throw Na();let i=e.sessions.lastCwd(n.sessionKey),s=i??e.roots.primary,o=typeof t.workdir==="string"?t.workdir.trim():"",a=o===""?s:md(o)?o:tt(s,o),d;try{if(d=await fd(a),!(await pd(d)).isDirectory())throw Error("not a directory")}catch{let v=o===""&&i!==void 0;if(v)e.sessions.forget(n.sessionKey);throw Pa(a,v)}let c=Jd(Zn(t.timeoutMs),n.deadlineMs),l=Zn(t.timeoutMs),u=l!==void 0&&l!==we&&c<l,h=t.background===!0,f=st();await hd(f,{recursive:!0});let g=qd(n,Yd(r,n.turnId)),p=await yr({command:r,cwd:d,env:e.env,timeoutMs:c,pty:t.pty===!0,background:h,signal:n.signal,outPath:g.out,statusPath:g.status});if(p.cwdAfter!==void 0)e.sessions.remember(n.sessionKey,p.cwdAfter);let m=await fr(g.out),w=t.pty===!0?{...m,head:bd(m.head)}:m;if(await Jn(g.status,{force:!0}),!w.spilled&&p.ending!=="backgrounded")await Jn(g.out,{force:!0});return Xd({command:r,cwd:d,run:p,observation:w,clamped:u,timeoutMs:c,path:g.out})}}function Yd(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 Xd(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,Qe("Output so far",e.observation.head)].join(`
|
|
28
|
-
|
|
29
|
-
`);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 ${vd(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(Qe("First part of the output",e.observation.head)),n)r.push(Qe("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(`
|
|
30
|
-
|
|
31
|
-
`)}function Qe(e,t){return`${e}:
|
|
32
|
-
${t.trimEnd()}`}function Zd(e){return{spec:ot(zd,e.roots,["command","workdir"],"shell"),handler:Vd(e)}}var oc=["agent.yaml","agent.yml","SOUL.md","SOUL.compact.md","AGENTS.md","POLICY.md","REMINDER.md"],Sr=[".ssh",".aws",".kube",".gnupg",".docker"],Tr=/^(?:\.env(\..+)?|\.netrc|\.npmrc|\.pypirc|id_[a-z0-9]+|.*\.pem|.*\.key)$/i;function Er(e){return e.split($r).filter((t)=>t!=="")}function nt(e){let t=Er(e),n=t[t.length-1]??"";for(let r of Sr)if(t.includes(r))return`${r}/ holds credentials`;if(Tr.test(n))return`${n} holds secrets — the manifest names environment variables, and their values are not the agent's`;if(t[0]==="proc"&&(n==="environ"||n==="cmdline"))return`${e} is a process's environment, which holds this runtime's secrets`;return}function ac(e,t){let n=Er(e),r=n[n.length-1]??"";for(let a of Sr)if(n.includes(a))return`${a}/ holds credentials, and nothing under it is writable by an agent`;if(Tr.test(r))return`${r} holds secrets — the manifest names environment variables, and their values are not the agent's to edit`;let i=sc(t.agentDir),s=ic(i,e);if(s!==""&&!s.startsWith("..")&&!rc(s)){let a=s.split($r),d=a[a.length-1]??"";if(oc.includes(d))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 er=2000000,it=400;function dc(e){return e.subarray(0,8000).includes(0)}var cc={slug:"file_read",provider:O,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",policyArgIsPath:!0,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 ${it}.`,default:it}},required:["path"]}},lc={slug:"file_write",provider:O,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",policyArgIsPath:!0,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"]}},uc={slug:"file_edit",provider:O,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",policyArgIsPath:!0,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 ye(e,t,n,r){let i=Td(typeof e==="string"?e.trim():"");if(i==="")throw Ua();let s=t.lastCwd(n)??r;return nc(i)?Qn(i):Qn(s,i)}function Ar(e,t){if(!Id(e,t.roots))throw Ga(e,V(t.roots));let n=ac(e,{agentDir:t.agentDir,...t.protect===void 0?{}:{extra:t.protect}});if(n!==void 0)throw Ba(e,n)}function tr(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function hc(e){return async(t,n)=>{let r=ye(t.path,e.sessions,n.sessionKey,e.roots.primary);mr(r,e.roots);let i=nt(await ec(r).catch(()=>r))??nt(r);if(i!==void 0)throw Fa(r,i);let s;try{s=(await kr(r)).size}catch{throw dr(r)}if(s>er)throw ja(r,s,er);let o=await vr(r);if(dc(o))throw Da(r,s);let d=jA(o.toString("utf8")).split(`
|
|
33
|
-
`),c=Math.max(1,tr(t.offset)??1),l=Math.max(1,tr(t.limit)??it),u=d.slice(c-1,c-1+l);if(u.length===0)return`${r} has ${d.length} lines, so there is nothing at line ${c}.`;let h=u.join(`
|
|
34
|
-
`),f=c-1+u.length;if(c===1&&f>=d.length)return h;return`Lines ${c}-${f} of ${d.length} in ${r}:
|
|
35
|
-
${h}`}}function fc(e){return async(t,n)=>{let r=ye(t.path,e.sessions,n.sessionKey,e.roots.primary);Ar(r,e);let i=typeof t.content==="string"?t.content:String(t.content??""),s=await kr(r).then(()=>!0,()=>!1);await Qd(tc(r),{recursive:!0}),await _r(r,i,"utf8");let o=i===""?0:i.split(`
|
|
36
|
-
`).length;return`${s?"Replaced":"Created"} ${r} — ${o} line${o===1?"":"s"}, ${i.length} characters.`}}function pc(e){return async(t,n)=>{let r=ye(t.path,e.sessions,n.sessionKey,e.roots.primary);Ar(r,e);let i=typeof t.find==="string"?t.find:"",s=typeof t.replace==="string"?t.replace:"",o;try{o=await vr(r,"utf8")}catch{throw dr(r)}let a=i===""?0:o.split(i).length-1;if(a===0)throw Wa(r,i);if(a>1&&t.all!==!0)throw Ka(r,a);let d=t.all===!0?o.split(i).join(s):o.replace(i,s);await _r(r,d,"utf8");let c=t.all===!0?a:1;return`Edited ${r} — replaced ${c} occurrence${c===1?"":"s"}. The file is now ${d.split(`
|
|
37
|
-
`).length} lines.`}}function mc(e){let t=(n)=>ot(n,e.roots,["path"]);return[{spec:t(cc),handler:hc(e)},{spec:t(lc),handler:fc(e)},{spec:t(uc),handler:pc(e)}]}var vc=new Set(["node_modules",".git",".hg",".svn","dist","build","out",".next",".turbo",".cache","coverage","__pycache__",".venv","venv","target","vendor"]);function Ir(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 kc(e){return nr==="/"?e:e.split(nr).join("/")}async function Cr(e,t){let n=[],r=[e];while(r.length>0){let i=r.shift();if(i===void 0)break;let s;try{s=await wc(i,{withFileTypes:!0})}catch{continue}for(let o of s){let a=yc(i,o.name);if(o.isDirectory()){if(vc.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 d=kc(bc(e,a));if(t.accept!==void 0&&!t.accept(d))continue;if(n.length>=t.limit)return{files:n,truncated:!0};n.push(d)}}return{files:n,truncated:!1}}var rr=200,ir=100,_c=1e6,$c={slug:"glob",provider:O,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"]}},Sc={slug:"grep",provider:O,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 Rr(e,t,n){let r=typeof e.path==="string"&&e.path.trim()!==""?e.path:".",i=ye(r,t.sessions,n,t.roots.primary);return mr(i,t.roots),i}function Tc(e){return async(t,n)=>{let r=typeof t.pattern==="string"?t.pattern.trim():"",i=Rr(t,e,n.sessionKey),s=Ir(r),o=await Cr(i,{limit:rr,...t.hidden===!0?{hidden:!0}:{},accept:(d)=>s.test(d)});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 ${rr} 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}:`}
|
|
38
|
-
${o.files.join(`
|
|
39
|
-
`)}`}}function Ec(e){return async(t,n)=>{let r=typeof t.pattern==="string"?t.pattern:"",i=Rr(t,e,n.sessionKey),s;try{s=new RegExp(r,t.ignoreCase===!0?"i":"")}catch(h){throw Ha(r,String(h))}let o=typeof t.glob==="string"&&t.glob.trim()!==""?Ir(t.glob.trim()):void 0,a=await Cr(i,{limit:5000,...o===void 0?{}:{accept:(h)=>o.test(h)}}),d=[],c=0,l=!1;for(let h of a.files){if(d.length>=ir){l=!0;break}if(nt(`${i}/${h}`)!==void 0)continue;let f;try{let p=await gc(`${i}/${h}`);if(p.length>_c||p.subarray(0,8000).includes(0))continue;f=p.toString("utf8")}catch{continue}c+=1;let g=f.split(`
|
|
40
|
-
`);for(let p=0;p<g.length;p+=1){let m=g[p]??"";if(!s.test(m))continue;if(d.length>=ir){l=!0;break}let w=m.length>300?`${m.slice(0,300)}…`:m;d.push(`${h}:${p+1}: ${jA(w).trim()}`)}}if(d.length===0)return`Nothing under ${i} matches ${r}${o===void 0?"":` in files matching ${String(t.glob)}`}. ${c} file${c===1?"":"s"} were searched; node_modules, .git, dist and dot-files are skipped.`;return`${l?`The first ${d.length} matches for ${r} under ${i} — there are more, so narrow the pattern or pass a glob:`:`${d.length} match${d.length===1?"":"es"} for ${r} under ${i}, across ${c} file${c===1?"":"s"} searched:`}
|
|
41
|
-
${d.join(`
|
|
42
|
-
`)}`}}function Ac(e){let t=(n)=>ot(n,e.roots,["path"]);return[{spec:t($c),handler:Tc(e)},{spec:t(Sc),handler:Ec(e)}]}class xr{#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 sr(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}class Mr{id=O;#e=new xr;#n;constructor(e){let t=Ad(e.dir,e.writeRoots??[],e.confineReads===!0),n={sessions:this.#e,agentDir:e.dir,roots:t,...e.protect===void 0?{}:{protect:e.protect}};this.#n=[Zd({sessions:this.#e,env:e.env,roots:t}),...mc(n),...Ac({sessions:this.#e,roots:t}),...dd({agentDir:e.dir,...e.providers===void 0?{}:{providers:e.providers},...e.mediaProviders===void 0?{}:{mediaProviders:e.mediaProviders}})]}available(){return Promise.resolve(this.#n.map((e)=>({slug:e.spec.slug,summary:e.spec.summary})))}resolve(e){let t=new Set(e.map(sr));return Promise.resolve(this.#n.filter((n)=>t.has(sr(n.spec.slug))))}stop(){return Promise.resolve(Pd())}list(){return Promise.resolve(this.#n.map((e)=>e.spec.slug))}}var or=["protect","writeRoots","env","confineReads"];function at(e,t){let n=Object.keys(e.config).filter((a)=>!or.includes(a));if(n.length>0)throw new B({code:"system_config_unknown",message:`tools.providerConfig has ${n.length===1?"a key":"keys"} the system provider does not read: ${n.join(", ")}.`,hint:`Accepted keys are ${or.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 r=e.config.protect,i=e.config.writeRoots,s=e.config.confineReads;if(s!==void 0&&typeof s!=="boolean")throw new B({code:"system_config_invalid",message:"tools.providers.system.confineReads must be true or false.",hint:"true confines file_read, glob and grep to the agent's directory and its writeRoots; false, or leaving it out, keeps reads unconfined as before.",field:"tools.providers.system.confineReads"});let o=ud(e.config.env);return t?.(o),new Mr({env:ur(e.env,o),dir:e.dir,...e.providers===void 0?{}:{providers:e.providers},...e.mediaProviders===void 0?{}:{mediaProviders:e.mediaProviders},...Array.isArray(r)?{protect:r.map((a)=>String(a))}:{},...Array.isArray(i)?{writeRoots:i.map((a)=>String(a))}:{},...s===!0?{confineReads:!0}:{}})}function xc(e){return`'${e.replaceAll("'","'\\''")}'`}class be{#e;#n;constructor(e){this.#e=e.env,this.#n=e.policy??(()=>"inherit")}has(e){let t=this.#e.PATH??process.env.PATH??"";for(let n of t.split(Rc)){if(n==="")continue;try{let r=Ic(et(n,e));if(r.isFile()&&(r.mode&73)!==0)return!0}catch{}}return!1}async run(e){let t=st();await Cc(t,{recursive:!0});let n=Mc([e.command,...e.args].join(" ")),r=et(t,`skill-${n}.out`),i=et(t,`skill-${n}.status`),s=[e.command,...e.args].map(xc).join(" "),o=await yr({command:s,cwd:e.cwd,env:ur(this.#e,this.#n()),timeoutMs:e.timeoutMs,pty:!1,background:!1,signal:e.signal,outPath:r,statusPath:i}),a=await fr(r);if(await ar(i,{force:!0}),!a.spilled&&o.ending!=="backgrounded")await ar(r,{force:!0});let d=o.ending==="killed"||o.ending==="backgrounded",c=a.spilled?`${a.head}
|
|
43
|
-
|
|
44
|
-
… ${a.bytes} bytes in total; the rest is at ${r}
|
|
45
|
-
|
|
46
|
-
${a.tail}`:a.head;return{ok:o.ending==="finished"&&o.code===0,output:o.ending==="backgrounded"?`${c}
|
|
47
|
-
|
|
48
|
-
Still running past ${e.timeoutMs} ms, left going rather than discarded. Output continues to accumulate at ${r}.`:c,...o.code===void 0?{}:{code:o.code},timedOut:d}}}function Mc(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 Oc="0.1.0",Or={name:"system",version:Oc,dispachApi:"^0.2",permissions:[{kind:"exec",commands:["*"]},{kind:"fs",paths:["<workspace>"],mode:"write"}],setup(e){let t="inherit";e.defineToolProvider("system",(n)=>at(n,(r)=>{t=r})),e.defineScriptRunner(new be({env:e.env,policy:()=>t}))}};import{lookup as el}from"node:dns/promises";function Nr(e,t){return new S({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 Nc(e){return new S({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 Pc(){return new S({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 dt(e,t,n,r,i){let s=t===e?t:`${e} → ${t}`;return new S({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 ve(e,t){return new S({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 Pr(e,t){return new S({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 Lr(e,t){return new S({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 zr(e,t,n){return new S({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 Ur(e,t){return new S({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 Lc(e,t){return new S({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 Uc(e,t){return new B({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 jc(e,t,n){return new S({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 x(e,t){return new B({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}`})}function Dc(e){return new B({code:"web_firecrawl_key_missing",message:`Firecrawl needs ${e} and it is not set.`,hint:`Set ${e} in the .env beside agent.yaml, or in the environment (or ${e}_FILE naming a file that holds it). tools.providers.web.firecrawl.apiKeyEnv names a different variable if you need one.`,field:"tools.providers.web.firecrawl.apiKeyEnv"})}function Fc(e,t,n){return new S({code:t===402?"web_firecrawl_credits":"web_firecrawl_failed",message:`Firecrawl ${e} answered ${t}: ${n}`,hint:t===402?"The Firecrawl account is out of credits. Nothing here can fix that; say so rather than trying another page.":t===401||t===403?"The Firecrawl key was rejected. Check the value of the variable named in tools.providers.web.firecrawl.apiKeyEnv.":t===429?"Rate limited by Firecrawl. Wait before the next call; nothing in the manifest raises it.":"A failure at Firecrawl rather than in the request. The page may block its crawler; try another source."})}var jr=["tavily","brave","exa","firecrawl"];function b(e,t){return typeof e==="object"&&e!==null?e[t]:void 0}function C(e){return typeof e==="string"?e:""}function _e(e){return Array.isArray(e)?e:[]}var Bc={id:"tavily",defaultKeyEnv:"TAVILY_API_KEY",defaultBase:"https://api.tavily.com",unit:"credits",request(e,t,n,r){return{url:`${r}/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 _e(b(e,"results")).map((t)=>({title:C(b(t,"title")),url:C(b(t,"url")),snippet:C(b(t,"content"))}))}},Wc={id:"brave",defaultKeyEnv:"BRAVE_API_KEY",defaultBase:"https://api.search.brave.com/res/v1",unit:"requests",request(e,t,n,r){let i=new URL(`${r}/web/search`);return i.searchParams.set("q",e),i.searchParams.set("count",String(t)),{url:i.href,init:{method:"GET",headers:{accept:"application/json","x-subscription-token":n}}}},read(e){return _e(b(b(e,"web"),"results")).map((t)=>({title:C(b(t,"title")),url:C(b(t,"url")),snippet:C(b(t,"description"))}))}},Kc={id:"exa",defaultKeyEnv:"EXA_API_KEY",defaultBase:"https://api.exa.ai",unit:"requests",request(e,t,n,r){return{url:`${r}/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 _e(b(e,"results")).map((t)=>({title:C(b(t,"title")),url:C(b(t,"url")),snippet:C(b(t,"text"))||C(b(t,"snippet"))}))}},Hc={id:"firecrawl",defaultKeyEnv:"FIRECRAWL_API_KEY",defaultBase:"https://api.firecrawl.dev/v2",unit:"credits",request(e,t,n,r){return{url:`${r}/search`,init:{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({query:e,limit:t})}}},read(e){return _e(b(b(e,"data"),"web")).map((t)=>({title:C(b(t,"title")),url:C(b(t,"url")),snippet:C(b(t,"description"))}))},units(e){let t=b(e,"creditsUsed");return typeof t==="number"&&Number.isFinite(t)?t:1}},Gc={tavily:Bc,brave:Wc,exa:Kc,firecrawl:Hc};function qr(e){return Gc[e]}async function zc(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 jc(e,t.status,n)}var Jc=["script","style","noscript","template","svg","canvas","iframe","head"],qc=/<\/?(?: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,Vc={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 Vr(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 Vc[n.toLowerCase()]??t})}function Yc(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(e);if(t===null)return;let n=Yr(Vr(t[1]??""));return n===""?void 0:n}function Xc(e){let t=e;for(let n of Jc)t=t.replace(new RegExp(`<${n}\\b[^>]*>[\\s\\S]*?</${n}>`,"gi")," "),t=t.replace(new RegExp(`<${n}\\b[^>]*>[\\s\\S]*$`,"i")," ");return t=Jr(t," "),t=t.replace(qc,`
|
|
49
|
-
`),t=t.replace(/<[^>]*>/g," "),t=Vr(t),t.split(`
|
|
50
|
-
`).map((n)=>Yr(n)).filter((n,r,i)=>n!==""||(i[r-1]??"")!=="").join(`
|
|
51
|
-
`).trim()}function Yr(e){return e.replace(/\s+/g," ").trim()}function Zc(e,t){let n=t.split(";")[0]?.trim().toLowerCase()??"";if(n.includes("html")||n.includes("xml")){let r=Yc(e);return{text:Xc(e),...r===void 0?{}:{title:r}}}return{text:e.trim()}}function Qc(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 tl=new Set(["http:","https:"]),nl=[".local",".localhost",".internal",".intranet",".lan",".home.arpa"];function Xr(e){let t=e.trim();if(t==="")throw Nr(e,"the value is empty");try{return new URL(t)}catch(n){throw Nr(e,n instanceof Error?n.message:String(n))}}function rl(e){if(!tl.has(e.protocol))throw Nc(e.protocol.replace(":",""));if(e.username!==""||e.password!=="")throw Pc();let t=e.hostname.toLowerCase();if(t==="")throw ve(e.href,"there is no host in the URL");if(t==="localhost")throw ve(t,"it is this machine by definition");for(let r of nl)if(t.endsWith(r))throw ve(t,`${r} names are resolved on the local network, not the internet`);let n=t.startsWith("[")?"":t;if(n!==""&&!n.includes(".")&&Br(t)===void 0)throw ve(t,"a name with no dot in it is completed by the local search domain")}async function Zr(e,t,n=0){rl(e);let r=e.hostname.toLowerCase(),i=Br(r);if(i!==void 0){if(i.kind!=="public")throw dt(r,r,i.kind,i.range,n);return}let s;try{s=await t(r)}catch(o){throw Pr(r,o instanceof Error?o.message:String(o))}if(s.length===0)throw Pr(r,"it has no addresses");for(let{address:o}of s){let a=Br(o);if(a===void 0)throw dt(r,o,"an address this cannot classify",void 0,n);if(a.kind!=="public")throw dt(r,o,a.kind,a.range,n)}}var il=async(e)=>(await el(e,{all:!0,verbatim:!0})).map((n)=>({address:n.address})),X="web",Qr=2000000,ct=6000,ke=5,sl=3000,ol=20000,ei={slug:"web_fetch",provider:X,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 al(e){return{spec:ei,handler:cl(e)}}function dl(e){let t=Math.max(1000,e-sl);return Math.min(ol,t)}function cl(e){let t=e.maxBytes??Qr;return async(n,r)=>{let i=String(n.url??""),s=Xr(i),o=new AbortController,a=()=>{o.abort()};r.signal.addEventListener("abort",a,{once:!0});let d=setTimeout(a,dl(r.deadlineMs));try{for(let c=0;c<=ke;c+=1){await Zr(s,e.lookup,c);let l;try{l=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(v){throw Lr(s.href,v instanceof Error?v.message:String(v))}let u=l.headers.get("location");if(ll(l.status)&&u!==null){if(await l.body?.cancel().catch(()=>{return}),c===ke)throw Ur(i,ke);try{s=new URL(u,s)}catch{throw Lr(s.href,`it redirected to an unusable address: ${u}`)}continue}if(!l.ok)throw await l.body?.cancel().catch(()=>{return}),zr(s.href,l.status,l.statusText);let h=l.headers.get("content-type")??"";if(!Qc(h))throw await l.body?.cancel().catch(()=>{return}),Lc(s.href,h.split(";")[0]?.trim()??"binary");let{text:f,read:g,capped:p}=await ul(l,t),{title:m,text:w}=Zc(f,h);return ti({url:s.href,requested:i,...m===void 0?{}:{title:m},text:w,read:g,capped:p,hops:c})}throw Ur(i,ke)}finally{clearTimeout(d),r.signal.removeEventListener("abort",a)}}}function ll(e){return e===301||e===302||e===303||e===307||e===308}async function ul(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:d,value:c}=await r.read();if(d)break;if(c===void 0)continue;if(o+=c.byteLength,o>=t){let l=c.byteLength-(o-t);s.push(i.decode(c.subarray(0,Math.max(0,l)),{stream:!0})),a=!0;break}s.push(i.decode(c,{stream:!0}))}}finally{await r.cancel().catch(()=>{return})}return s.push(i.decode()),{text:s.join(""),read:Math.min(o,t),capped:a}}function ti(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>ct)n=n.slice(0,ct),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 ${ct.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(`
|
|
52
|
-
`)}var hl="https://api.firecrawl.dev/v2",lt=3000,ni=60000,fl=2000,pl=12000,ml=6000,ri=5,ii=20,si=100,oi=500;function y(e,t){return typeof e==="object"&&e!==null?e[t]:void 0}function T(e){if(typeof e==="string")return e;if(Array.isArray(e)&&typeof e[0]==="string")return e[0];return""}function ut(e,t){let n=y(e,"creditsUsed");return typeof n==="number"&&Number.isFinite(n)?n:t}async function Y(e,t,n,r,i){let s=e.env[e.config.apiKeyEnv]??"";if(s==="")throw Dc(e.config.apiKeyEnv);let o=await e.fetch(`${e.config.baseUrl??hl}${n}`,{method:r.method,headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},...r.body===void 0?{}:{body:JSON.stringify(r.body)},signal:i});if(!o.ok){let a=o.statusText;try{let d=await o.text(),c=T(y(gl(d),"error"));a=c!==""?c:d.length>300?`${d.slice(0,300)}…`:d}catch{}throw Fc(t,o.status,a)}return await o.json()}function gl(e){try{return JSON.parse(e)}catch{return}}function ht(e,t){let n=new AbortController,r=()=>n.abort();e.signal.addEventListener("abort",r,{once:!0});let i=setTimeout(r,Math.min(t,Math.max(1000,e.deadlineMs-lt)));return{signal:n.signal,done:()=>{clearTimeout(i),e.signal.removeEventListener("abort",r)}}}async function ft(e,t){let n=Xr(e);return await Zr(n,t.lookup),n}function wl(e){return{spec:ei,handler:async(n,r)=>{let i=String(n.url??""),s=await ft(i,e),o=Math.max(1000,Math.min(e.config.timeoutMs??ni,r.deadlineMs-2*lt)),{signal:a,done:d}=ht(r,o+lt);try{let c=await Y(e,"scrape","/scrape",{method:"POST",body:{url:s.href,formats:["markdown"],onlyMainContent:e.config.onlyMainContent,timeout:o,...e.config.maxAgeMs===void 0?{}:{maxAge:e.config.maxAgeMs}}},a);r.meter?.({provider:"firecrawl",operation:"scrape",unit:"credits",units:ut(c,1)});let l=y(c,"data"),u=y(l,"metadata"),h=y(u,"statusCode"),f=T(y(u,"url"))||T(y(u,"sourceURL"))||s.href;if(typeof h==="number"&&h>=400)throw zr(f,h,T(y(u,"error")));let g=T(y(u,"title")),p=T(y(l,"markdown"));return ti({url:f,requested:i,...g===""?{}:{title:g},text:p,read:p.length,capped:!1,hops:f===s.href?0:1})}finally{d()}}}}var yl={slug:"web_map",provider:X,summary:"Lists the page addresses on one website, optionally filtered by a phrase.",whenToUse:"you need to find the right page on a site you already know — its documentation, pricing, a changelog — before reading it with web_fetch",whenNotToUse:"you do not know the site yet, which is web_search; you already have the page's address, which is web_fetch; or you need the pages' text, which is web_crawl",mutating:!1,trust:"untrusted",policyArg:"url",tags:["read","web"],parameters:{type:"object",properties:{url:{type:"string",description:"The site's address, including https://. Public internet only."},search:{type:"string",description:"A word or phrase the addresses should relate to. Leave it out to list them all."},limit:{type:"integer",description:`How many addresses to return, 1 to ${oi}.`,default:si}},required:["url"]}};function bl(e){return{spec:yl,handler:async(n,r)=>{let i=await ft(String(n.url??""),e),s=String(n.search??"").trim(),o=ai(n.limit,si,oi),{signal:a,done:d}=ht(r,ni);try{let c=await Y(e,"map","/map",{method:"POST",body:{url:i.href,limit:o,...s===""?{}:{search:s}}},a);r.meter?.({provider:"firecrawl",operation:"map",unit:"credits",units:ut(c,1)});let l=(Array.isArray(y(c,"links"))?y(c,"links"):[]).map((p)=>typeof p==="string"?{url:p,title:""}:{url:T(y(p,"url")),title:T(y(p,"title"))}).filter((p)=>p.url!=="").slice(0,o);if(l.length===0)return`No addresses found on ${i.host}${s===""?"":` for ${JSON.stringify(s)}`}. The site may block crawlers or publish no sitemap; web_fetch on its home page is the other way in.`;let u=[],h=0;for(let p of l){let m=p.title===""?p.url:`${p.url} — ${p.title}`;if(h+m.length>ml)break;u.push(m),h+=m.length+1}let f=`${l.length} address${l.length===1?"":"es"} on ${i.host}${s===""?"":` for ${JSON.stringify(s)}`}:`,g=u.length<l.length?[`incomplete: only the first ${u.length} are shown; narrow it with search`]:[];return[f,...g,"",...u].join(`
|
|
53
|
-
`)}finally{d()}}}}var vl={slug:"web_crawl",provider:X,summary:"Reads several pages of one website, following its links, and returns their text.",whenToUse:"the answer is spread over a section of one site — a documentation chapter, a set of policy pages — and reading the pages one at a time would take many calls",whenNotToUse:"one page is enough, which is web_fetch; you only need the addresses, which is web_map; or you do not know the site, which is web_search. Each page costs, so keep the limit small",mutating:!1,trust:"untrusted",policyArg:"url",tags:["read","web"],parameters:{type:"object",properties:{url:{type:"string",description:"Where to start, including https://. Only pages on this site are read."},limit:{type:"integer",description:`How many pages to read, 1 to ${ii}.`,default:ri},includePaths:{type:"array",items:{type:"string"},description:"Only follow addresses whose path matches one of these regular expressions, such as ^/docs/. Leave it out to follow any page on the site."}},required:["url"]}};function kl(e){return{spec:vl,handler:async(n,r)=>{let i=await ft(String(n.url??""),e),s=ai(n.limit,ri,ii),o=Array.isArray(n.includePaths)?n.includePaths.map((l)=>String(l)).filter((l)=>l!==""):[],{signal:a,done:d}=ht(r,Number.POSITIVE_INFINITY),c="";try{let l=await Y(e,"crawl","/crawl",{method:"POST",body:{url:i.href,limit:s,...o.length===0?{}:{includePaths:o},scrapeOptions:{formats:["markdown"],onlyMainContent:e.config.onlyMainContent,...e.config.maxAgeMs===void 0?{}:{maxAge:e.config.maxAgeMs}}}},a);c=T(y(l,"id"));let u={};while(!a.aborted){if(await _l(fl,a),a.aborted)break;try{u=await Y(e,"crawl",`/crawl/${encodeURIComponent(c)}`,{method:"GET"},a)}catch(v){if(a.aborted)break;throw v}let w=T(y(u,"status"));if(w==="completed"||w==="failed")break}let h=T(y(u,"status")),f=(Array.isArray(y(u,"data"))?y(u,"data"):[]).map((w)=>({url:T(y(y(w,"metadata"),"sourceURL"))||T(y(y(w,"metadata"),"url")),markdown:T(y(w,"markdown"))})).filter((w)=>w.markdown!=="");if(r.meter?.({provider:"firecrawl",operation:"crawl",unit:"credits",units:ut(u,f.length)}),h!=="completed"&&c!=="")await Y(e,"crawl",`/crawl/${encodeURIComponent(c)}`,{method:"DELETE"},AbortSignal.timeout(5000)).catch(()=>{return});if(f.length===0)return h==="failed"?`The crawl of ${i.href} failed and read no pages. Try web_fetch on the page itself.`:`The crawl of ${i.href} read no pages in time. Try a smaller limit, or web_fetch on the page itself.`;let g=Math.floor(pl/f.length),p=f.map((w)=>{let v=w.markdown.length>g?`${w.markdown.slice(0,g).trimEnd()}
|
|
54
|
-
…(cut)`:w.markdown;return`## ${w.url}
|
|
55
|
-
|
|
56
|
-
${v}`}),m=[];if(h!=="completed")m.push("the crawl did not finish in time, so some pages are missing");if(f.some((w)=>w.markdown.length>g))m.push(`each page is cut to ${g.toLocaleString("en-US")} characters`);return[`${f.length} page${f.length===1?"":"s"} from ${i.host}:`,...m.length===0?[]:[`incomplete: ${m.join("; ")}`],"",p.join(`
|
|
57
|
-
|
|
58
|
-
`)].join(`
|
|
59
|
-
`)}finally{d()}}}}function ai(e,t,n){let r=typeof e==="number"?e:Number(e);if(!Number.isFinite(r))return t;return Math.min(n,Math.max(1,Math.trunc(r)))}function _l(e,t){return new Promise((n)=>{if(t.aborted)return n();let r=setTimeout(()=>{t.removeEventListener("abort",i),n()},e),i=()=>{clearTimeout(r),n()};t.addEventListener("abort",i,{once:!0})})}var di=5,ci=10,Dr=300,$l=3000,Sl=15000,Tl={slug:"web_search",provider:X,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 ${ci}.`,default:di}},required:["query"]}};function El(e){return{spec:Tl,handler:Al(e)}}function Al(e){let t=qr(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 Uc(t.id,e.apiKeyEnv);let o=Il(n.maxResults),{url:a,init:d}=t.request(i,o,s,e.baseUrl??t.defaultBase),c=new AbortController,l=()=>{c.abort()};r.signal.addEventListener("abort",l,{once:!0});let u=setTimeout(l,Math.min(Sl,Math.max(1000,r.deadlineMs-$l)));try{let h=await e.fetch(a,{...d,signal:c.signal});if(!h.ok)await zc(t.id,h);let f=await h.json();return r.meter?.({provider:t.id,operation:"search",unit:t.unit,units:t.units?.(f)??1}),Cl(i,t.read(f).slice(0,o))}finally{clearTimeout(u),r.signal.removeEventListener("abort",l)}}}function Il(e){let t=typeof e==="number"?e:Number(e);if(!Number.isFinite(t))return di;return Math.min(ci,Math.max(1,Math.trunc(t)))}function Cl(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>Dr?`${r.snippet.slice(0,Dr).trimEnd()}…`:r.snippet;return[`${i+1}. ${r.title===""?"(untitled)":r.title}`,` ${r.url}`,...s===""?[]:[` ${s.replace(/\s+/g," ")}`]].join(`
|
|
60
|
-
`)});return[`${t.length} result${t.length===1?"":"s"} for ${JSON.stringify(e)}:`,"",...n].join(`
|
|
61
|
-
`)}var Rl="dispach-agent/0.1 (+https://github.com/moeen-mahmud/dispach)";function Fr(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}class li{id=X;#e;constructor(e){let t=e.backend??"tavily",n=qr(t),r=e.fetch??((s,o)=>fetch(s,o)),i=e.lookup??il;this.#e=[El({backend:t,apiKeyEnv:e.apiKeyEnv??n.defaultKeyEnv,...e.baseUrl===void 0?{}:{baseUrl:e.baseUrl},env:e.env,fetch:r}),...e.firecrawl===void 0?[al({lookup:i,fetch:r,maxBytes:e.maxBytes??Qr,userAgent:Rl})]:(()=>{let s={config:e.firecrawl,env:e.env,fetch:r,lookup:i};return[wl(s),kl(s),bl(s)]})()]}available(){return Promise.resolve(this.#e.map((e)=>({slug:e.spec.slug,summary:e.spec.summary})))}resolve(e){let t=new Set(e.map(Fr));return Promise.resolve(this.#e.filter((n)=>t.has(Fr(n.spec.slug))))}list(){return Promise.resolve(this.#e.map((e)=>e.spec.slug))}}var Hr=["backend","apiKeyEnv","baseUrl","maxBytes","firecrawl"],Gr=["apiKeyEnv","baseUrl","onlyMainContent","maxAge","timeoutMs"];function pt(e){let t=Object.keys(e.config).filter((a)=>!Hr.includes(a));if(t.length>0)throw new B({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 ${Hr.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&&!jr.includes(String(n)))throw x("backend",`must be one of ${jr.join(", ")} — got ${JSON.stringify(n)}.`);let r=e.config.apiKeyEnv;if(r!==void 0&&(typeof r!=="string"||r===""))throw x("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 x("maxBytes","must be a number of at least 1000.");let s=ui(e.config.baseUrl,"baseUrl"),o=xl(e.config.firecrawl,n==="firecrawl",typeof r==="string"?r:void 0,s);return new li({env:e.env,...s===void 0?{}:{baseUrl:s},...o===void 0?{}:{firecrawl:o},...n===void 0?{}:{backend:String(n)},...typeof r==="string"?{apiKeyEnv:r}:{},...typeof i==="number"?{maxBytes:i}:{}})}function xl(e,t,n,r){if(e===void 0&&!t)return;let i=typeof e==="object"&&e!==null?e:{};if(e!==void 0&&(typeof e!=="object"||e===null||Array.isArray(e)))throw x("firecrawl","must be a map, e.g. `firecrawl: {}` for the defaults.");let s=Object.keys(i).find((f)=>!Gr.includes(f));if(s!==void 0)throw x(`firecrawl.${s}`,`is not a setting. Accepted: ${Gr.join(", ")}.`);let o=i.apiKeyEnv;if(o!==void 0&&(typeof o!=="string"||o===""))throw x("firecrawl.apiKeyEnv","must be the non-empty name of an environment variable.");let a=i.onlyMainContent;if(a!==void 0&&typeof a!=="boolean")throw x("firecrawl.onlyMainContent","must be true or false.");let d=(f,g,p)=>{let m=i[f];if(m===void 0)return;if(typeof m!=="number"||!Number.isFinite(m)||m<g||m>p)throw x(`firecrawl.${f}`,`must be a number of milliseconds from ${g} to ${p}.`);return m},l=ui(i.baseUrl,"firecrawl.baseUrl")??(t?r:void 0),u=d("maxAge",0,2592000000),h=d("timeoutMs",1000,300000);return{apiKeyEnv:typeof o==="string"?o:t&&n!==void 0?n:"FIRECRAWL_API_KEY",onlyMainContent:a??!0,...l===void 0?{}:{baseUrl:l},...u===void 0?{}:{maxAgeMs:u},...h===void 0?{}:{timeoutMs:h}}}function ui(e,t){if(e===void 0)return;let n;try{n=new URL(String(e))}catch{throw x(t,`is not a URL: ${JSON.stringify(e)}.`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw x(t,"must be an http or https address.");if(n.username!==""||n.password!=="")throw x(t,"must not carry credentials. The key travels in the request's own header, from apiKeyEnv.");return n.href.replace(/\/+$/,"")}var Ml="0.1.0",hi={name:"web",version:Ml,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["*"]}],setup(e){e.defineToolProvider("web",pt)}};var oe={composio:Je,mcp:(e)=>Ye(e),system:at,web:pt},Se={"bedrock-converse":Ue()},Ie={aws:Fe()};function de(){return new be({env:process.env})}var Oh=Object.keys(oe),ce={teams:Ce,slack:Te,telegram:Me,whatsapp:Ne},Nh=Object.keys(ce),he={"@dispach/channel-a2a":yt,"@dispach/channel-teams":Mt,"@dispach/channel-slack":$t,"@dispach/channel-telegram":jt,"@dispach/channel-whatsapp":Xt,"@dispach/media-aws":dn,"@dispach/model-bedrock":rn,"@dispach/tools-composio":In,"@dispach/tools-mcp":Bn,"@dispach/tools-system":Or,"@dispach/tools-web":hi},Kr=Object.keys(he);
|
|
62
|
-
export{oe,Se,Ie,de,ce,he,Kr};
|
|
63
|
-
|
|
64
|
-
//# debugId=A5B533EB7A9539D964756E2164756E21
|
|
65
|
-
//# sourceMappingURL=index-358nsn9t.js.map
|