dispach 0.2.1 → 0.2.3
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 +94 -36
- package/dist/APEv2Parser-ysjr6adv.js +5 -0
- package/dist/{FlacParser-bf8y3e0w.js.map → APEv2Parser-ysjr6adv.js.map} +1 -1
- package/dist/{AiffParser-tbx3xkmk.js → AiffParser-9hj6fpmy.js} +3 -3
- package/dist/{AiffParser-tbx3xkmk.js.map → AiffParser-9hj6fpmy.js.map} +1 -1
- package/dist/App-2f72vhjv.js +11 -0
- package/dist/{App-hjn867nc.js.map → App-2f72vhjv.js.map} +3 -3
- package/dist/{AsfParser-d784ak3y.js → AsfParser-7emspn04.js} +3 -3
- package/dist/{AsfParser-d784ak3y.js.map → AsfParser-7emspn04.js.map} +1 -1
- package/dist/{ConfigEditor-g7eb2wsm.js → ConfigEditor-vk7vxaa6.js} +3 -3
- package/dist/{ConfigEditor-g7eb2wsm.js.map → ConfigEditor-vk7vxaa6.js.map} +1 -1
- package/dist/{DsdiffParser-vxnfx80c.js → DsdiffParser-dz88pnnr.js} +3 -3
- package/dist/{DsdiffParser-vxnfx80c.js.map → DsdiffParser-dz88pnnr.js.map} +1 -1
- package/dist/{DsfParser-0xsh0zzk.js → DsfParser-qgh63tbs.js} +3 -3
- package/dist/{DsfParser-0xsh0zzk.js.map → DsfParser-qgh63tbs.js.map} +1 -1
- package/dist/FlacParser-drm5wq0p.js +5 -0
- package/dist/{APEv2Parser-9wqew3zv.js.map → FlacParser-drm5wq0p.js.map} +1 -1
- package/dist/{KeyProbe-w8c37s9q.js → KeyProbe-5anphmb7.js} +3 -3
- package/dist/{KeyProbe-w8c37s9q.js.map → KeyProbe-5anphmb7.js.map} +1 -1
- package/dist/{MP4Parser-tq7r7wd4.js → MP4Parser-yr7p3z12.js} +3 -3
- package/dist/{MP4Parser-tq7r7wd4.js.map → MP4Parser-yr7p3z12.js.map} +1 -1
- package/dist/{MatroskaParser-a79gsmzb.js → MatroskaParser-jkbsbsk3.js} +3 -3
- package/dist/{MatroskaParser-a79gsmzb.js.map → MatroskaParser-jkbsbsk3.js.map} +1 -1
- package/dist/{MpegParser-zs61b3wq.js → MpegParser-t93vwnew.js} +3 -3
- package/dist/{MpegParser-zs61b3wq.js.map → MpegParser-t93vwnew.js.map} +1 -1
- package/dist/{MusepackParser-bp8dm6nz.js → MusepackParser-6e8kbh2d.js} +3 -3
- package/dist/{MusepackParser-bp8dm6nz.js.map → MusepackParser-6e8kbh2d.js.map} +1 -1
- package/dist/OggParser-ggcypmag.js +5 -0
- package/dist/{OggParser-7pxr1sn9.js.map → OggParser-ggcypmag.js.map} +1 -1
- package/dist/Picker-j7txnm7w.js +5 -0
- package/dist/{Picker-b09hr4tk.js.map → Picker-j7txnm7w.js.map} +1 -1
- package/dist/SessionPicker-hpv2ncsb.js +5 -0
- package/dist/{SessionPicker-wtfxwdxg.js.map → SessionPicker-hpv2ncsb.js.map} +3 -3
- package/dist/SkillBrowser-qc542n71.js +5 -0
- package/dist/{SkillBrowser-p9ht63c7.js.map → SkillBrowser-qc542n71.js.map} +1 -1
- package/dist/{WavPackParser-gpf3r92t.js → WavPackParser-jw9stzqp.js} +3 -3
- package/dist/{WavPackParser-gpf3r92t.js.map → WavPackParser-jw9stzqp.js.map} +1 -1
- package/dist/{WaveParser-3kcak550.js → WaveParser-epmncs9w.js} +3 -3
- package/dist/{WaveParser-3kcak550.js.map → WaveParser-epmncs9w.js.map} +1 -1
- package/dist/WizardApp-pgzcz9zq.js +5 -0
- package/dist/{WizardApp-494018sk.js.map → WizardApp-pgzcz9zq.js.map} +3 -3
- package/dist/{channels-yhdvxxrb.js → channels-m8nambmm.js} +14 -14
- package/dist/{channels-yhdvxxrb.js.map → channels-m8nambmm.js.map} +1 -1
- package/dist/client.d.ts +285 -1
- package/dist/client.js +11 -11
- package/dist/client.js.map +5 -5
- package/dist/components/App.d.ts.map +1 -1
- package/dist/{config-g0ybmm4t.js → config-hmgrqgf2.js} +17 -17
- package/dist/{config-g0ybmm4t.js.map → config-hmgrqgf2.js.map} +1 -1
- package/dist/{credential-pkme1sfe.js → credential-nkb2ya59.js} +5 -5
- package/dist/{credential-pkme1sfe.js.map → credential-nkb2ya59.js.map} +1 -1
- package/dist/{index-q8b1fc3k.js → index-0444sh6x.js} +4 -4
- package/dist/{index-q8b1fc3k.js.map → index-0444sh6x.js.map} +1 -1
- package/dist/{index-ec101x93.js → index-095hrkyr.js} +6 -6
- package/dist/{index-ec101x93.js.map → index-095hrkyr.js.map} +1 -1
- package/dist/index-1mbdz3f7.js +12 -0
- package/dist/{index-3fgq1acj.js.map → index-1mbdz3f7.js.map} +3 -3
- package/dist/index-1x8mzvz7.js +6 -0
- package/dist/{index-f056wkb4.js.map → index-1x8mzvz7.js.map} +1 -1
- package/dist/{index-633eqxry.js → index-22fzzn7z.js} +7 -7
- package/dist/{index-633eqxry.js.map → index-22fzzn7z.js.map} +1 -1
- package/dist/index-2bsardvh.js +5 -0
- package/dist/{index-9dmgk6d3.js.map → index-2bsardvh.js.map} +2 -2
- package/dist/{index-thmq816c.js → index-2zjh5zd5.js} +4 -4
- package/dist/{index-thmq816c.js.map → index-2zjh5zd5.js.map} +1 -1
- package/dist/{index-ad5c9t83.js → index-308y9xt0.js} +4 -4
- package/dist/{index-ad5c9t83.js.map → index-308y9xt0.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-mn34kj95.js → index-3826kf9t.js} +5 -5
- package/dist/{index-mn34kj95.js.map → index-3826kf9t.js.map} +1 -1
- package/dist/index-38gs9anh.js +9 -0
- package/dist/{index-akv6e7ge.js.map → index-38gs9anh.js.map} +1 -1
- package/dist/index-3c5jt6by.js +5 -0
- package/dist/{index-3b3h8kyh.js.map → index-3c5jt6by.js.map} +2 -2
- package/dist/{index-a6mtqkth.js → index-3vzf253k.js} +7 -7
- package/dist/{index-a6mtqkth.js.map → index-3vzf253k.js.map} +1 -1
- package/dist/{index-5m9wydxb.js → index-42e29zs4.js} +4 -4
- package/dist/{index-5m9wydxb.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-s2tzq27a.js → index-51x0n5z0.js} +5 -5
- package/dist/{index-s2tzq27a.js.map → index-51x0n5z0.js.map} +1 -1
- package/dist/index-836hc2h1.js +6 -0
- package/dist/{index-xa9crtzq.js.map → index-836hc2h1.js.map} +2 -2
- package/dist/index-8edck2pr.js +6 -0
- package/dist/{index-7gsbzvnc.js.map → index-8edck2pr.js.map} +1 -1
- package/dist/index-8tmv33mr.js +6 -0
- package/dist/{index-vw2hf4d8.js.map → index-8tmv33mr.js.map} +1 -1
- package/dist/index-9t4dz145.js +8 -0
- package/dist/{index-0mz7wpbw.js.map → index-9t4dz145.js.map} +2 -2
- 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-djeqvfms.js +74 -0
- package/dist/index-djeqvfms.js.map +13 -0
- package/dist/{index-307qmvb0.js → index-dpcm1j62.js} +28 -28
- package/dist/{index-307qmvb0.js.map → index-dpcm1j62.js.map} +1 -1
- package/dist/index-dv9pdjy4.js +429 -0
- package/dist/index-dv9pdjy4.js.map +12 -0
- package/dist/{index-j20k6k0m.js → index-dzy19wtf.js} +4 -4
- package/dist/{index-j20k6k0m.js.map → index-dzy19wtf.js.map} +1 -1
- package/dist/{index-9qv87rq7.js → index-eztfverw.js} +7 -7
- package/dist/{index-9qv87rq7.js.map → index-eztfverw.js.map} +1 -1
- package/dist/{index-myg5enf5.js → index-fbsrhcga.js} +4 -4
- package/dist/{index-myg5enf5.js.map → index-fbsrhcga.js.map} +1 -1
- package/dist/{index-6r9h7ftn.js → index-fxpmx6cr.js} +117 -117
- package/dist/index-fxpmx6cr.js.map +21 -0
- package/dist/{index-ye2yb3xf.js → index-hgm2gchq.js} +6 -6
- package/dist/{index-ye2yb3xf.js.map → index-hgm2gchq.js.map} +1 -1
- package/dist/index-hpvfqq6r.js +1252 -0
- package/dist/{index-26ejkp8q.js.map → index-hpvfqq6r.js.map} +30 -26
- package/dist/{index-y34s71qe.js → index-hrwakb11.js} +3 -3
- package/dist/{index-y34s71qe.js.map → index-hrwakb11.js.map} +1 -1
- package/dist/{index-qh82wtpa.js → index-jc4kmfwa.js} +4 -4
- package/dist/{index-qh82wtpa.js.map → index-jc4kmfwa.js.map} +1 -1
- package/dist/{index-twcgf73h.js → index-jff5q27j.js} +4 -4
- package/dist/{index-twcgf73h.js.map → index-jff5q27j.js.map} +1 -1
- package/dist/index-k8e9f466.js +110 -0
- package/dist/index-k8e9f466.js.map +13 -0
- package/dist/{index-trx9xb59.js → index-m6fqx0ch.js} +7 -7
- package/dist/{index-trx9xb59.js.map → index-m6fqx0ch.js.map} +1 -1
- package/dist/{index-ac2wzspd.js → index-mjfv7k5w.js} +4 -4
- package/dist/{index-ac2wzspd.js.map → index-mjfv7k5w.js.map} +1 -1
- package/dist/index-nvc24414.js +6 -0
- package/dist/{index-1f1erzfx.js.map → index-nvc24414.js.map} +1 -1
- package/dist/index-nxhqf597.js +6 -0
- package/dist/{index-w97gprre.js.map → index-nxhqf597.js.map} +1 -1
- package/dist/{index-jh2az41t.js → index-p6ya59m6.js} +5 -5
- package/dist/{index-jh2az41t.js.map → index-p6ya59m6.js.map} +1 -1
- package/dist/{index-psk6q25h.js → index-pqw1n1pv.js} +4 -4
- package/dist/{index-psk6q25h.js.map → index-pqw1n1pv.js.map} +1 -1
- package/dist/{index-6c4p19m1.js → index-pszmnhgq.js} +2 -2
- package/dist/index-qgsdgbk8.js +5 -0
- package/dist/{index-wk6andxq.js.map → index-qgsdgbk8.js.map} +2 -2
- package/dist/index-qv6ktepc.js +6 -0
- package/dist/index-qv6ktepc.js.map +10 -0
- package/dist/{index-pdsey1ab.js → index-ry6a4bqh.js} +62 -62
- package/dist/{index-pdsey1ab.js.map → index-ry6a4bqh.js.map} +1 -1
- package/dist/{index-x9z2xnct.js → index-sh44ymqz.js} +5 -5
- package/dist/{index-x9z2xnct.js.map → index-sh44ymqz.js.map} +1 -1
- package/dist/{index-zg89tq04.js → index-snz49ndn.js} +4 -4
- package/dist/{index-zg89tq04.js.map → index-snz49ndn.js.map} +1 -1
- package/dist/{index-zjphh8ch.js → index-xg7s813b.js} +4 -4
- package/dist/{index-zjphh8ch.js.map → index-xg7s813b.js.map} +1 -1
- package/dist/{index-gqaa06yh.js → index-y7dxq4a4.js} +9 -9
- package/dist/{index-gqaa06yh.js.map → index-y7dxq4a4.js.map} +1 -1
- package/dist/index-ytxbw8py.js +63 -0
- package/dist/{index-0pddq849.js.map → index-ytxbw8py.js.map} +2 -2
- package/dist/index-yw3fby4n.js +6 -0
- package/dist/{index-4emtktc0.js.map → index-yw3fby4n.js.map} +2 -2
- package/dist/{index-skkddg44.js → index-zw6wyas6.js} +4 -4
- package/dist/{index-skkddg44.js.map → index-zw6wyas6.js.map} +1 -1
- package/dist/index.js +304 -288
- 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 +25 -0
- package/dist/lib/source.d.ts.map +1 -1
- package/dist/lib/types.d.ts +8 -2
- package/dist/lib/types.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-f6869dy2.js → web-gfv0mzgs.js} +7 -7
- package/dist/{web-f6869dy2.js.map → web-gfv0mzgs.js.map} +1 -1
- package/dist/wire.d.ts +50 -0
- package/dist/wire.js +5 -5
- package/dist/wire.js.map +4 -4
- package/dist/wrapper-f662ny3r.js +5 -0
- package/dist/{wrapper-52c0vacs.js.map → wrapper-f662ny3r.js.map} +1 -1
- package/package.json +4 -1
- package/dist/APEv2Parser-9wqew3zv.js +0 -5
- package/dist/App-hjn867nc.js +0 -11
- package/dist/FlacParser-bf8y3e0w.js +0 -5
- package/dist/OggParser-7pxr1sn9.js +0 -5
- package/dist/Picker-b09hr4tk.js +0 -5
- package/dist/SessionPicker-wtfxwdxg.js +0 -5
- package/dist/SkillBrowser-p9ht63c7.js +0 -5
- package/dist/WizardApp-494018sk.js +0 -5
- package/dist/index-0mz7wpbw.js +0 -8
- package/dist/index-0pddq849.js +0 -63
- package/dist/index-1f1erzfx.js +0 -6
- package/dist/index-26ejkp8q.js +0 -1194
- package/dist/index-3b3h8kyh.js +0 -5
- package/dist/index-3fgq1acj.js +0 -12
- package/dist/index-4emtktc0.js +0 -6
- package/dist/index-4t3p7vm9.js +0 -6
- package/dist/index-4t3p7vm9.js.map +0 -10
- package/dist/index-6r9h7ftn.js.map +0 -21
- package/dist/index-7gsbzvnc.js +0 -6
- package/dist/index-94k4mh6s.js +0 -96
- package/dist/index-94k4mh6s.js.map +0 -13
- package/dist/index-9dmgk6d3.js +0 -5
- package/dist/index-akv6e7ge.js +0 -9
- package/dist/index-f056wkb4.js +0 -6
- package/dist/index-s57ztjhq.js +0 -74
- package/dist/index-s57ztjhq.js.map +0 -13
- package/dist/index-vw2hf4d8.js +0 -6
- package/dist/index-w97gprre.js +0 -6
- package/dist/index-wk6andxq.js +0 -5
- package/dist/index-xa9crtzq.js +0 -6
- package/dist/index-z0dgxd7d.js +0 -429
- package/dist/index-z0dgxd7d.js.map +0 -11
- package/dist/wrapper-52c0vacs.js +0 -5
- /package/dist/{index-6c4p19m1.js.map → index-pszmnhgq.js.map} +0 -0
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`);if(i.length>e.maxChars)throw new
|
|
2
|
+
import{se,T,te,h,st,S,xe,jt,ro,io,zr,ao,Ns,Ms,qt,Ts,go,sA,ti,Qr}from"./index-djeqvfms.js";import{bt,Ot,z,hn}from"./index-hpvfqq6r.js";import{randomUUID as Wr}from"node:crypto";import{randomUUID as ct}from"node:crypto";var Et="1.0",we={parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,taskNotFound:-32001,taskNotCancelable:-32002,unsupportedOperation:-32004,contentTypeNotSupported:-32005,versionNotSupported:-32009},Ic=["TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED"],Cc=3600000,Pc=3000;class pe extends Error{code;status;constructor(e,t,n=200){super(t);this.code=e,this.status=n}}class Vr{#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",Lc(this.#e.peers))},stop:async()=>{this.#a=void 0},send:async(n)=>this.#w(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 o=this.#m(t);if(o!==void 0)this.#g(o,"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)},Pc).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:Et,supportedInterfaces:[{url:t,protocolBinding:"JSONRPC",protocolVersion:Et}],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 pe(we.versionNotSupported,`A2A-Version ${n} is not supported; this agent speaks ${Et}.`);let r=this.#s(e.caller),i;try{i=await e.request.json()}catch{throw new pe(we.parse,"The body is not JSON.")}let o=typeof i==="object"&&i!==null?i:{};if(t=o.id??null,o.jsonrpc!=="2.0"||typeof o.method!=="string")throw new pe(we.invalidRequest,"Not a JSON-RPC 2.0 request.");this.#c(r);let s=typeof o.params==="object"&&o.params!==null?o.params:{};switch(o.method){case"SendMessage":return Hr(t,await this.#l(r,s));case"SendStreamingMessage":return this.#d(t,await this.#u(r,s));case"GetTask":return Hr(t,this.#p(r,s.id).task);case"CancelTask":{let c=this.#p(r,s.id);throw new pe(we.taskNotCancelable,c.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 pe(o.method.startsWith("SendMessage")||o.method.includes("PushNotification")?we.unsupportedOperation:we.methodNotFound,`${o.method} is not supported here.`)}}catch(n){if(n instanceof pe)return Rc(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 pe(we.invalidRequest,"This credential is not a peer of this agent. Each peer calls with the operator key its `key` names.",403);return t}#c(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 pe(we.invalidRequest,`Peer ${e.name} is over ${e.ratePerMinute} requests a minute.`,429);this.#i.set(e.name,[...n,t])}async#l(e,t){let n=await this.#u(e,t);if(t.configuration?.returnImmediately===!0||n.endedAt!==void 0)return this.#h(n);return{task:await this.#f(n,this.#e.waitMs)}}async#u(e,t){this.#v();let n=typeof t.message==="object"&&t.message!==null?t.message:{},r=Array.isArray(n.parts)?n.parts:[];if(r.length===0)throw new pe(we.invalidParams,"The message has no parts.");if(r.some((d)=>typeof d.text!=="string"))throw new pe(we.contentTypeNotSupported,"Only text parts are accepted.");let i=r.map((d)=>String(d.text)).join(`
|
|
3
|
+
`);if(i.length>e.maxChars)throw new pe(we.invalidParams,`The message is ${i.length} characters; ${e.name} may send ${e.maxChars}.`);let o=typeof n.messageId==="string"&&n.messageId!==""?n.messageId:ct(),s=this.#o.get(`${e.name}\x1F${o}`),c=s===void 0?void 0:this.#t.get(s);if(c!==void 0)return c;let l=this.#a;if(l===void 0)throw new pe(we.unsupportedOperation,"This agent has no running a2a channel. Add `channels: [{type: a2a, id: a2a}]`.",503);let a=typeof n.contextId==="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(n.contextId)?n.contextId:ct(),p=`${e.name}:${a}`,f={task:{id:ct(),contextId:a,status:{state:"TASK_STATE_WORKING",timestamp:new Date().toISOString()},artifacts:[]},peer:e.name,recipient:p,messageId:o,text:"",waiters:[]};return this.#t.set(f.task.id,f),this.#o.set(`${e.name}\x1F${o}`,f.task.id),this.#r.set(p,[...this.#r.get(p)??[],f.task.id]),l.receive({peerId:p,senderHandle:e.name,senderName:e.name,senderKind:"agent",providerMessageId:o,receivedAt:new Date().toISOString(),text:i}),f}#d(e,t){let n=new TextEncoder,r=(o)=>n.encode(`data: ${JSON.stringify({jsonrpc:"2.0",id:e,result:o})}
|
|
4
4
|
|
|
5
|
-
`),i=new ReadableStream({start:async(o)=>{o.enqueue(r(this.#h(t)));let s=await this.#f(t,this.#e.waitMs);o.enqueue(r({statusUpdate:{taskId:s.id,contextId:s.contextId,status:s.status}})),o.close()}});return new Response(i,{headers:{"content-type":"text/event-stream","cache-control":"no-cache"}})}#f(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.#v();let n=typeof t==="string"?this.#t.get(t):void 0;if(n===void 0||n.peer!==e.name)throw new
|
|
5
|
+
`),i=new ReadableStream({start:async(o)=>{o.enqueue(r(this.#h(t)));let s=await this.#f(t,this.#e.waitMs);o.enqueue(r({statusUpdate:{taskId:s.id,contextId:s.contextId,status:s.status}})),o.close()}});return new Response(i,{headers:{"content-type":"text/event-stream","cache-control":"no-cache"}})}#f(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.#v();let n=typeof t==="string"?this.#t.get(t):void 0;if(n===void 0||n.peer!==e.name)throw new pe(we.taskNotFound,"No such task.");return n}#h(e){return{task:e.task}}#m(e){let t=this.#r.get(e)?.[0];return t===void 0?void 0:this.#t.get(t)}#w(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:ct(),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:ct(),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)}#v(){let e=Date.now()-Cc;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 Mc(e){return Ic.includes(e)}function Hr(e,t){return Response.json({jsonrpc:"2.0",id:e,result:t})}function Rc(e,t,n,r){return Response.json({jsonrpc:"2.0",id:e,error:{code:t,message:n}},{status:r})}function Lc(e){if(e.length===0)return"no peers configured";return e.map((t)=>{let n=[...t.key===void 0?[]:["calls in"],...t.url===void 0?[]:["is called"]];return`${t.name} ${n.join(" and ")}`}).join(" · ")}function xc(e){let t=typeof e==="object"&&e!==null?e:{},n=(o)=>(o??[]).flatMap((s)=>typeof s.text==="string"?[s.text]:[]).join(`
|
|
6
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(!Mc(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((o)=>n(o.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 xc(e,t=fetch){let n=e.peers.filter((i)=>i.url!==void 0),r=new Map;return(i)=>{let o={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((s)=>s.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((s)=>s.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(s,c){let l=n.find((g)=>g.name===s.peer);if(l?.url===void 0)throw new ee({code:"a2a_peer_unknown",message:`No peer "${String(s.peer)}" to send to.`,hint:`The peers this agent may call are: ${n.map((g)=>g.name).join(", ")||"none"}. Another needs a url in the plugin's peers.`});let a=l.tokenEnv===void 0?void 0:i.env[l.tokenEnv];if(l.tokenEnv!==void 0&&(a===void 0||a===""))throw new ee({code:"a2a_peer_token_missing",message:`Peer ${l.name} needs ${l.tokenEnv}, which is not set.`,hint:`Put the key ${l.name} issued to this agent in ${l.tokenEnv}, in the .env beside the manifest.`});let p=`${c.sessionKey}\x1F${l.name}`,f=AbortSignal.timeout(Math.max(1000,Math.min(60000,c.deadlineMs-5000))),d;try{d=await t(l.url,{method:"POST",headers:{"content-type":"application/json","a2a-version":Et,...a===void 0?{}:{authorization:`Bearer ${a}`}},body:JSON.stringify({jsonrpc:"2.0",id:Vr(),method:"SendMessage",params:{message:{messageId:Vr(),role:"ROLE_USER",parts:[{text:String(s.text??"")}],...r.has(p)?{contextId:r.get(p)}:{}}}}),signal:AbortSignal.any([c.signal,f])})}catch(g){throw new ee({code:"a2a_peer_unreachable",message:`Peer ${l.name} did not answer: ${g instanceof Error?g.message:String(g)}`,hint:`Check ${l.url} is reachable from this runtime; a timeout is 60 seconds at most.`})}let u=await d.json().catch(()=>({}));if(u.error!==void 0||!d.ok)throw new ee({code:"a2a_peer_refused",message:`Peer ${l.name} refused: ${u.error?.message??`HTTP ${d.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 m=u.result?.task?.contextId??u.result?.message?.contextId;if(typeof m==="string")r.set(p,m);return Lc(u.result)}};return{id:"a2a",resolve:async(s)=>s.includes("a2a_send")?[o]:[]}}}var Pe=(e)=>typeof e==="string"&&e.trim()!==""?e.trim():void 0,$n=(e,t,n)=>{if(e===void 0)return t;if(typeof e==="number"&&Number.isInteger(e)&&e>0)return e;throw Ye(`${n} must be a positive whole number.`,n)};function Ye(e,t){return new h({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 Dc(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(([l,a])=>{if(!/^[a-z0-9][a-z0-9-]*$/.test(l))throw Ye(`Peer "${l}" needs a lowercase slug name; it becomes part of a session key.`,`peers.${l}`);let p=typeof a==="object"&&a!==null?a:{},f=Pe(p.key),d=Pe(p.url),u=Pe(p.tokenEnv);if(f===void 0&&d===void 0)throw Ye(`Peer "${l}" names neither a key (inbound) nor a url (outbound).`,`peers.${l}`);if(d!==void 0&&!/^https?:\/\//.test(d))throw Ye(`Peer "${l}"'s url must be absolute http(s).`,`peers.${l}.url`);return{name:l,...f===void 0?{}:{key:f},...d===void 0?{}:{url:d},...u===void 0?{}:{tokenEnv:u},ratePerMinute:$n(p.ratePerMinute,30,`peers.${l}.ratePerMinute`),maxChars:$n(p.maxChars,20000,`peers.${l}.maxChars`)}}),o=i.flatMap((l)=>l.key===void 0?[]:[l.key]);if(new Set(o).size!==o.length)throw Ye("Two peers name the same key; a key identifies exactly one peer.","peers");let s=Array.isArray(n.skills)?n.skills:[],c=Pe(t.publicUrl);return{card:{name:Pe(n.name)??"Agent",description:Pe(n.description)??"",skills:s.map((l,a)=>{let p=typeof l==="object"&&l!==null?l:{},f=Pe(p.id);if(f===void 0)throw Ye("A card skill needs an id.",`card.skills.${a}`);return{id:f,name:Pe(p.name)??f,description:Pe(p.description)??"",tags:Array.isArray(p.tags)?p.tags.map(String):[]}})},peers:i,...c===void 0?{}:{publicUrl:c},waitMs:$n(t.waitMs,60000,"waitMs")}}var jc="0.1.0",Xr={name:"a2a",version:jc,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["*"]}],setup(e){let t=Dc(e.config),n=new Yr(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",xc(t)),e.events.on("turn.end",(r)=>n.observe(r))}};import{readFile as Uc}from"node:fs/promises";import{basename as zc}from"node:path";function ei(e){return e.files?.find((t)=>t.url_private_download!==void 0&&(t.subtype==="slack_audio"||t.mimetype?.startsWith("audio/")===!0))}function ti(e){return(e.files??[]).filter((t)=>t.url_private_download!==void 0&&t.mimetype?.startsWith("image/")===!0)}var Fc={"&":"&","<":"<",">":">"};function Bc(e,t){return(t===void 0?e.replace(/^\s*<@[A-Z0-9]+>/,""):e.replaceAll(`<@${t}>`,"")).replace(/&(amp|lt|gt);/g,(r)=>Fc[r]??r).replace(/\s+/g," ").trim()}function Kc(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=Bc(e.text??"",t);if(r===""&&ei(e)===void 0&&ti(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 qc="https://slack.com/api/",Zc="https://files.slack.com/",Wc=[1000,2000,5000,15000,30000];class At extends Error{detail;constructor(e){super(e.message);this.detail=e}}class ni{id;type="slack";limits={maxMessageChars:12000,idempotentSend:!1,minSendIntervalMs:1000,attachments:!0,voiceNotes:!0};#e;#n;#t;#r;#o;#i;#a;#s;#c;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??Wc,this.#i=e.apiBase??qc}async start(e){if(this.#s!==void 0)return;this.#a=e,this.#s=new AbortController,this.#c=this.#l(e,this.#s.signal)}async stop(){this.#s?.abort(),await this.#c?.catch(()=>{}),this.#s=void 0,this.#c=void 0,this.#a?.status("disconnected"),this.#a=void 0}async#l(e,t){let n=0,r=!1;while(!t.aborted)try{let i=await this.#u(t),o=await this.#d(e,i,t,()=>{if(n=0,!r)e.status("connected","Socket Mode");r=!0});if(t.aborted)return;if(o)continue;throw new At({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 s=i instanceof At?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",s.message),e.error(s)}let o=this.#o[Math.min(n,this.#o.length)-1]??30000;await Gc(o,t)}}async#u(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 At({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."})}#d(e,t,n,r){return new Promise((i)=>{let o=this.#r(t),s=!1,c=()=>o.close();n.addEventListener("abort",c,{once:!0}),o.addEventListener("message",(l)=>{let a;try{a=JSON.parse(String(l.data))}catch{return}if(a.envelope_id!==void 0)o.send(JSON.stringify({envelope_id:a.envelope_id}));if(a.type==="hello")s=!0,r();else if(a.type==="disconnect")o.close();else if(a.type==="events_api"&&a.payload?.event){let p=a.payload.event,f=a.payload.authorizations?.[0]?.user_id,d=Kc(p,f),u=ei(p),m=u?.url_private_download;if(d===void 0)return;let g=ti(p).map((y)=>({...y.size===void 0?{}:{sizeBytes:y.size},fetch:(w)=>this.#h(y.url_private_download??"",w)}));e.receive({...d,...g.length===0?{}:{images:g},...u===void 0||m===void 0?{}:{audio:{mimeType:u.mimetype??"audio/webm",...u.duration_ms===void 0?{}:{durationS:u.duration_ms/1000},...u.size===void 0?{}:{sizeBytes:u.size},fetch:(y)=>this.#h(m,y)}}})}}),o.addEventListener("close",()=>{n.removeEventListener("abort",c),i(s)})})}async send(e,t){try{if(e.attachment!==void 0)return await this.#f(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 lt)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#f(e,t){let n=e.attachment,r=await Uc(n.path),i=zc(n.path),o=await this.#p("files.getUploadURLExternal",new URLSearchParams({filename:i,length:String(r.byteLength)}),t),{upload_url:s,file_id:c}=o;if(typeof s!=="string"||typeof c!=="string")throw new lt(200,"no_upload_url",void 0);let l=await this.#t(s,{method:"POST",headers:{"content-type":n.mimeType},body:r,...t===void 0?{}:{signal:t}});if(!l.ok)throw new lt(l.status,`upload_${l.status}`,void 0);return await this.#p("files.completeUploadExternal",{files:[{id:c,title:i}],channel_id:e.recipient,...e.thread===void 0?{}:{thread_ts:e.thread},...e.text===""?{}:{initial_comment:e.text}},t),{ok:!0,providerMessageId:c}}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 o=Number(r.headers.get("retry-after"));throw new lt(r.status,typeof i.error==="string"?i.error:`HTTP ${r.status}`,Number.isFinite(o)&&o>0?o*1000:void 0)}async#h(e,t){let n=Jc(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 Jc(e){try{let t=new URL(e);if(`${t.protocol}//${t.host}/`!==Zc)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 lt 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||Hc.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:Vc[this.code]??"Slack's own error code is above. Rate limits and server errors are retried; anything else is not."}}}}var Hc=new Set(["ratelimited","internal_error","fatal_error","service_unavailable","request_timeout"]),Vc={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 Gc(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}function Qr(e,t,n,r,i){let o=e.config[t],s=typeof o==="string"&&o!==""?o:n,c=e.env[s],l=`channels[${e.id}].${t}`;if(c===void 0||c==="")throw new h({code:"slack_token_missing",message:`Channel "${e.id}" needs ${s}, which is not set.`,hint:`Put the ${i} in ${s}, in the environment or the .env beside the manifest. The agent starts either way, with this channel reported broken.`,field:l});if(!c.startsWith(r))throw new h({code:"slack_token_wrong_kind",message:`${s} 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:l});return c}var En=(e)=>new ni({id:e.id,appToken:Qr(e,"appTokenEnv","SLACK_APP_TOKEN","xapp-","app-level token"),botToken:Qr(e,"botTokenEnv","SLACK_BOT_TOKEN","xoxb-","bot token")}),Yc="0.1.0",ri={name:"channel-slack",version:Yc,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",En)}};import{createPublicKey as Xc,verify as Qc}from"node:crypto";import{mkdirSync as rl,readFileSync as il,renameSync as sl,writeFileSync as ol}from"node:fs";import{dirname as al,join as cl}from"node:path";var el="https://login.botframework.com/v1/.well-known/openidconfiguration",tl="https://api.botframework.com",ii=300,nl=86400000;class he extends Error{}function si(e){return JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}class ci{#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 he("no bearer token");let[r,i,o]=n.split(".");if(r===void 0||i===void 0||o===void 0)throw new he("malformed token");let s,c;try{s=si(r),c=si(i)}catch{throw new he("unreadable token")}if(s.alg!=="RS256")throw new he(`unexpected algorithm ${String(s.alg)}`);let l=await this.#i(String(s.kid??""));if(l===void 0)throw new he("signed by a key the connector does not publish");if(l.endorsements!==void 0&&t.channelId!==void 0&&!l.endorsements.includes(t.channelId))throw new he(`key not endorsed for channel ${t.channelId}`);if(!Qc("RSA-SHA256",Buffer.from(`${r}.${i}`),Xc({key:{kty:l.kty??"RSA",n:l.n??"",e:l.e??""},format:"jwk"}),Buffer.from(o,"base64url")))throw new he("bad signature");let p=this.#t()/1000;if(c.iss!==tl)throw new he(`issuer ${String(c.iss)}`);if(c.aud!==this.#e.appId)throw new he("token is for another bot");if(typeof c.exp!=="number"||c.exp<p-ii)throw new he("token expired");if(typeof c.nbf==="number"&&c.nbf>p+ii)throw new he("token not yet valid");if(typeof c.serviceUrl!=="string"||c.serviceUrl!==t.serviceUrl)throw new he("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 On(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<nl?this.#r?.keys.find((o)=>o.kid===e):void 0;if(n!==void 0)return n;let r=await(await this.#n(el)).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((o)=>o.kid===e)}}class On extends Error{status;constructor(e,t){super(t);this.status=e}}var oi={m4a:"audio/mp4",mp4:"audio/mp4",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"audio/webm",aac:"audio/aac"};function li(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&&oi[n]!==void 0)return{url:r,mimeType:oi[n],signed:!0};if(t.contentType.startsWith("audio/")&&t.contentUrl!==void 0)return{url:t.contentUrl,mimeType:t.contentType,signed:!1}}return}var ll=new Set(["png","jpg","jpeg","gif","webp"]);function ui(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&&ll.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 ul={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"};function dl(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)=>ul[r]??r).replace(/\s+/g," ").trim()}function fl(e){let t=e.recipient?.id;return(e.entities??[]).some((n)=>n.type==="mention"&&n.mentioned?.id===t)}function hl(e){return e.channelData?.tenant?.id??e.conversation?.tenantId}function pl(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"&&!fl(e))return;let n=dl(e);if(n===""&&li(e)===void 0&&ui(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 di{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=cl(e.dir,re.stateDir,`teams-${e.id}.json`),this.#a=ml(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(s){if(s instanceof he)return{status:401,detail:s.message};return this.#i?.status("error",`cannot verify activities: ${String(s)}`),{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&&hl(t)!==this.#n)return{status:200,detail:"other tenant"};if(t.serviceUrl?.startsWith("https://")===!0&&t.conversation!==void 0)this.#l(t.conversation.id,t.serviceUrl);let r=pl(t);if(r===void 0)return{status:200};let i=li(t),o=ui(t).map((s)=>({fetch:(c)=>this.#c(s.url,s.signed,c)}));return n.receive({...r,...o.length===0?{}:{images:o},...i===void 0?{}:{audio:{mimeType:i.mimeType,fetch:(s)=>this.#c(i.url,i.signed,s)}}}),{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(a){let p=a instanceof On?a.status:0;return{ok:!1,retryable:p===0||p>=500,error:{code:"teams_token_refused",message:`Entra ID did not issue the bot a token: ${a instanceof Error?a.message:String(a)}`,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 o=`${r.replace(/\/?$/,"/")}v3/conversations/${encodeURIComponent(e)}/activities`,s;try{s=await this.#t(o,{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify(t),...n===void 0?{}:{signal:n}})}catch(a){return{ok:!1,retryable:!0,error:{code:"teams_unreachable",message:`Cannot reach ${r}: ${a instanceof Error?a.message:String(a)}`,hint:"Allow outbound HTTPS to smba.trafficmanager.net (the Teams service URLs) and login.microsoftonline.com. Retried."}}}if(s.ok){let a=await s.json().catch(()=>({}));return{ok:!0,...a.id===void 0?{}:{providerMessageId:a.id}}}let c=(await s.text().catch(()=>"")).slice(0,300),l=Number(s.headers.get("retry-after"));return{ok:!1,retryable:s.status===429||s.status>=500,...Number.isFinite(l)&&l>0?{retryAfterMs:l*1000}:{},error:{code:"teams_send_failed",message:`Teams refused the reply (${s.status}): ${c}`,hint:s.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#c(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())}#l(e,t){if(this.#a[e]===t)return;this.#a={...this.#a,[e]:t},rl(al(this.#o),{recursive:!0});let n=`${this.#o}.partial`;ol(n,`${JSON.stringify(this.#a,null,2)}
|
|
8
|
-
`),sl(n,this.#o)}}function ml(e){try{let t=JSON.parse(il(e,"utf8"));if(typeof t!=="object"||t===null)return{};return Object.fromEntries(Object.entries(t).filter((n)=>typeof n[1]==="string"))}catch{return{}}}var ai=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function An(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var Nn=(e)=>{let t=(s)=>`channels[${e.id}].${s}`,n=An(e.config,"appId");if(n===void 0||!ai.test(n))throw new h({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=An(e.config,"passwordEnv")??"TEAMS_APP_PASSWORD",i=e.env[r];if(i===void 0||i==="")throw new h({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 o=An(e.config,"tenantId");if(o!==void 0&&!ai.test(o))throw new h({code:"teams_tenant_invalid",message:`Channel "${e.id}" declares tenantId "${o}", 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 di({id:e.id,agentId:e.agentId,dir:e.dir,auth:new ci({appId:n,password:i,...o===void 0?{}:{tenantId:o}}),...o===void 0?{}:{tenantId:o}})},gl="0.1.0",fi={name:"channel-teams",version:gl,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",Nn)}};import{readFile as hi}from"node:fs/promises";import{basename as pi}from"node:path";class Ne 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 yl="https://api.telegram.org";class Pn{#e;#n;#t;constructor(e){this.#e=e.token,this.#n=e.fetch??((t,n)=>fetch(t,n)),this.#t=io(e.baseUrl??yl)}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(o){throw new Ne({message:`Telegram ${e} did not complete: ${o instanceof Error?o.message:String(o)}`,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 wl(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 Ne({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 wl(e,t,n){let r=n.description??`HTTP ${t}`,i=n.error_code??t,o=n.parameters?.retry_after;if(i===429)return new Ne({message:`Telegram rate-limited ${e}: ${r}`,status:i,retryable:!0,...o===void 0?{}:{retryAfterMs:o*1000},detail:{code:"telegram_rate_limited",message:`Telegram rate-limited ${e}.`,hint:o===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 ${o}s. The outbox honours that verbatim rather than applying its own backoff.`}});if(i===401)return new Ne({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 Ne({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 Ne({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 s=i===400||i===403;return new Ne({message:`Telegram refused ${e}: ${r}`,status:i,retryable:!s,detail:{code:s?"telegram_refused":"telegram_error",message:`Telegram refused ${e}: ${r}`,hint:s?"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 vl=4096,bl=30,mi=[1000,2000,5000,15000,30000],_l=350;class yi{id;type="telegram";limits={maxMessageChars:vl,idempotentSend:!1,minSendIntervalMs:_l,attachments:!0,voiceNotes:!0};#e;#n;#t;#r;#o;#i=0;#a=!1;#s;#c;constructor(e){this.id=e.id,this.#e=e.api??new Pn({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(In(n,`registering the webhook for channel "${this.id}"`))}return}this.#c=this.#l(e,this.#s.signal)}async stop(){if(!this.#a)return;this.#a=!1,this.#s?.abort(),await this.#c?.catch(()=>{}),this.#c=void 0,this.#o?.status("disconnected"),this.#o=void 0}async send(e,t){let n=gi(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 hi(r.path)],{type:"audio/ogg"}),filename:pi(r.path),...n===void 0?{}:{threadId:n}},t):await this.#e.sendPhoto({chatId:e.recipient,photo:new Blob([await hi(r.path)],{type:r.mimeType}),filename:pi(r.path),caption:e.text,...n===void 0?{}:{threadId:n}},t);return{ok:!0,providerMessageId:String(i.message_id)}}catch(r){if(r instanceof Ne)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=gi(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(!Tl(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.#u(t,n),{status:200}}async#l(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(In(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:bl},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 o of i)this.#i=Math.max(this.#i,o.update_id+1),this.#u(e,o)}catch(i){if(t.aborted)return;let o=mi[Math.min(n,mi.length-1)]??1000;if(n+=1,n===1||n%8===0)e.status("error",i instanceof Error?i.message:String(i)),e.error(In(i,`polling channel "${this.id}"`));await $l(o,t)}}#u(e,t){let n=t.message;if(n===void 0)return;let r=n.text??n.caption??"",i=n.voice??n.audio,o=kl(n);if(r.trim()===""&&i===void 0&&o===void 0)return;if(n.from?.is_bot===!0)return;let s=Sl(n,r),c=o===void 0?[]:[{...o.file_size===void 0?{}:{sizeBytes:o.file_size},fetch:(l)=>this.#d(o.file_id,"photo",l)}];e.receive({...s,...c.length===0?{}:{images:c},...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:(l)=>this.#d(i.file_id,"voice note",l)}}})}async#d(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 kl(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 Sl(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 gi(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function In(e,t){if(e instanceof Ne)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 Tl(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 $l(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}var Mn=(e)=>{let t=e.config,n=ut(t,"tokenEnv")??"TELEGRAM_BOT_TOKEN",r=e.env[n];if(r===void 0||r==="")throw new h({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=ut(t,"mode")??"longpoll";if(i!=="longpoll"&&i!=="webhook")throw new h({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 o=ut(t,"secretTokenEnv"),s=o===void 0?void 0:e.env[o];if(o!==void 0&&(s===void 0||s===""))throw new h({code:"telegram_secret_missing",message:`Channel "${e.id}" names secretTokenEnv ${o}, which is not set.`,hint:`Export ${o} 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 c=ut(t,"apiBaseUrl"),l=ut(t,"webhookUrl");return new yi({id:e.id,token:r,mode:i,...l===void 0?{}:{webhookUrl:l},...s===void 0||s===""?{}:{secretToken:s},...c===void 0?{}:{api:new Pn({token:r,baseUrl:c})}})};function ut(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var El="0.1.0",wi={name:"telegram",version:El,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["api.telegram.org"]},{kind:"env",vars:["TELEGRAM_BOT_TOKEN"]}],setup(e){e.defineChannel("telegram",Mn)}};import{createRequire as Al}from"node:module";import{isAbsolute as Gl,resolve as Yl}from"node:path";import{appendFile as Ki,mkdir as fm,readFile as hm}from"node:fs/promises";import{join as qi}from"node:path";import{appendFile as lo,mkdir as pm,readFile as mm,writeFile as gm}from"node:fs/promises";import{join as ym}from"node:path";import{chmodSync as Hi,mkdirSync as yg,readdirSync as wg,rmSync as vg}from"node:fs";import{readFile as Vi}from"node:fs/promises";import{join as bg}from"node:path";var C=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Wt=Al(import.meta.url),F=C(function(e){var t=Symbol.for("yaml.alias"),n=Symbol.for("yaml.document"),r=Symbol.for("yaml.map"),i=Symbol.for("yaml.pair"),o=Symbol.for("yaml.scalar"),s=Symbol.for("yaml.seq"),c=Symbol.for("yaml.node.type"),l=(w)=>!!w&&typeof w==="object"&&w[c]===t,a=(w)=>!!w&&typeof w==="object"&&w[c]===n,p=(w)=>!!w&&typeof w==="object"&&w[c]===r,f=(w)=>!!w&&typeof w==="object"&&w[c]===i,d=(w)=>!!w&&typeof w==="object"&&w[c]===o,u=(w)=>!!w&&typeof w==="object"&&w[c]===s;function m(w){if(w&&typeof w==="object")switch(w[c]){case r:case s:return!0}return!1}function g(w){if(w&&typeof w==="object")switch(w[c]){case t:case r:case o:case s:return!0}return!1}var y=(w)=>(d(w)||m(w))&&!!w.anchor;e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=c,e.PAIR=i,e.SCALAR=o,e.SEQ=s,e.hasAnchor=y,e.isAlias=l,e.isCollection=m,e.isDocument=a,e.isMap=p,e.isNode=g,e.isPair=f,e.isScalar=d,e.isSeq=u}),Jt=C(function(e){var t=F(),n=Symbol("break visit"),r=Symbol("skip children"),i=Symbol("remove node");function o(d,u){let m=a(u);if(t.isDocument(d)){if(s(null,d.contents,m,Object.freeze([d]))===i)d.contents=null}else s(null,d,m,Object.freeze([]))}o.BREAK=n,o.SKIP=r,o.REMOVE=i;function s(d,u,m,g){let y=p(d,u,m,g);if(t.isNode(y)||t.isPair(y))return f(d,g,y),s(d,y,m,g);if(typeof y!=="symbol"){if(t.isCollection(u)){g=Object.freeze(g.concat(u));for(let w=0;w<u.items.length;++w){let v=s(w,u.items[w],m,g);if(typeof v==="number")w=v-1;else if(v===n)return n;else if(v===i)u.items.splice(w,1),w-=1}}else if(t.isPair(u)){g=Object.freeze(g.concat(u));let w=s("key",u.key,m,g);if(w===n)return n;else if(w===i)u.key=null;let v=s("value",u.value,m,g);if(v===n)return n;else if(v===i)u.value=null}}return y}async function c(d,u){let m=a(u);if(t.isDocument(d)){if(await l(null,d.contents,m,Object.freeze([d]))===i)d.contents=null}else await l(null,d,m,Object.freeze([]))}c.BREAK=n,c.SKIP=r,c.REMOVE=i;async function l(d,u,m,g){let y=await p(d,u,m,g);if(t.isNode(y)||t.isPair(y))return f(d,g,y),l(d,y,m,g);if(typeof y!=="symbol"){if(t.isCollection(u)){g=Object.freeze(g.concat(u));for(let w=0;w<u.items.length;++w){let v=await l(w,u.items[w],m,g);if(typeof v==="number")w=v-1;else if(v===n)return n;else if(v===i)u.items.splice(w,1),w-=1}}else if(t.isPair(u)){g=Object.freeze(g.concat(u));let w=await l("key",u.key,m,g);if(w===n)return n;else if(w===i)u.key=null;let v=await l("value",u.value,m,g);if(v===n)return n;else if(v===i)u.value=null}}return y}function a(d){if(typeof d==="object"&&(d.Collection||d.Node||d.Value))return Object.assign({Alias:d.Node,Map:d.Node,Scalar:d.Node,Seq:d.Node},d.Value&&{Map:d.Value,Scalar:d.Value,Seq:d.Value},d.Collection&&{Map:d.Collection,Seq:d.Collection},d);return d}function p(d,u,m,g){if(typeof m==="function")return m(d,u,g);if(t.isMap(u))return m.Map?.(d,u,g);if(t.isSeq(u))return m.Seq?.(d,u,g);if(t.isPair(u))return m.Pair?.(d,u,g);if(t.isScalar(u))return m.Scalar?.(d,u,g);if(t.isAlias(u))return m.Alias?.(d,u,g);return}function f(d,u,m){let g=u[u.length-1];if(t.isCollection(g))g.items[d]=m;else if(t.isPair(g))if(d==="key")g.key=m;else g.value=m;else if(t.isDocument(g))g.contents=m;else{let y=t.isAlias(g)?"alias":"scalar";throw Error(`Cannot replace node with ${y} parent`)}}e.visit=o,e.visitAsync=c}),ns=C(function(e){var t=F(),n=Jt(),r={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},i=(s)=>s.replace(/[!,[\]{}]/g,(c)=>r[c]);class o{constructor(s,c){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},o.defaultYaml,s),this.tags=Object.assign({},o.defaultTags,c)}clone(){let s=new o(this.yaml,this.tags);return s.docStart=this.docStart,s}atDocument(){let s=new o(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:o.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},o.defaultTags);break}return s}add(s,c){if(this.atNextDocument)this.yaml={explicit:o.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},o.defaultTags),this.atNextDocument=!1;let l=s.trim().split(/[ \t]+/),a=l.shift();switch(a){case"%TAG":{if(l.length!==2){if(c(0,"%TAG directive should contain exactly two parts"),l.length<2)return!1}let[p,f]=l;return this.tags[p]=f,!0}case"%YAML":{if(this.yaml.explicit=!0,l.length!==1)return c(0,"%YAML directive should contain exactly one part"),!1;let[p]=l;if(p==="1.1"||p==="1.2")return this.yaml.version=p,!0;else{let f=/^\d+\.\d+$/.test(p);return c(6,`Unsupported YAML version ${p}`,f),!1}}default:return c(0,`Unknown directive ${a}`,!0),!1}}tagName(s,c){if(s==="!")return"!";if(s[0]!=="!")return c(`Not a valid tag: ${s}`),null;if(s[1]==="<"){let f=s.slice(2,-1);if(f==="!"||f==="!!")return c(`Verbatim tags aren't resolved, so ${s} is invalid.`),null;if(s[s.length-1]!==">")c("Verbatim tags must end with a >");return f}let[,l,a]=s.match(/^(.*!)([^!]*)$/s);if(!a)c(`The ${s} tag has no suffix`);let p=this.tags[l];if(p)try{return p+decodeURIComponent(a)}catch(f){return c(String(f)),null}if(l==="!")return s;return c(`Could not resolve tag: ${s}`),null}tagString(s){for(let[c,l]of Object.entries(this.tags))if(s.startsWith(l))return c+i(s.substring(l.length));return s[0]==="!"?s:`!<${s}>`}toString(s){let c=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],l=Object.entries(this.tags),a;if(s&&l.length>0&&t.isNode(s.contents)){let p={};n.visit(s.contents,(f,d)=>{if(t.isNode(d)&&d.tag)p[d.tag]=!0}),a=Object.keys(p)}else a=[];for(let[p,f]of l){if(p==="!!"&&f==="tag:yaml.org,2002:")continue;if(!s||a.some((d)=>d.startsWith(f)))c.push(`%TAG ${p} ${f}`)}return c.join(`
|
|
9
|
-
`)}}o.defaultYaml={explicit:!1,version:"1.2"},o.defaultTags={"!!":"tag:yaml.org,2002:"},e.Directives=o}),Wn=
|
|
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 Dc(e,t=fetch){let n=e.peers.filter((i)=>i.url!==void 0),r=new Map;return(i)=>{let o={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((s)=>s.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((s)=>s.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(s,c){let l=n.find((g)=>g.name===s.peer);if(l?.url===void 0)throw new te({code:"a2a_peer_unknown",message:`No peer "${String(s.peer)}" to send to.`,hint:`The peers this agent may call are: ${n.map((g)=>g.name).join(", ")||"none"}. Another needs a url in the plugin's peers.`});let a=l.tokenEnv===void 0?void 0:i.env[l.tokenEnv];if(l.tokenEnv!==void 0&&(a===void 0||a===""))throw new te({code:"a2a_peer_token_missing",message:`Peer ${l.name} needs ${l.tokenEnv}, which is not set.`,hint:`Put the key ${l.name} issued to this agent in ${l.tokenEnv}, in the .env beside the manifest.`});let p=`${c.sessionKey}\x1F${l.name}`,f=AbortSignal.timeout(Math.max(1000,Math.min(60000,c.deadlineMs-5000))),d;try{d=await t(l.url,{method:"POST",headers:{"content-type":"application/json","a2a-version":Et,...a===void 0?{}:{authorization:`Bearer ${a}`}},body:JSON.stringify({jsonrpc:"2.0",id:Wr(),method:"SendMessage",params:{message:{messageId:Wr(),role:"ROLE_USER",parts:[{text:String(s.text??"")}],...r.has(p)?{contextId:r.get(p)}:{}}}}),signal:AbortSignal.any([c.signal,f])})}catch(g){throw new te({code:"a2a_peer_unreachable",message:`Peer ${l.name} did not answer: ${g instanceof Error?g.message:String(g)}`,hint:`Check ${l.url} is reachable from this runtime; a timeout is 60 seconds at most.`})}let u=await d.json().catch(()=>({}));if(u.error!==void 0||!d.ok)throw new te({code:"a2a_peer_refused",message:`Peer ${l.name} refused: ${u.error?.message??`HTTP ${d.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 m=u.result?.task?.contextId??u.result?.message?.contextId;if(typeof m==="string")r.set(p,m);return xc(u.result)}};return{id:"a2a",resolve:async(s)=>s.includes("a2a_send")?[o]:[]}}}var Pe=(e)=>typeof e==="string"&&e.trim()!==""?e.trim():void 0,En=(e,t,n)=>{if(e===void 0)return t;if(typeof e==="number"&&Number.isInteger(e)&&e>0)return e;throw Ye(`${n} must be a positive whole number.`,n)};function Ye(e,t){return new h({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 jc(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(([l,a])=>{if(!/^[a-z0-9][a-z0-9-]*$/.test(l))throw Ye(`Peer "${l}" needs a lowercase slug name; it becomes part of a session key.`,`peers.${l}`);let p=typeof a==="object"&&a!==null?a:{},f=Pe(p.key),d=Pe(p.url),u=Pe(p.tokenEnv);if(f===void 0&&d===void 0)throw Ye(`Peer "${l}" names neither a key (inbound) nor a url (outbound).`,`peers.${l}`);if(d!==void 0&&!/^https?:\/\//.test(d))throw Ye(`Peer "${l}"'s url must be absolute http(s).`,`peers.${l}.url`);return{name:l,...f===void 0?{}:{key:f},...d===void 0?{}:{url:d},...u===void 0?{}:{tokenEnv:u},ratePerMinute:En(p.ratePerMinute,30,`peers.${l}.ratePerMinute`),maxChars:En(p.maxChars,20000,`peers.${l}.maxChars`)}}),o=i.flatMap((l)=>l.key===void 0?[]:[l.key]);if(new Set(o).size!==o.length)throw Ye("Two peers name the same key; a key identifies exactly one peer.","peers");let s=Array.isArray(n.skills)?n.skills:[],c=Pe(t.publicUrl);return{card:{name:Pe(n.name)??"Agent",description:Pe(n.description)??"",skills:s.map((l,a)=>{let p=typeof l==="object"&&l!==null?l:{},f=Pe(p.id);if(f===void 0)throw Ye("A card skill needs an id.",`card.skills.${a}`);return{id:f,name:Pe(p.name)??f,description:Pe(p.description)??"",tags:Array.isArray(p.tags)?p.tags.map(String):[]}})},peers:i,...c===void 0?{}:{publicUrl:c},waitMs:En(t.waitMs,60000,"waitMs")}}var Uc="0.1.0",Gr={name:"a2a",version:Uc,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["*"]}],setup(e){let t=jc(e.config),n=new Vr(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",Dc(t)),e.events.on("turn.end",(r)=>n.observe(r))}};import{readFile as zc}from"node:fs/promises";import{basename as Fc}from"node:path";function Xr(e){return e.files?.find((t)=>t.url_private_download!==void 0&&(t.subtype==="slack_audio"||t.mimetype?.startsWith("audio/")===!0))}function ei(e){return(e.files??[]).filter((t)=>t.url_private_download!==void 0&&t.mimetype?.startsWith("image/")===!0)}var Bc={"&":"&","<":"<",">":">"};function Kc(e,t){return(t===void 0?e.replace(/^\s*<@[A-Z0-9]+>/,""):e.replaceAll(`<@${t}>`,"")).replace(/&(amp|lt|gt);/g,(r)=>Bc[r]??r).replace(/\s+/g," ").trim()}function qc(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=Kc(e.text??"",t);if(r===""&&Xr(e)===void 0&&ei(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 Zc="https://slack.com/api/",Wc="https://files.slack.com/",Jc=[1000,2000,5000,15000,30000];class At extends Error{detail;constructor(e){super(e.message);this.detail=e}}class ni{id;type="slack";limits={maxMessageChars:12000,idempotentSend:!1,minSendIntervalMs:1000,attachments:!0,voiceNotes:!0};#e;#n;#t;#r;#o;#i;#a;#s;#c;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??Jc,this.#i=e.apiBase??Zc}async start(e){if(this.#s!==void 0)return;this.#a=e,this.#s=new AbortController,this.#c=this.#l(e,this.#s.signal)}async stop(){this.#s?.abort(),await this.#c?.catch(()=>{}),this.#s=void 0,this.#c=void 0,this.#a?.status("disconnected"),this.#a=void 0}async#l(e,t){let n=0,r=!1;while(!t.aborted)try{let i=await this.#u(t),o=await this.#d(e,i,t,()=>{if(n=0,!r)e.status("connected","Socket Mode");r=!0});if(t.aborted)return;if(o)continue;throw new At({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 s=i instanceof At?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",s.message),e.error(s)}let o=this.#o[Math.min(n,this.#o.length)-1]??30000;await Yc(o,t)}}async#u(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 At({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."})}#d(e,t,n,r){return new Promise((i)=>{let o=this.#r(t),s=!1,c=()=>o.close();n.addEventListener("abort",c,{once:!0}),o.addEventListener("message",(l)=>{let a;try{a=JSON.parse(String(l.data))}catch{return}if(a.envelope_id!==void 0)o.send(JSON.stringify({envelope_id:a.envelope_id}));if(a.type==="hello")s=!0,r();else if(a.type==="disconnect")o.close();else if(a.type==="events_api"&&a.payload?.event){let p=a.payload.event,f=a.payload.authorizations?.[0]?.user_id,d=qc(p,f),u=Xr(p),m=u?.url_private_download;if(d===void 0)return;let g=ei(p).map((y)=>({...y.size===void 0?{}:{sizeBytes:y.size},fetch:(w)=>this.#h(y.url_private_download??"",w)}));e.receive({...d,...g.length===0?{}:{images:g},...u===void 0||m===void 0?{}:{audio:{mimeType:u.mimetype??"audio/webm",...u.duration_ms===void 0?{}:{durationS:u.duration_ms/1000},...u.size===void 0?{}:{sizeBytes:u.size},fetch:(y)=>this.#h(m,y)}}})}}),o.addEventListener("close",()=>{n.removeEventListener("abort",c),i(s)})})}async send(e,t){try{if(e.attachment!==void 0)return await this.#f(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 lt)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#f(e,t){let n=e.attachment,r=await zc(n.path),i=Fc(n.path),o=await this.#p("files.getUploadURLExternal",new URLSearchParams({filename:i,length:String(r.byteLength)}),t),{upload_url:s,file_id:c}=o;if(typeof s!=="string"||typeof c!=="string")throw new lt(200,"no_upload_url",void 0);let l=await this.#t(s,{method:"POST",headers:{"content-type":n.mimeType},body:r,...t===void 0?{}:{signal:t}});if(!l.ok)throw new lt(l.status,`upload_${l.status}`,void 0);return await this.#p("files.completeUploadExternal",{files:[{id:c,title:i}],channel_id:e.recipient,...e.thread===void 0?{}:{thread_ts:e.thread},...e.text===""?{}:{initial_comment:e.text}},t),{ok:!0,providerMessageId:c}}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 o=Number(r.headers.get("retry-after"));throw new lt(r.status,typeof i.error==="string"?i.error:`HTTP ${r.status}`,Number.isFinite(o)&&o>0?o*1000:void 0)}async#h(e,t){let n=Hc(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 Hc(e){try{let t=new URL(e);if(`${t.protocol}//${t.host}/`!==Wc)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 lt 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||Vc.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:Gc[this.code]??"Slack's own error code is above. Rate limits and server errors are retried; anything else is not."}}}}var Vc=new Set(["ratelimited","internal_error","fatal_error","service_unavailable","request_timeout"]),Gc={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 Yc(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}function Yr(e,t,n,r,i){let o=e.config[t],s=typeof o==="string"&&o!==""?o:n,c=e.env[s],l=`channels[${e.id}].${t}`;if(c===void 0||c==="")throw new h({code:"slack_token_missing",message:`Channel "${e.id}" needs ${s}, which is not set.`,hint:`Put the ${i} in ${s}, in the environment or the .env beside the manifest. The agent starts either way, with this channel reported broken.`,field:l});if(!c.startsWith(r))throw new h({code:"slack_token_wrong_kind",message:`${s} 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:l});return c}var An=(e)=>new ni({id:e.id,appToken:Yr(e,"appTokenEnv","SLACK_APP_TOKEN","xapp-","app-level token"),botToken:Yr(e,"botTokenEnv","SLACK_BOT_TOKEN","xoxb-","bot token")}),Xc="0.1.0",ri={name:"channel-slack",version:Xc,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",An)}};import{createPublicKey as Qc,verify as el}from"node:crypto";import{mkdirSync as il,readFileSync as sl,renameSync as ol,writeFileSync as al}from"node:fs";import{dirname as cl,join as ll}from"node:path";var tl="https://login.botframework.com/v1/.well-known/openidconfiguration",nl="https://api.botframework.com",ii=300,rl=86400000;class me extends Error{}function si(e){return JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}class ci{#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 me("no bearer token");let[r,i,o]=n.split(".");if(r===void 0||i===void 0||o===void 0)throw new me("malformed token");let s,c;try{s=si(r),c=si(i)}catch{throw new me("unreadable token")}if(s.alg!=="RS256")throw new me(`unexpected algorithm ${String(s.alg)}`);let l=await this.#i(String(s.kid??""));if(l===void 0)throw new me("signed by a key the connector does not publish");if(l.endorsements!==void 0&&t.channelId!==void 0&&!l.endorsements.includes(t.channelId))throw new me(`key not endorsed for channel ${t.channelId}`);if(!el("RSA-SHA256",Buffer.from(`${r}.${i}`),Qc({key:{kty:l.kty??"RSA",n:l.n??"",e:l.e??""},format:"jwk"}),Buffer.from(o,"base64url")))throw new me("bad signature");let p=this.#t()/1000;if(c.iss!==nl)throw new me(`issuer ${String(c.iss)}`);if(c.aud!==this.#e.appId)throw new me("token is for another bot");if(typeof c.exp!=="number"||c.exp<p-ii)throw new me("token expired");if(typeof c.nbf==="number"&&c.nbf>p+ii)throw new me("token not yet valid");if(typeof c.serviceUrl!=="string"||c.serviceUrl!==t.serviceUrl)throw new me("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 Nn(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<rl?this.#r?.keys.find((o)=>o.kid===e):void 0;if(n!==void 0)return n;let r=await(await this.#n(tl)).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((o)=>o.kid===e)}}class Nn extends Error{status;constructor(e,t){super(t);this.status=e}}var oi={m4a:"audio/mp4",mp4:"audio/mp4",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"audio/webm",aac:"audio/aac"};function li(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&&oi[n]!==void 0)return{url:r,mimeType:oi[n],signed:!0};if(t.contentType.startsWith("audio/")&&t.contentUrl!==void 0)return{url:t.contentUrl,mimeType:t.contentType,signed:!1}}return}var ul=new Set(["png","jpg","jpeg","gif","webp"]);function ui(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&&ul.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 dl={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"};function fl(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)=>dl[r]??r).replace(/\s+/g," ").trim()}function hl(e){let t=e.recipient?.id;return(e.entities??[]).some((n)=>n.type==="mention"&&n.mentioned?.id===t)}function pl(e){return e.channelData?.tenant?.id??e.conversation?.tenantId}function ml(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"&&!hl(e))return;let n=fl(e);if(n===""&&li(e)===void 0&&ui(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 di{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=ll(e.dir,se.stateDir,`teams-${e.id}.json`),this.#a=gl(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(s){if(s instanceof me)return{status:401,detail:s.message};return this.#i?.status("error",`cannot verify activities: ${String(s)}`),{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&&pl(t)!==this.#n)return{status:200,detail:"other tenant"};if(t.serviceUrl?.startsWith("https://")===!0&&t.conversation!==void 0)this.#l(t.conversation.id,t.serviceUrl);let r=ml(t);if(r===void 0)return{status:200};let i=li(t),o=ui(t).map((s)=>({fetch:(c)=>this.#c(s.url,s.signed,c)}));return n.receive({...r,...o.length===0?{}:{images:o},...i===void 0?{}:{audio:{mimeType:i.mimeType,fetch:(s)=>this.#c(i.url,i.signed,s)}}}),{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(a){let p=a instanceof Nn?a.status:0;return{ok:!1,retryable:p===0||p>=500,error:{code:"teams_token_refused",message:`Entra ID did not issue the bot a token: ${a instanceof Error?a.message:String(a)}`,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 o=`${r.replace(/\/?$/,"/")}v3/conversations/${encodeURIComponent(e)}/activities`,s;try{s=await this.#t(o,{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify(t),...n===void 0?{}:{signal:n}})}catch(a){return{ok:!1,retryable:!0,error:{code:"teams_unreachable",message:`Cannot reach ${r}: ${a instanceof Error?a.message:String(a)}`,hint:"Allow outbound HTTPS to smba.trafficmanager.net (the Teams service URLs) and login.microsoftonline.com. Retried."}}}if(s.ok){let a=await s.json().catch(()=>({}));return{ok:!0,...a.id===void 0?{}:{providerMessageId:a.id}}}let c=(await s.text().catch(()=>"")).slice(0,300),l=Number(s.headers.get("retry-after"));return{ok:!1,retryable:s.status===429||s.status>=500,...Number.isFinite(l)&&l>0?{retryAfterMs:l*1000}:{},error:{code:"teams_send_failed",message:`Teams refused the reply (${s.status}): ${c}`,hint:s.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#c(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())}#l(e,t){if(this.#a[e]===t)return;this.#a={...this.#a,[e]:t},il(cl(this.#o),{recursive:!0});let n=`${this.#o}.partial`;al(n,`${JSON.stringify(this.#a,null,2)}
|
|
8
|
+
`),ol(n,this.#o)}}function gl(e){try{let t=JSON.parse(sl(e,"utf8"));if(typeof t!=="object"||t===null)return{};return Object.fromEntries(Object.entries(t).filter((n)=>typeof n[1]==="string"))}catch{return{}}}var ai=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function On(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var In=(e)=>{let t=(s)=>`channels[${e.id}].${s}`,n=On(e.config,"appId");if(n===void 0||!ai.test(n))throw new h({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=On(e.config,"passwordEnv")??"TEAMS_APP_PASSWORD",i=e.env[r];if(i===void 0||i==="")throw new h({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 o=On(e.config,"tenantId");if(o!==void 0&&!ai.test(o))throw new h({code:"teams_tenant_invalid",message:`Channel "${e.id}" declares tenantId "${o}", 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 di({id:e.id,agentId:e.agentId,dir:e.dir,auth:new ci({appId:n,password:i,...o===void 0?{}:{tenantId:o}}),...o===void 0?{}:{tenantId:o}})},yl="0.1.0",fi={name:"channel-teams",version:yl,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",In)}};import{readFile as hi}from"node:fs/promises";import{basename as pi}from"node:path";class Ie 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 wl="https://api.telegram.org";class Pn{#e;#n;#t;constructor(e){this.#e=e.token,this.#n=e.fetch??((t,n)=>fetch(t,n)),this.#t=ao(e.baseUrl??wl)}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(o){throw new Ie({message:`Telegram ${e} did not complete: ${o instanceof Error?o.message:String(o)}`,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 vl(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 Ie({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 vl(e,t,n){let r=n.description??`HTTP ${t}`,i=n.error_code??t,o=n.parameters?.retry_after;if(i===429)return new Ie({message:`Telegram rate-limited ${e}: ${r}`,status:i,retryable:!0,...o===void 0?{}:{retryAfterMs:o*1000},detail:{code:"telegram_rate_limited",message:`Telegram rate-limited ${e}.`,hint:o===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 ${o}s. The outbox honours that verbatim rather than applying its own backoff.`}});if(i===401)return new Ie({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 Ie({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 Ie({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 s=i===400||i===403;return new Ie({message:`Telegram refused ${e}: ${r}`,status:i,retryable:!s,detail:{code:s?"telegram_refused":"telegram_error",message:`Telegram refused ${e}: ${r}`,hint:s?"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 bl=4096,_l=30,mi=[1000,2000,5000,15000,30000],kl=350;class yi{id;type="telegram";limits={maxMessageChars:bl,idempotentSend:!1,minSendIntervalMs:kl,attachments:!0,voiceNotes:!0};#e;#n;#t;#r;#o;#i=0;#a=!1;#s;#c;constructor(e){this.id=e.id,this.#e=e.api??new Pn({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(Cn(n,`registering the webhook for channel "${this.id}"`))}return}this.#c=this.#l(e,this.#s.signal)}async stop(){if(!this.#a)return;this.#a=!1,this.#s?.abort(),await this.#c?.catch(()=>{}),this.#c=void 0,this.#o?.status("disconnected"),this.#o=void 0}async send(e,t){let n=gi(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 hi(r.path)],{type:"audio/ogg"}),filename:pi(r.path),...n===void 0?{}:{threadId:n}},t):await this.#e.sendPhoto({chatId:e.recipient,photo:new Blob([await hi(r.path)],{type:r.mimeType}),filename:pi(r.path),caption:e.text,...n===void 0?{}:{threadId:n}},t);return{ok:!0,providerMessageId:String(i.message_id)}}catch(r){if(r instanceof Ie)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=gi(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(!$l(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.#u(t,n),{status:200}}async#l(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(Cn(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:_l},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 o of i)this.#i=Math.max(this.#i,o.update_id+1),this.#u(e,o)}catch(i){if(t.aborted)return;let o=mi[Math.min(n,mi.length-1)]??1000;if(n+=1,n===1||n%8===0)e.status("error",i instanceof Error?i.message:String(i)),e.error(Cn(i,`polling channel "${this.id}"`));await El(o,t)}}#u(e,t){let n=t.message;if(n===void 0)return;let r=n.text??n.caption??"",i=n.voice??n.audio,o=Sl(n);if(r.trim()===""&&i===void 0&&o===void 0)return;if(n.from?.is_bot===!0)return;let s=Tl(n,r),c=o===void 0?[]:[{...o.file_size===void 0?{}:{sizeBytes:o.file_size},fetch:(l)=>this.#d(o.file_id,"photo",l)}];e.receive({...s,...c.length===0?{}:{images:c},...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:(l)=>this.#d(i.file_id,"voice note",l)}}})}async#d(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 Sl(e){let t=e.photo??[];if(t.length>0)return t.findLast((r)=>(r.file_size??0)<=io)??t[0];let n=e.document;return n?.mime_type?.startsWith("image/")===!0?n:void 0}function Tl(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 gi(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function Cn(e,t){if(e instanceof Ie)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 $l(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 El(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}var Mn=(e)=>{let t=e.config,n=ut(t,"tokenEnv")??"TELEGRAM_BOT_TOKEN",r=e.env[n];if(r===void 0||r==="")throw new h({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=ut(t,"mode")??"longpoll";if(i!=="longpoll"&&i!=="webhook")throw new h({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 o=ut(t,"secretTokenEnv"),s=o===void 0?void 0:e.env[o];if(o!==void 0&&(s===void 0||s===""))throw new h({code:"telegram_secret_missing",message:`Channel "${e.id}" names secretTokenEnv ${o}, which is not set.`,hint:`Export ${o} 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 c=ut(t,"apiBaseUrl"),l=ut(t,"webhookUrl");return new yi({id:e.id,token:r,mode:i,...l===void 0?{}:{webhookUrl:l},...s===void 0||s===""?{}:{secretToken:s},...c===void 0?{}:{api:new Pn({token:r,baseUrl:c})}})};function ut(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var Al="0.1.0",wi={name:"telegram",version:Al,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["api.telegram.org"]},{kind:"env",vars:["TELEGRAM_BOT_TOKEN"]}],setup(e){e.defineChannel("telegram",Mn)}};import{createRequire as Ol}from"node:module";import{isAbsolute as Yl,resolve as Xl}from"node:path";import{appendFile as Ki,mkdir as hm,readFile as pm}from"node:fs/promises";import{join as qi}from"node:path";import{appendFile as co,mkdir as mm,readFile as gm,writeFile as ym}from"node:fs/promises";import{join as wm}from"node:path";import{chmodSync as Hi,mkdirSync as _g,readdirSync as kg,rmSync as Sg}from"node:fs";import{readFile as Vi}from"node:fs/promises";import{join as Tg}from"node:path";var P=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Wt=Ol(import.meta.url),B=P(function(e){var t=Symbol.for("yaml.alias"),n=Symbol.for("yaml.document"),r=Symbol.for("yaml.map"),i=Symbol.for("yaml.pair"),o=Symbol.for("yaml.scalar"),s=Symbol.for("yaml.seq"),c=Symbol.for("yaml.node.type"),l=(w)=>!!w&&typeof w==="object"&&w[c]===t,a=(w)=>!!w&&typeof w==="object"&&w[c]===n,p=(w)=>!!w&&typeof w==="object"&&w[c]===r,f=(w)=>!!w&&typeof w==="object"&&w[c]===i,d=(w)=>!!w&&typeof w==="object"&&w[c]===o,u=(w)=>!!w&&typeof w==="object"&&w[c]===s;function m(w){if(w&&typeof w==="object")switch(w[c]){case r:case s:return!0}return!1}function g(w){if(w&&typeof w==="object")switch(w[c]){case t:case r:case o:case s:return!0}return!1}var y=(w)=>(d(w)||m(w))&&!!w.anchor;e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=c,e.PAIR=i,e.SCALAR=o,e.SEQ=s,e.hasAnchor=y,e.isAlias=l,e.isCollection=m,e.isDocument=a,e.isMap=p,e.isNode=g,e.isPair=f,e.isScalar=d,e.isSeq=u}),Jt=P(function(e){var t=B(),n=Symbol("break visit"),r=Symbol("skip children"),i=Symbol("remove node");function o(d,u){let m=a(u);if(t.isDocument(d)){if(s(null,d.contents,m,Object.freeze([d]))===i)d.contents=null}else s(null,d,m,Object.freeze([]))}o.BREAK=n,o.SKIP=r,o.REMOVE=i;function s(d,u,m,g){let y=p(d,u,m,g);if(t.isNode(y)||t.isPair(y))return f(d,g,y),s(d,y,m,g);if(typeof y!=="symbol"){if(t.isCollection(u)){g=Object.freeze(g.concat(u));for(let w=0;w<u.items.length;++w){let v=s(w,u.items[w],m,g);if(typeof v==="number")w=v-1;else if(v===n)return n;else if(v===i)u.items.splice(w,1),w-=1}}else if(t.isPair(u)){g=Object.freeze(g.concat(u));let w=s("key",u.key,m,g);if(w===n)return n;else if(w===i)u.key=null;let v=s("value",u.value,m,g);if(v===n)return n;else if(v===i)u.value=null}}return y}async function c(d,u){let m=a(u);if(t.isDocument(d)){if(await l(null,d.contents,m,Object.freeze([d]))===i)d.contents=null}else await l(null,d,m,Object.freeze([]))}c.BREAK=n,c.SKIP=r,c.REMOVE=i;async function l(d,u,m,g){let y=await p(d,u,m,g);if(t.isNode(y)||t.isPair(y))return f(d,g,y),l(d,y,m,g);if(typeof y!=="symbol"){if(t.isCollection(u)){g=Object.freeze(g.concat(u));for(let w=0;w<u.items.length;++w){let v=await l(w,u.items[w],m,g);if(typeof v==="number")w=v-1;else if(v===n)return n;else if(v===i)u.items.splice(w,1),w-=1}}else if(t.isPair(u)){g=Object.freeze(g.concat(u));let w=await l("key",u.key,m,g);if(w===n)return n;else if(w===i)u.key=null;let v=await l("value",u.value,m,g);if(v===n)return n;else if(v===i)u.value=null}}return y}function a(d){if(typeof d==="object"&&(d.Collection||d.Node||d.Value))return Object.assign({Alias:d.Node,Map:d.Node,Scalar:d.Node,Seq:d.Node},d.Value&&{Map:d.Value,Scalar:d.Value,Seq:d.Value},d.Collection&&{Map:d.Collection,Seq:d.Collection},d);return d}function p(d,u,m,g){if(typeof m==="function")return m(d,u,g);if(t.isMap(u))return m.Map?.(d,u,g);if(t.isSeq(u))return m.Seq?.(d,u,g);if(t.isPair(u))return m.Pair?.(d,u,g);if(t.isScalar(u))return m.Scalar?.(d,u,g);if(t.isAlias(u))return m.Alias?.(d,u,g);return}function f(d,u,m){let g=u[u.length-1];if(t.isCollection(g))g.items[d]=m;else if(t.isPair(g))if(d==="key")g.key=m;else g.value=m;else if(t.isDocument(g))g.contents=m;else{let y=t.isAlias(g)?"alias":"scalar";throw Error(`Cannot replace node with ${y} parent`)}}e.visit=o,e.visitAsync=c}),ns=P(function(e){var t=B(),n=Jt(),r={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},i=(s)=>s.replace(/[!,[\]{}]/g,(c)=>r[c]);class o{constructor(s,c){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},o.defaultYaml,s),this.tags=Object.assign({},o.defaultTags,c)}clone(){let s=new o(this.yaml,this.tags);return s.docStart=this.docStart,s}atDocument(){let s=new o(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:o.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},o.defaultTags);break}return s}add(s,c){if(this.atNextDocument)this.yaml={explicit:o.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},o.defaultTags),this.atNextDocument=!1;let l=s.trim().split(/[ \t]+/),a=l.shift();switch(a){case"%TAG":{if(l.length!==2){if(c(0,"%TAG directive should contain exactly two parts"),l.length<2)return!1}let[p,f]=l;return this.tags[p]=f,!0}case"%YAML":{if(this.yaml.explicit=!0,l.length!==1)return c(0,"%YAML directive should contain exactly one part"),!1;let[p]=l;if(p==="1.1"||p==="1.2")return this.yaml.version=p,!0;else{let f=/^\d+\.\d+$/.test(p);return c(6,`Unsupported YAML version ${p}`,f),!1}}default:return c(0,`Unknown directive ${a}`,!0),!1}}tagName(s,c){if(s==="!")return"!";if(s[0]!=="!")return c(`Not a valid tag: ${s}`),null;if(s[1]==="<"){let f=s.slice(2,-1);if(f==="!"||f==="!!")return c(`Verbatim tags aren't resolved, so ${s} is invalid.`),null;if(s[s.length-1]!==">")c("Verbatim tags must end with a >");return f}let[,l,a]=s.match(/^(.*!)([^!]*)$/s);if(!a)c(`The ${s} tag has no suffix`);let p=this.tags[l];if(p)try{return p+decodeURIComponent(a)}catch(f){return c(String(f)),null}if(l==="!")return s;return c(`Could not resolve tag: ${s}`),null}tagString(s){for(let[c,l]of Object.entries(this.tags))if(s.startsWith(l))return c+i(s.substring(l.length));return s[0]==="!"?s:`!<${s}>`}toString(s){let c=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],l=Object.entries(this.tags),a;if(s&&l.length>0&&t.isNode(s.contents)){let p={};n.visit(s.contents,(f,d)=>{if(t.isNode(d)&&d.tag)p[d.tag]=!0}),a=Object.keys(p)}else a=[];for(let[p,f]of l){if(p==="!!"&&f==="tag:yaml.org,2002:")continue;if(!s||a.some((d)=>d.startsWith(f)))c.push(`%TAG ${p} ${f}`)}return c.join(`
|
|
9
|
+
`)}}o.defaultYaml={explicit:!1,version:"1.2"},o.defaultTags={"!!":"tag:yaml.org,2002:"},e.Directives=o}),Wn=P(function(e){var t=B(),n=Jt();function r(c){if(/[\x00-\x19\s,[\]{}]/.test(c)){let a=`Anchor must not contain whitespace or control characters: ${JSON.stringify(c)}`;throw Error(a)}return!0}function i(c){let l=new Set;return n.visit(c,{Value(a,p){if(p.anchor)l.add(p.anchor)}}),l}function o(c,l){for(let a=1;;++a){let p=`${c}${a}`;if(!l.has(p))return p}}function s(c,l){let a=[],p=new Map,f=null;return{onAnchor:(d)=>{a.push(d),f??(f=i(c));let u=o(l,f);return f.add(u),u},setAnchors:()=>{for(let d of a){let u=p.get(d);if(typeof u==="object"&&u.anchor&&(t.isScalar(u.node)||t.isCollection(u.node)))u.node.anchor=u.anchor;else{let m=Error("Failed to resolve repeated object (this should not happen)");throw m.source=d,m}}},sourceObjects:p}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=s,e.findNewAnchor=o}),rs=P(function(e){function t(n,r,i,o){if(o&&typeof o==="object")if(Array.isArray(o))for(let s=0,c=o.length;s<c;++s){let l=o[s],a=t(n,o,String(s),l);if(a===void 0)delete o[s];else if(a!==l)o[s]=a}else if(o instanceof Map)for(let s of Array.from(o.keys())){let c=o.get(s),l=t(n,o,s,c);if(l===void 0)o.delete(s);else if(l!==c)o.set(s,l)}else if(o instanceof Set)for(let s of Array.from(o)){let c=t(n,o,s,s);if(c===void 0)o.delete(s);else if(c!==s)o.delete(s),o.add(c)}else for(let[s,c]of Object.entries(o)){let l=t(n,o,s,c);if(l===void 0)delete o[s];else if(l!==c)o[s]=l}return n.call(r,i,o)}e.applyReviver=t}),qe=P(function(e){var t=B();function n(r,i,o){if(Array.isArray(r))return r.map((s,c)=>n(s,String(c),o));if(r&&typeof r.toJSON==="function"){if(!o||!t.hasAnchor(r))return r.toJSON(i,o);let s={aliasCount:0,count:1,res:void 0};o.anchors.set(r,s),o.onCreate=(l)=>{s.res=l,delete o.onCreate};let c=r.toJSON(i,o);if(o.onCreate)o.onCreate(c);return c}if(typeof r==="bigint"&&!o?.keep)return Number(r);return r}e.toJS=n}),Jn=P(function(e){var t=rs(),n=B(),r=qe();class i{constructor(o){Object.defineProperty(this,n.NODE_TYPE,{value:o})}clone(){let o=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)o.range=this.range.slice();return o}toJS(o,{mapAsMap:s,maxAliasCount:c,onAnchor:l,reviver:a}={}){if(!n.isDocument(o))throw TypeError("A document argument is required");let p={anchors:new Map,doc:o,keep:!0,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof c==="number"?c:100},f=r.toJS(this,"",p);if(typeof l==="function")for(let{count:d,res:u}of p.anchors.values())l(u,d);return typeof a==="function"?t.applyReviver(a,{"":f},"",f):f}}e.NodeBase=i}),Ht=P(function(e){var t=Wn(),n=Jt(),r=B(),i=Jn(),o=qe();class s extends i.NodeBase{constructor(l){super(r.ALIAS);this.source=l,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve(l,a){if(a?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let p;if(a?.aliasResolveCache)p=a.aliasResolveCache;else if(p=[],n.visit(l,{Node:(d,u)=>{if(r.isAlias(u)||r.hasAnchor(u))p.push(u)}}),a)a.aliasResolveCache=p;let f=void 0;for(let d of p){if(d===this)break;if(d.anchor===this.source)f=d}return f}toJSON(l,a){if(!a)return{source:this.source};let{anchors:p,doc:f,maxAliasCount:d}=a,u=this.resolve(f,a);if(!u){let g=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(g)}let m=p.get(u);if(!m)o.toJS(u,null,a),m=p.get(u);if(m?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(d>=0){if(m.count+=1,m.aliasCount===0)m.aliasCount=c(f,u,p);if(m.count*m.aliasCount>d)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return m.res}toString(l,a,p){let f=`*${this.source}`;if(l){if(t.anchorIsValid(this.source),l.options.verifyAliasOrder&&!l.anchors.has(this.source)){let d=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(d)}if(l.implicitKey)return`${f} `}return f}}function c(l,a,p){if(r.isAlias(a)){let f=a.resolve(l),d=p&&f&&p.get(f);return d?d.count*d.aliasCount:0}else if(r.isCollection(a)){let f=0;for(let d of a.items){let u=c(l,d,p);if(u>f)f=u}return f}else if(r.isPair(a)){let f=c(l,a.key,p),d=c(l,a.value,p);return Math.max(f,d)}return 1}e.Alias=s}),oe=P(function(e){var t=B(),n=Jn(),r=qe(),i=(s)=>!s||typeof s!=="function"&&typeof s!=="object";class o extends n.NodeBase{constructor(s){super(t.SCALAR);this.value=s}toJSON(s,c){return c?.keep?this.value:r.toJS(this.value,s,c)}toString(){return String(this.value)}}o.BLOCK_FOLDED="BLOCK_FOLDED",o.BLOCK_LITERAL="BLOCK_LITERAL",o.PLAIN="PLAIN",o.QUOTE_DOUBLE="QUOTE_DOUBLE",o.QUOTE_SINGLE="QUOTE_SINGLE",e.Scalar=o,e.isScalarValue=i}),Vt=P(function(e){var t=Ht(),n=B(),r=oe(),i="tag:yaml.org,2002:";function o(c,l,a){if(l){let p=a.filter((d)=>d.tag===l),f=p.find((d)=>!d.format)??p[0];if(!f)throw Error(`Tag ${l} not found`);return f}return a.find((p)=>p.identify?.(c)&&!p.format)}function s(c,l,a){if(n.isDocument(c))c=c.contents;if(n.isNode(c))return c;if(n.isPair(c)){let v=a.schema[n.MAP].createNode?.(a.schema,null,a);return v.items.push(c),v}if(c instanceof String||c instanceof Number||c instanceof Boolean||typeof BigInt<"u"&&c instanceof BigInt)c=c.valueOf();let{aliasDuplicateObjects:p,onAnchor:f,onTagObj:d,schema:u,sourceObjects:m}=a,g=void 0;if(p&&c&&typeof c==="object")if(g=m.get(c),g)return g.anchor??(g.anchor=f(c)),new t.Alias(g.anchor);else g={anchor:null,node:null},m.set(c,g);if(l?.startsWith("!!"))l=i+l.slice(2);let y=o(c,l,u.tags);if(!y){if(c&&typeof c.toJSON==="function")c=c.toJSON();if(!c||typeof c!=="object"){let v=new r.Scalar(c);if(g)g.node=v;return v}y=c instanceof Map?u[n.MAP]:(Symbol.iterator in Object(c))?u[n.SEQ]:u[n.MAP]}if(d)d(y),delete a.onTagObj;let w=y?.createNode?y.createNode(a.schema,c,a):typeof y?.nodeClass?.from==="function"?y.nodeClass.from(a.schema,c,a):new r.Scalar(c);if(l)w.tag=l;else if(!y.default)w.tag=y.tag;if(g)g.node=w;return w}e.createNode=s}),Hn=P(function(e){var t=Vt(),n=B(),r=Jn();function i(c,l,a){let p=a;for(let f=l.length-1;f>=0;--f){let d=l[f];if(typeof d==="number"&&Number.isInteger(d)&&d>=0){let u=[];u[d]=p,p=u}else p=new Map([[d,p]])}return t.createNode(p,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:c,sourceObjects:new Map})}var o=(c)=>c==null||typeof c==="object"&&!!c[Symbol.iterator]().next().done;class s extends r.NodeBase{constructor(c,l){super(c);Object.defineProperty(this,"schema",{value:l,configurable:!0,enumerable:!1,writable:!0})}clone(c){let l=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(c)l.schema=c;if(l.items=l.items.map((a)=>n.isNode(a)||n.isPair(a)?a.clone(c):a),this.range)l.range=this.range.slice();return l}addIn(c,l){if(o(c))this.add(l);else{let[a,...p]=c,f=this.get(a,!0);if(n.isCollection(f))f.addIn(p,l);else if(f===void 0&&this.schema)this.set(a,i(this.schema,p,l));else throw Error(`Expected YAML collection at ${a}. Remaining path: ${p}`)}}deleteIn(c){let[l,...a]=c;if(a.length===0)return this.delete(l);let p=this.get(l,!0);if(n.isCollection(p))return p.deleteIn(a);else throw Error(`Expected YAML collection at ${l}. Remaining path: ${a}`)}getIn(c,l){let[a,...p]=c,f=this.get(a,!0);if(p.length===0)return!l&&n.isScalar(f)?f.value:f;else return n.isCollection(f)?f.getIn(p,l):void 0}hasAllNullValues(c){return this.items.every((l)=>{if(!n.isPair(l))return!1;let a=l.value;return a==null||c&&n.isScalar(a)&&a.value==null&&!a.commentBefore&&!a.comment&&!a.tag})}hasIn(c){let[l,...a]=c;if(a.length===0)return this.has(l);let p=this.get(l,!0);return n.isCollection(p)?p.hasIn(a):!1}setIn(c,l){let[a,...p]=c;if(p.length===0)this.set(a,l);else{let f=this.get(a,!0);if(n.isCollection(f))f.setIn(p,l);else if(f===void 0&&this.schema)this.set(a,i(this.schema,p,l));else throw Error(`Expected YAML collection at ${a}. Remaining path: ${p}`)}}}e.Collection=s,e.collectionFromPath=i,e.isEmptyPath=o}),Gt=P(function(e){var t=(i)=>i.replace(/^(?!$)(?: $)?/gm,"#");function n(i,o){if(/^\n+$/.test(i))return i.substring(1);return o?i.replace(/^(?! *$)/gm,o):i}var r=(i,o,s)=>i.endsWith(`
|
|
10
10
|
`)?n(s,o):s.includes(`
|
|
11
11
|
`)?`
|
|
12
|
-
`+n(s,o):(i.endsWith(" ")?"":" ")+s;e.indentComment=n,e.lineComment=r,e.stringifyComment=t}),
|
|
13
|
-
`){if(l===n)_=o(s,_,c.length);w=_+c.length+m,v=void 0}else{if(
|
|
14
|
-
`&&b!=="\t"){let
|
|
15
|
-
`&&
|
|
16
|
-
${c}${s.slice(0,L)}`;else{if(l===r&&y[
|
|
17
|
-
${c}${s.slice(
|
|
18
|
-
`);a=c,p=c+1,f=s[p]}return a}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=i}),Yt=
|
|
19
|
-
`){if(v-b>y)return!0;if(b=v+1,w-b<=y)return!1}return!0}function s(u,m){let g=JSON.stringify(u);if(m.options.doubleQuotedAsJSON)return g;let{implicitKey:y}=m,w=m.options.doubleQuotedMinMultiLineLength,v=m.indent||(i(u)?" ":""),b="",k=0;for(let _=0,
|
|
12
|
+
`+n(s,o):(i.endsWith(" ")?"":" ")+s;e.indentComment=n,e.lineComment=r,e.stringifyComment=t}),Nl=P(function(e){var t="flow",n="block",r="quoted";function i(s,c,l="flow",{indentAtStart:a,lineWidth:p=80,minContentWidth:f=20,onFold:d,onOverflow:u}={}){if(!p||p<0)return s;if(p<f)f=0;let m=Math.max(1+f,1+p-c.length);if(s.length<=m)return s;let g=[],y={},w=p-c.length;if(typeof a==="number")if(a>p-Math.max(2,f))g.push(0);else w=p-a;let v=void 0,b=void 0,k=!1,_=-1,E=-1,O=-1;if(l===n){if(_=o(s,_,c.length),_!==-1)w=_+m}for(let C;C=s[_+=1];){if(l===r&&C==="\\"){switch(E=_,s[_+1]){case"x":_+=3;break;case"u":_+=5;break;case"U":_+=9;break;default:_+=1}O=_}if(C===`
|
|
13
|
+
`){if(l===n)_=o(s,_,c.length);w=_+c.length+m,v=void 0}else{if(C===" "&&b&&b!==" "&&b!==`
|
|
14
|
+
`&&b!=="\t"){let N=s[_+1];if(N&&N!==" "&&N!==`
|
|
15
|
+
`&&N!=="\t")v=_}if(_>=w)if(v)g.push(v),w=v+m,v=void 0;else if(l===r){while(b===" "||b==="\t")b=C,C=s[_+=1],k=!0;let N=_>O+1?_-2:E-1;if(y[N])return s;g.push(N),y[N]=!0,w=N+m,v=void 0}else k=!0}b=C}if(k&&u)u();if(g.length===0)return s;if(d)d();let I=s.slice(0,g[0]);for(let C=0;C<g.length;++C){let N=g[C],L=g[C+1]||s.length;if(N===0)I=`
|
|
16
|
+
${c}${s.slice(0,L)}`;else{if(l===r&&y[N])I+=`${s[N]}\\`;I+=`
|
|
17
|
+
${c}${s.slice(N+1,L)}`}}return I}function o(s,c,l){let a=c,p=c+1,f=s[p];while(f===" "||f==="\t")if(c<p+l)f=s[++c];else{do f=s[++c];while(f&&f!==`
|
|
18
|
+
`);a=c,p=c+1,f=s[p]}return a}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=i}),Yt=P(function(e){var t=oe(),n=Nl(),r=(u,m)=>({indentAtStart:m?u.indent.length:u.indentAtStart,lineWidth:u.options.lineWidth,minContentWidth:u.options.minContentWidth}),i=(u)=>/^(%|---|\.\.\.)/m.test(u);function o(u,m,g){if(!m||m<0)return!1;let y=m-g,w=u.length;if(w<=y)return!1;for(let v=0,b=0;v<w;++v)if(u[v]===`
|
|
19
|
+
`){if(v-b>y)return!0;if(b=v+1,w-b<=y)return!1}return!0}function s(u,m){let g=JSON.stringify(u);if(m.options.doubleQuotedAsJSON)return g;let{implicitKey:y}=m,w=m.options.doubleQuotedMinMultiLineLength,v=m.indent||(i(u)?" ":""),b="",k=0;for(let _=0,E=g[_];E;E=g[++_]){if(E===" "&&g[_+1]==="\\"&&g[_+2]==="n")b+=g.slice(k,_)+"\\ ",_+=1,k=_,E="\\";if(E==="\\")switch(g[_+1]){case"u":{b+=g.slice(k,_);let O=g.substr(_+2,4);switch(O){case"0000":b+="\\0";break;case"0007":b+="\\a";break;case"000b":b+="\\v";break;case"001b":b+="\\e";break;case"0085":b+="\\N";break;case"00a0":b+="\\_";break;case"2028":b+="\\L";break;case"2029":b+="\\P";break;default:if(O.substr(0,2)==="00")b+="\\x"+O.substr(2);else b+=g.substr(_,6)}_+=5,k=_+1}break;case"n":if(y||g[_+2]==='"'||g.length<w)_+=1;else{b+=g.slice(k,_)+`
|
|
20
20
|
|
|
21
21
|
`;while(g[_+2]==="\\"&&g[_+3]==="n"&&g[_+4]!=='"')b+=`
|
|
22
22
|
`,_+=2;if(b+=v,g[_+2]===" ")b+="\\";_+=1,k=_+1}break;default:_+=1}}return b=k?b+g.slice(k):g,y?b:n.foldFlowLines(b,v,n.FOLD_QUOTED,r(m,!1))}function c(u,m){if(m.options.singleQuote===!1||m.implicitKey&&u.includes(`
|
|
@@ -24,71 +24,71 @@ ${c}${s.slice(O+1,L)}`}}return N}function o(s,c,l){let a=c,p=c+1,f=s[p];while(f=
|
|
|
24
24
|
${g}`)+"'";return m.implicitKey?y:n.foldFlowLines(y,g,n.FOLD_FLOW,r(m,!1))}function l(u,m){let{singleQuote:g}=m.options,y;if(g===!1)y=s;else{let w=u.includes('"'),v=u.includes("'");if(w&&!v)y=c;else if(v&&!w)y=s;else y=g?c:s}return y(u,m)}var a;try{a=new RegExp(`(^|(?<!
|
|
25
25
|
))
|
|
26
26
|
+(?!
|
|
27
|
-
|$)`,"g")}catch{a=/\n+(?!\n|$)/g}function p({comment:u,type:m,value:g},y,w,v){let{blockQuote:b,commentString:k,lineWidth:_}=y.options;if(!b||/\n[\t ]+$/.test(g))return l(g,y);let
|
|
27
|
+
|$)`,"g")}catch{a=/\n+(?!\n|$)/g}function p({comment:u,type:m,value:g},y,w,v){let{blockQuote:b,commentString:k,lineWidth:_}=y.options;if(!b||/\n[\t ]+$/.test(g))return l(g,y);let E=y.indent||(y.forceBlockIndent||i(g)?" ":""),O=b==="literal"?!0:b==="folded"||m===t.Scalar.BLOCK_FOLDED?!1:m===t.Scalar.BLOCK_LITERAL?!0:!o(g,_,E.length);if(!g)return O?`|
|
|
28
28
|
`:`>
|
|
29
|
-
`;let
|
|
30
|
-
`&&U!=="\t"&&U!==" ")break}let
|
|
31
|
-
`);if(L===-1)
|
|
32
|
-
`)
|
|
33
|
-
`)ne=
|
|
34
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${
|
|
35
|
-
${
|
|
36
|
-
${
|
|
37
|
-
`)||
|
|
38
|
-
`)?l(v,m):p(u,m,g,y);if(!k&&!
|
|
39
|
-
`))return p(u,m,g,y);if(i(v)){if(_==="")return m.forceBlockIndent=!0,p(u,m,g,y);else if(k&&_===
|
|
40
|
-
${_}`);if(b){let
|
|
41
|
-
${p.indent}${y}`}e.createStringifyContext=o,e.stringify=l}),
|
|
42
|
-
${u}:`}else if(
|
|
43
|
-
`:"",
|
|
44
|
-
${i.indentComment(
|
|
45
|
-
`&&
|
|
29
|
+
`;let I,C;for(C=g.length;C>0;--C){let U=g[C-1];if(U!==`
|
|
30
|
+
`&&U!=="\t"&&U!==" ")break}let N=g.substring(C),L=N.indexOf(`
|
|
31
|
+
`);if(L===-1)I="-";else if(g===N||L!==N.length-1){if(I="+",v)v()}else I="";if(N){if(g=g.slice(0,-N.length),N[N.length-1]===`
|
|
32
|
+
`)N=N.slice(0,-1);N=N.replace(a,`$&${E}`)}let D=!1,K,ne=-1;for(K=0;K<g.length;++K){let U=g[K];if(U===" ")D=!0;else if(U===`
|
|
33
|
+
`)ne=K;else break}let Y=g.substring(0,ne<K?ne+1:K);if(Y)g=g.substring(Y.length),Y=Y.replace(/\n+/g,`$&${E}`);let re=(D?E?"2":"1":"")+I;if(u){if(re+=" "+k(u.replace(/ ?[\r\n]+/g," ")),w)w()}if(!O){let U=g.replace(/\n+/g,`
|
|
34
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${E}`),ce=!1,V=r(y,!0);if(b!=="folded"&&m!==t.Scalar.BLOCK_FOLDED)V.onOverflow=()=>{ce=!0};let fe=n.foldFlowLines(`${Y}${U}${N}`,E,n.FOLD_BLOCK,V);if(!ce)return`>${re}
|
|
35
|
+
${E}${fe}`}return g=g.replace(/\n+/g,`$&${E}`),`|${re}
|
|
36
|
+
${E}${Y}${g}${N}`}function f(u,m,g,y){let{type:w,value:v}=u,{actualString:b,implicitKey:k,indent:_,indentStep:E,inFlow:O}=m;if(k&&v.includes(`
|
|
37
|
+
`)||O&&/[[\]{},]/.test(v))return l(v,m);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(v))return k||O||!v.includes(`
|
|
38
|
+
`)?l(v,m):p(u,m,g,y);if(!k&&!O&&w!==t.Scalar.PLAIN&&v.includes(`
|
|
39
|
+
`))return p(u,m,g,y);if(i(v)){if(_==="")return m.forceBlockIndent=!0,p(u,m,g,y);else if(k&&_===E)return l(v,m)}let I=v.replace(/\n+/g,`$&
|
|
40
|
+
${_}`);if(b){let C=(D)=>D.default&&D.tag!=="tag:yaml.org,2002:str"&&D.test?.test(I),{compat:N,tags:L}=m.doc.schema;if(L.some(C)||N?.some(C))return l(v,m)}return k?I:n.foldFlowLines(I,_,n.FOLD_FLOW,r(m,!1))}function d(u,m,g,y){let{implicitKey:w,inFlow:v}=m,b=typeof u.value==="string"?u:Object.assign({},u,{value:String(u.value)}),{type:k}=u;if(k!==t.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(b.value))k=t.Scalar.QUOTE_DOUBLE}let _=(O)=>{switch(O){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return w||v?l(b.value,m):p(b,m,g,y);case t.Scalar.QUOTE_DOUBLE:return s(b.value,m);case t.Scalar.QUOTE_SINGLE:return c(b.value,m);case t.Scalar.PLAIN:return f(b,m,g,y);default:return null}},E=_(k);if(E===null){let{defaultKeyType:O,defaultStringType:I}=m.options,C=w&&O||I;if(E=_(C),E===null)throw Error(`Unsupported default string type ${C}`)}return E}e.stringifyString=d}),Xt=P(function(e){var t=Wn(),n=B(),r=Gt(),i=Yt();function o(a,p){let f=Object.assign({blockQuote:!0,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},a.schema.toStringOptions,p),d;switch(f.collectionStyle){case"block":d=!1;break;case"flow":d=!0;break;default:d=null}return{anchors:new Set,doc:a,flowCollectionPadding:f.flowCollectionPadding?" ":"",indent:"",indentStep:typeof f.indent==="number"?" ".repeat(f.indent):" ",inFlow:d,options:f}}function s(a,p){if(p.tag){let u=a.filter((m)=>m.tag===p.tag);if(u.length>0)return u.find((m)=>m.format===p.format)??u[0]}let f=void 0,d;if(n.isScalar(p)){d=p.value;let u=a.filter((m)=>m.identify?.(d));if(u.length>1){let m=u.filter((g)=>g.test);if(m.length>0)u=m}f=u.find((m)=>m.format===p.format)??u.find((m)=>!m.format)}else d=p,f=a.find((u)=>u.nodeClass&&d instanceof u.nodeClass);if(!f){let u=d?.constructor?.name??(d===null?"null":typeof d);throw Error(`Tag not resolved for ${u} value`)}return f}function c(a,p,{anchors:f,doc:d}){if(!d.directives)return"";let u=[],m=(n.isScalar(a)||n.isCollection(a))&&a.anchor;if(m&&t.anchorIsValid(m))f.add(m),u.push(`&${m}`);let g=a.tag??(p.default?null:p.tag);if(g)u.push(d.directives.tagString(g));return u.join(" ")}function l(a,p,f,d){if(n.isPair(a))return a.toString(p,f,d);if(n.isAlias(a)){if(p.doc.directives)return a.toString(p);if(p.resolvedAliases?.has(a))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(p.resolvedAliases)p.resolvedAliases.add(a);else p.resolvedAliases=new Set([a]);a=a.resolve(p.doc)}}let u=void 0,m=n.isNode(a)?a:p.doc.createNode(a,{onTagObj:(w)=>u=w});u??(u=s(p.doc.schema.tags,m));let g=c(m,u,p);if(g.length>0)p.indentAtStart=(p.indentAtStart??0)+g.length+1;let y=typeof u.stringify==="function"?u.stringify(m,p,f,d):n.isScalar(m)?i.stringifyString(m,p,f,d):m.toString(p,f,d);if(!g)return y;return n.isScalar(m)||y[0]==="{"||y[0]==="["?`${g} ${y}`:`${g}
|
|
41
|
+
${p.indent}${y}`}e.createStringifyContext=o,e.stringify=l}),Il=P(function(e){var t=B(),n=oe(),r=Xt(),i=Gt();function o({key:s,value:c},l,a,p){let{allNullValues:f,doc:d,indent:u,indentStep:m,options:{commentString:g,indentSeq:y,simpleKeys:w}}=l,v=t.isNode(s)&&s.comment||null;if(w){if(v)throw Error("With simple keys, key nodes cannot have comments");if(t.isCollection(s)||!t.isNode(s)&&typeof s==="object")throw Error("With simple keys, collection cannot be used as a key value")}let b=!w&&(!s||v&&c==null&&!l.inFlow||t.isCollection(s)||(t.isScalar(s)?s.type===n.Scalar.BLOCK_FOLDED||s.type===n.Scalar.BLOCK_LITERAL:typeof s==="object"));l=Object.assign({},l,{allNullValues:!1,implicitKey:!b&&(w||!f),indent:u+m});let k=!1,_=!1,E=r.stringify(s,l,()=>k=!0,()=>_=!0);if(!b&&!l.inFlow&&E.length>1024){if(w)throw Error("With simple keys, single line scalar must not span more than 1024 characters");b=!0}if(l.inFlow){if(f||c==null){if(k&&a)a();return E===""?"?":b?`? ${E}`:E}}else if(f&&!w||c==null&&b){if(E=`? ${E}`,v&&!k)E+=i.lineComment(E,l.indent,g(v));else if(_&&p)p();return E}if(k)v=null;if(b){if(v)E+=i.lineComment(E,l.indent,g(v));E=`? ${E}
|
|
42
|
+
${u}:`}else if(E=`${E}:`,v)E+=i.lineComment(E,l.indent,g(v));let O,I,C;if(t.isNode(c))O=!!c.spaceBefore,I=c.commentBefore,C=c.comment;else if(O=!1,I=null,C=null,c&&typeof c==="object")c=d.createNode(c);if(l.implicitKey=!1,!b&&!v&&t.isScalar(c))l.indentAtStart=E.length+1;if(_=!1,!y&&m.length>=2&&!l.inFlow&&!b&&t.isSeq(c)&&!c.flow&&!c.tag&&!c.anchor)l.indent=l.indent.substring(2);let N=!1,L=r.stringify(c,l,()=>N=!0,()=>_=!0),D=" ";if(v||O||I){if(D=O?`
|
|
43
|
+
`:"",I){let K=g(I);D+=`
|
|
44
|
+
${i.indentComment(K,l.indent)}`}if(L===""&&!l.inFlow){if(D===`
|
|
45
|
+
`&&C)D=`
|
|
46
46
|
|
|
47
47
|
`}else D+=`
|
|
48
|
-
${l.indent}`}else if(!b&&t.isCollection(c)){let
|
|
49
|
-
`),Y=ne!==-1
|
|
48
|
+
${l.indent}`}else if(!b&&t.isCollection(c)){let K=L[0],ne=L.indexOf(`
|
|
49
|
+
`),Y=ne!==-1,Ee=l.inFlow??c.flow??c.items.length===0;if(Y||!Ee){let re=!1;if(Y&&(K==="&"||K==="!")){let U=L.indexOf(" ");if(K==="&"&&U!==-1&&U<ne&&L[U+1]==="!")U=L.indexOf(" ",U+1);if(U===-1||ne<U)re=!0}if(!re)D=`
|
|
50
50
|
${l.indent}`}}else if(L===""||L[0]===`
|
|
51
|
-
`)D="";if(
|
|
52
|
-
${y}${
|
|
51
|
+
`)D="";if(E+=D+L,l.inFlow){if(N&&a)a()}else if(C&&!N)E+=i.lineComment(E,l.indent,g(C));else if(_&&p)p();return E}e.stringifyPair=o}),is=P(function(e){var t=Wt("process");function n(i,...o){if(i==="debug")console.log(...o)}function r(i,o){if(i==="debug"||i==="warn")if(typeof t.emitWarning==="function")t.emitWarning(o);else console.warn(o)}e.debug=n,e.warn=r}),Vn=P(function(e){var t=B(),n=oe(),r="<<",i={identify:(a)=>a===r||typeof a==="symbol"&&a.description===r,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new n.Scalar(Symbol(r)),{addToJSMap:s}),stringify:()=>r},o=(a,p)=>(i.identify(p)||t.isScalar(p)&&(!p.type||p.type===n.Scalar.PLAIN)&&i.identify(p.value))&&a?.doc.schema.tags.some((f)=>f.tag===i.tag&&f.default);function s(a,p,f){let d=l(a,f);if(t.isSeq(d))for(let u of d.items)c(a,p,u);else if(Array.isArray(d))for(let u of d)c(a,p,u);else c(a,p,d)}function c(a,p,f){let d=l(a,f);if(!t.isMap(d))throw Error("Merge sources must be maps or map aliases");let u=d.toJSON(null,a,Map);for(let[m,g]of u)if(p instanceof Map){if(!p.has(m))p.set(m,g)}else if(p instanceof Set)p.add(m);else if(!Object.prototype.hasOwnProperty.call(p,m))Object.defineProperty(p,m,{value:g,writable:!0,enumerable:!0,configurable:!0});return p}function l(a,p){return a&&t.isAlias(p)?p.resolve(a.doc,a):p}e.addMergeToJSMap=s,e.isMergeKey=o,e.merge=i}),ss=P(function(e){var t=is(),n=Vn(),r=Xt(),i=B(),o=qe();function s(l,a,{key:p,value:f}){if(i.isNode(p)&&p.addToJSMap)p.addToJSMap(l,a,f);else if(n.isMergeKey(l,p))n.addMergeToJSMap(l,a,f);else{let d=o.toJS(p,"",l);if(a instanceof Map)a.set(d,o.toJS(f,d,l));else if(a instanceof Set)a.add(d);else{let u=c(p,d,l),m=o.toJS(f,u,l);if(u in a)Object.defineProperty(a,u,{value:m,writable:!0,enumerable:!0,configurable:!0});else a[u]=m}}return a}function c(l,a,p){if(a===null)return"";if(typeof a!=="object")return String(a);if(i.isNode(l)&&p?.doc){let f=r.createStringifyContext(p.doc,{});f.anchors=new Set;for(let u of p.anchors.keys())f.anchors.add(u.anchor);f.inFlow=!0,f.inStringifyKey=!0;let d=l.toString(f);if(!p.mapKeyWarned){let u=JSON.stringify(d);if(u.length>40)u=u.substring(0,36)+'..."';t.warn(p.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${u}. Set mapAsMap: true to use object keys.`),p.mapKeyWarned=!0}return d}return JSON.stringify(a)}e.addPairToJSMap=s}),Ze=P(function(e){var t=Vt(),n=Il(),r=ss(),i=B();function o(c,l,a){let p=t.createNode(c,void 0,a),f=t.createNode(l,void 0,a);return new s(p,f)}class s{constructor(c,l=null){Object.defineProperty(this,i.NODE_TYPE,{value:i.PAIR}),this.key=c,this.value=l}clone(c){let{key:l,value:a}=this;if(i.isNode(l))l=l.clone(c);if(i.isNode(a))a=a.clone(c);return new s(l,a)}toJSON(c,l){let a=l?.mapAsMap?new Map:{};return r.addPairToJSMap(l,a,this)}toString(c,l,a){return c?.doc?n.stringifyPair(this,c,l,a):JSON.stringify(this)}}e.Pair=s,e.createPair=o}),os=P(function(e){var t=B(),n=Xt(),r=Gt();function i(l,a,p){return(a.inFlow??l.flow?s:o)(l,a,p)}function o({comment:l,items:a},p,{blockItemPrefix:f,flowChars:d,itemIndent:u,onChompKeep:m,onComment:g}){let{indent:y,options:{commentString:w}}=p,v=Object.assign({},p,{indent:u,type:null}),b=!1,k=[];for(let E=0;E<a.length;++E){let O=a[E],I=null;if(t.isNode(O)){if(!b&&O.spaceBefore)k.push("");if(c(p,k,O.commentBefore,b),O.comment)I=O.comment}else if(t.isPair(O)){let N=t.isNode(O.key)?O.key:null;if(N){if(!b&&N.spaceBefore)k.push("");c(p,k,N.commentBefore,b)}}b=!1;let C=n.stringify(O,v,()=>I=null,()=>b=!0);if(I)C+=r.lineComment(C,u,w(I));if(b&&I)b=!1;k.push(f+C)}let _;if(k.length===0)_=d.start+d.end;else{_=k[0];for(let E=1;E<k.length;++E){let O=k[E];_+=O?`
|
|
52
|
+
${y}${O}`:`
|
|
53
53
|
`}}if(l){if(_+=`
|
|
54
|
-
`+r.indentComment(w(l),y),g)g()}else if(b&&m)m();return _}function s({items:l},a,{flowChars:p,itemIndent:f}){let{indent:d,indentStep:u,flowCollectionPadding:m,options:{commentString:g}}=a;f+=u;let y=Object.assign({},a,{indent:f,inFlow:!0,type:null}),w=!1,v=0,b=[];for(let
|
|
55
|
-
`)),
|
|
56
|
-
${u}${d}${
|
|
57
|
-
`;return`${
|
|
58
|
-
${d}${_}`}else return`${k}${m}${b.join(" ")}${m}${_}`}}function c({indent:l,options:{commentString:a}},p,f,d){if(f&&d)f=f.replace(/^\n+/,"");if(f){let u=r.indentComment(a(f),l);p.push(u.trimStart())}}e.stringifyCollection=i}),
|
|
59
|
-
`:" ")}return r.stringifyString({comment:o,type:s,value:d},l,a,p)}};e.binary=i}),Yn=
|
|
54
|
+
`+r.indentComment(w(l),y),g)g()}else if(b&&m)m();return _}function s({items:l},a,{flowChars:p,itemIndent:f}){let{indent:d,indentStep:u,flowCollectionPadding:m,options:{commentString:g}}=a;f+=u;let y=Object.assign({},a,{indent:f,inFlow:!0,type:null}),w=!1,v=0,b=[];for(let E=0;E<l.length;++E){let O=l[E],I=null;if(t.isNode(O)){if(O.spaceBefore)b.push("");if(c(a,b,O.commentBefore,!1),O.comment)I=O.comment}else if(t.isPair(O)){let N=t.isNode(O.key)?O.key:null;if(N){if(N.spaceBefore)b.push("");if(c(a,b,N.commentBefore,!1),N.comment)w=!0}let L=t.isNode(O.value)?O.value:null;if(L){if(L.comment)I=L.comment;if(L.commentBefore)w=!0}else if(O.value==null&&N?.comment)I=N.comment}if(I)w=!0;let C=n.stringify(O,y,()=>I=null);if(w||(w=b.length>v||C.includes(`
|
|
55
|
+
`)),E<l.length-1)C+=",";else if(a.options.trailingComma){if(a.options.lineWidth>0)w||(w=b.reduce((N,L)=>N+L.length+2,2)+(C.length+2)>a.options.lineWidth);if(w)C+=","}if(I)C+=r.lineComment(C,f,g(I));b.push(C),v=b.length}let{start:k,end:_}=p;if(b.length===0)return k+_;else{if(!w){let E=b.reduce((O,I)=>O+I.length+2,2);w=a.options.lineWidth>0&&E>a.options.lineWidth}if(w){let E=k;for(let O of b)E+=O?`
|
|
56
|
+
${u}${d}${O}`:`
|
|
57
|
+
`;return`${E}
|
|
58
|
+
${d}${_}`}else return`${k}${m}${b.join(" ")}${m}${_}`}}function c({indent:l,options:{commentString:a}},p,f,d){if(f&&d)f=f.replace(/^\n+/,"");if(f){let u=r.indentComment(a(f),l);p.push(u.trimStart())}}e.stringifyCollection=i}),We=P(function(e){var t=os(),n=ss(),r=Hn(),i=B(),o=Ze(),s=oe();function c(a,p){let f=i.isScalar(p)?p.value:p;for(let d of a)if(i.isPair(d)){if(d.key===p||d.key===f)return d;if(i.isScalar(d.key)&&d.key.value===f)return d}return}class l extends r.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(a){super(i.MAP,a);this.items=[]}static from(a,p,f){let{keepUndefined:d,replacer:u}=f,m=new this(a),g=(y,w)=>{if(typeof u==="function")w=u.call(p,y,w);else if(Array.isArray(u)&&!u.includes(y))return;if(w!==void 0||d)m.items.push(o.createPair(y,w,f))};if(p instanceof Map)for(let[y,w]of p)g(y,w);else if(p&&typeof p==="object")for(let y of Object.keys(p))g(y,p[y]);if(typeof a.sortMapEntries==="function")m.items.sort(a.sortMapEntries);return m}add(a,p){let f;if(i.isPair(a))f=a;else if(!a||typeof a!=="object"||!("key"in a))f=new o.Pair(a,a?.value);else f=new o.Pair(a.key,a.value);let d=c(this.items,f.key),u=this.schema?.sortMapEntries;if(d){if(!p)throw Error(`Key ${f.key} already set`);if(i.isScalar(d.value)&&s.isScalarValue(f.value))d.value.value=f.value;else d.value=f.value}else if(u){let m=this.items.findIndex((g)=>u(f,g)<0);if(m===-1)this.items.push(f);else this.items.splice(m,0,f)}else this.items.push(f)}delete(a){let p=c(this.items,a);if(!p)return!1;return this.items.splice(this.items.indexOf(p),1).length>0}get(a,p){let d=c(this.items,a)?.value;return(!p&&i.isScalar(d)?d.value:d)??void 0}has(a){return!!c(this.items,a)}set(a,p){this.add(new o.Pair(a,p),!0)}toJSON(a,p,f){let d=f?new f:p?.mapAsMap?new Map:{};if(p?.onCreate)p.onCreate(d);for(let u of this.items)n.addPairToJSMap(p,d,u);return d}toString(a,p,f){if(!a)return JSON.stringify(this);for(let d of this.items)if(!i.isPair(d))throw Error(`Map items must all be pairs; found ${JSON.stringify(d)} instead`);if(!a.allNullValues&&this.hasAllNullValues(!1))a=Object.assign({},a,{allNullValues:!0});return t.stringifyCollection(this,a,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:a.indent||"",onChompKeep:f,onComment:p})}}e.YAMLMap=l,e.findPair=c}),ht=P(function(e){var t=B(),n=We(),r={collection:"map",default:!0,nodeClass:n.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(i,o){if(!t.isMap(i))o("Expected a mapping for this tag");return i},createNode:(i,o,s)=>n.YAMLMap.from(i,o,s)};e.map=r}),Je=P(function(e){var t=Vt(),n=os(),r=Hn(),i=B(),o=oe(),s=qe();class c extends r.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(a){super(i.SEQ,a);this.items=[]}add(a){this.items.push(a)}delete(a){let p=l(a);if(typeof p!=="number")return!1;return this.items.splice(p,1).length>0}get(a,p){let f=l(a);if(typeof f!=="number")return;let d=this.items[f];return!p&&i.isScalar(d)?d.value:d}has(a){let p=l(a);return typeof p==="number"&&p<this.items.length}set(a,p){let f=l(a);if(typeof f!=="number")throw Error(`Expected a valid index, not ${a}.`);let d=this.items[f];if(i.isScalar(d)&&o.isScalarValue(p))d.value=p;else this.items[f]=p}toJSON(a,p){let f=[];if(p?.onCreate)p.onCreate(f);let d=0;for(let u of this.items)f.push(s.toJS(u,String(d++),p));return f}toString(a,p,f){if(!a)return JSON.stringify(this);return n.stringifyCollection(this,a,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(a.indent||"")+" ",onChompKeep:f,onComment:p})}static from(a,p,f){let{replacer:d}=f,u=new this(a);if(p&&Symbol.iterator in Object(p)){let m=0;for(let g of p){if(typeof d==="function"){let y=p instanceof Set?g:String(m++);g=d.call(p,y,g)}u.items.push(t.createNode(g,void 0,f))}}return u}}function l(a){let p=i.isScalar(a)?a.value:a;if(p&&typeof p==="string")p=Number(p);return typeof p==="number"&&Number.isInteger(p)&&p>=0?p:null}e.YAMLSeq=c}),pt=P(function(e){var t=B(),n=Je(),r={collection:"seq",default:!0,nodeClass:n.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(i,o){if(!t.isSeq(i))o("Expected a sequence for this tag");return i},createNode:(i,o,s)=>n.YAMLSeq.from(i,o,s)};e.seq=r}),Qt=P(function(e){var t=Yt(),n={identify:(r)=>typeof r==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(r)=>r,stringify(r,i,o,s){return i=Object.assign({actualString:!0},i),t.stringifyString(r,i,o,s)}};e.string=n}),Gn=P(function(e){var t=oe(),n={identify:(r)=>r==null,createNode:()=>new t.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new t.Scalar(null),stringify:({source:r},i)=>typeof r==="string"&&n.test.test(r)?r:i.options.nullStr};e.nullTag=n}),as=P(function(e){var t=oe(),n={identify:(r)=>typeof r==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:(r)=>new t.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:i},o){if(r&&n.test.test(r)){let s=r[0]==="t"||r[0]==="T";if(i===s)return r}return i?o.options.trueStr:o.options.falseStr}};e.boolTag=n}),mt=P(function(e){function t({format:n,minFractionDigits:r,tag:i,value:o}){if(typeof o==="bigint")return String(o);let s=typeof o==="number"?o:Number(o);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let c=Object.is(o,-0)?"-0":JSON.stringify(o);if(!n&&r&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(c)&&!c.includes("e")){let l=c.indexOf(".");if(l<0)l=c.length,c+=".";let a=r-(c.length-l-1);while(a-- >0)c+="0"}return c}e.stringifyNumber=t}),cs=P(function(e){var t=oe(),n=mt(),r={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(s)=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:n.stringifyNumber},i={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(s)=>parseFloat(s),stringify(s){let c=Number(s.value);return isFinite(c)?c.toExponential():n.stringifyNumber(s)}},o={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){let c=new t.Scalar(parseFloat(s)),l=s.indexOf(".");if(l!==-1&&s[s.length-1]==="0")c.minFractionDigits=s.length-l-1;return c},stringify:n.stringifyNumber};e.float=o,e.floatExp=i,e.floatNaN=r}),ls=P(function(e){var t=mt(),n=(l)=>typeof l==="bigint"||Number.isInteger(l),r=(l,a,p,{intAsBigInt:f})=>f?BigInt(l):parseInt(l.substring(a),p);function i(l,a,p){let{value:f}=l;if(n(f)&&f>=0)return p+f.toString(a);return t.stringifyNumber(l)}var o={identify:(l)=>n(l)&&l>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(l,a,p)=>r(l,2,8,p),stringify:(l)=>i(l,8,"0o")},s={identify:n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(l,a,p)=>r(l,0,10,p),stringify:t.stringifyNumber},c={identify:(l)=>n(l)&&l>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(l,a,p)=>r(l,2,16,p),stringify:(l)=>i(l,16,"0x")};e.int=s,e.intHex=c,e.intOct=o}),Cl=P(function(e){var t=ht(),n=Gn(),r=pt(),i=Qt(),o=as(),s=cs(),c=ls(),l=[t.map,r.seq,i.string,n.nullTag,o.boolTag,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float];e.schema=l}),Pl=P(function(e){var t=oe(),n=ht(),r=pt();function i(a){return typeof a==="bigint"||Number.isInteger(a)}var o=({value:a})=>JSON.stringify(a),s=[{identify:(a)=>typeof a==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(a)=>a,stringify:o},{identify:(a)=>a==null,createNode:()=>new t.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:o},{identify:(a)=>typeof a==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(a)=>a==="true",stringify:o},{identify:i,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(a,p,{intAsBigInt:f})=>f?BigInt(a):parseInt(a,10),stringify:({value:a})=>i(a)?a.toString():JSON.stringify(a)},{identify:(a)=>typeof a==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:(a)=>parseFloat(a),stringify:o}],c={default:!0,tag:"",test:/^/,resolve(a,p){return p(`Unresolved plain scalar ${JSON.stringify(a)}`),a}},l=[n.map,r.seq].concat(s,c);e.schema=l}),us=P(function(e){var t=Wt("buffer"),n=oe(),r=Yt(),i={identify:(o)=>o instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(o,s){if(typeof t.Buffer==="function")return t.Buffer.from(o,"base64");else if(typeof atob==="function"){let c=atob(o.replace(/[\n\r]/g,"")),l=new Uint8Array(c.length);for(let a=0;a<c.length;++a)l[a]=c.charCodeAt(a);return l}else return s("This environment does not support reading binary tags; either Buffer or atob is required"),o},stringify({comment:o,type:s,value:c},l,a,p){if(!c)return"";let f=c,d;if(typeof t.Buffer==="function")d=f instanceof t.Buffer?f.toString("base64"):t.Buffer.from(f.buffer).toString("base64");else if(typeof btoa==="function"){let u="";for(let m=0;m<f.length;++m)u+=String.fromCharCode(f[m]);d=btoa(u)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(s??(s=n.Scalar.BLOCK_LITERAL),s!==n.Scalar.QUOTE_DOUBLE){let u=Math.max(l.options.lineWidth-l.indent.length,l.options.minContentWidth),m=Math.ceil(d.length/u),g=Array(m);for(let y=0,w=0;y<m;++y,w+=u)g[y]=d.substr(w,u);d=g.join(s===n.Scalar.BLOCK_LITERAL?`
|
|
59
|
+
`:" ")}return r.stringifyString({comment:o,type:s,value:d},l,a,p)}};e.binary=i}),Yn=P(function(e){var t=B(),n=Ze(),r=oe(),i=Je();function o(l,a){if(t.isSeq(l))for(let p=0;p<l.items.length;++p){let f=l.items[p];if(t.isPair(f))continue;else if(t.isMap(f)){if(f.items.length>1)a("Each pair must have its own sequence indicator");let d=f.items[0]||new n.Pair(new r.Scalar(null));if(f.commentBefore)d.key.commentBefore=d.key.commentBefore?`${f.commentBefore}
|
|
60
60
|
${d.key.commentBefore}`:f.commentBefore;if(f.comment){let u=d.value??d.key;u.comment=u.comment?`${f.comment}
|
|
61
|
-
${u.comment}`:f.comment}f=d}l.items[p]=t.isPair(f)?f:new n.Pair(f)}else a("Expected a sequence for this tag");return l}function s(l,a,p){let{replacer:f}=p,d=new i.YAMLSeq(l);d.tag="tag:yaml.org,2002:pairs";let u=0;if(a&&Symbol.iterator in Object(a))for(let m of a){if(typeof f==="function")m=f.call(a,String(u++),m);let g,y;if(Array.isArray(m))if(m.length===2)g=m[0],y=m[1];else throw TypeError(`Expected [key, value] tuple: ${m}`);else if(m&&m instanceof Object){let w=Object.keys(m);if(w.length===1)g=w[0],y=m[g];else throw TypeError(`Expected tuple with one key, not ${w.length} keys`)}else g=m;d.items.push(n.createPair(g,y,p))}return d}var c={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:o,createNode:s};e.createPairs=s,e.pairs=c,e.resolvePairs=o}),ds=C(function(e){var t=F(),n=Ke(),r=Ze(),i=We(),o=Yn();class s extends i.YAMLSeq{constructor(){super();this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=s.tag}toJSON(l,a){if(!a)return super.toJSON(l);let p=new Map;if(a?.onCreate)a.onCreate(p);for(let f of this.items){let d,u;if(t.isPair(f))d=n.toJS(f.key,"",a),u=n.toJS(f.value,d,a);else d=n.toJS(f,"",a);if(p.has(d))throw Error("Ordered maps must not include duplicate keys");p.set(d,u)}return p}static from(l,a,p){let f=o.createPairs(l,a,p),d=new this;return d.items=f.items,d}}s.tag="tag:yaml.org,2002:omap";var c={collection:"seq",identify:(l)=>l instanceof Map,nodeClass:s,default:!1,tag:"tag:yaml.org,2002:omap",resolve(l,a){let p=o.resolvePairs(l,a),f=[];for(let{key:d}of p.items)if(t.isScalar(d))if(f.includes(d.value))a(`Ordered maps must not include duplicate keys: ${d.value}`);else f.push(d.value);return Object.assign(new s,p)},createNode:(l,a,p)=>s.from(l,a,p)};e.YAMLOMap=s,e.omap=c}),Pl=C(function(e){var t=se();function n({value:o,source:s},c){if(s&&(o?r:i).test.test(s))return s;return o?c.options.trueStr:c.options.falseStr}var r={identify:(o)=>o===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:(o)=>o===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r}),Ml=C(function(e){var t=se(),n=mt(),r={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(s)=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:n.stringifyNumber},i={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(s)=>parseFloat(s.replace(/_/g,"")),stringify(s){let c=Number(s.value);return isFinite(c)?c.toExponential():n.stringifyNumber(s)}},o={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){let c=new t.Scalar(parseFloat(s.replace(/_/g,""))),l=s.indexOf(".");if(l!==-1){let a=s.substring(l+1).replace(/_/g,"");if(a[a.length-1]==="0")c.minFractionDigits=a.length}return c},stringify:n.stringifyNumber};e.float=o,e.floatExp=i,e.floatNaN=r}),Rl=C(function(e){var t=mt(),n=(a)=>typeof a==="bigint"||Number.isInteger(a);function r(a,p,f,{intAsBigInt:d}){let u=a[0];if(u==="-"||u==="+")p+=1;if(a=a.substring(p).replace(/_/g,""),d){switch(f){case 2:a=`0b${a}`;break;case 8:a=`0o${a}`;break;case 16:a=`0x${a}`;break}let g=BigInt(a);return u==="-"?BigInt(-1)*g:g}let m=parseInt(a,f);return u==="-"?-1*m:m}function i(a,p,f){let{value:d}=a;if(n(d)){let u=d.toString(p);return d<0?"-"+f+u.substr(1):f+u}return t.stringifyNumber(a)}var o={identify:n,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(a,p,f)=>r(a,2,2,f),stringify:(a)=>i(a,2,"0b")},s={identify:n,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(a,p,f)=>r(a,1,8,f),stringify:(a)=>i(a,8,"0")},c={identify:n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(a,p,f)=>r(a,0,10,f),stringify:t.stringifyNumber},l={identify:n,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(a,p,f)=>r(a,2,16,f),stringify:(a)=>i(a,16,"0x")};e.int=c,e.intBin=o,e.intHex=l,e.intOct=s}),fs=C(function(e){var t=F(),n=qe(),r=Ze();class i extends r.YAMLMap{constructor(s){super(s);this.tag=i.tag}add(s){let c;if(t.isPair(s))c=s;else if(s&&typeof s==="object"&&"key"in s&&"value"in s&&s.value===null)c=new n.Pair(s.key,null);else c=new n.Pair(s,null);if(!r.findPair(this.items,c.key))this.items.push(c)}get(s,c){let l=r.findPair(this.items,s);return!c&&t.isPair(l)?t.isScalar(l.key)?l.key.value:l.key:l}set(s,c){if(typeof c!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof c}`);let l=r.findPair(this.items,s);if(l&&!c)this.items.splice(this.items.indexOf(l),1);else if(!l&&c)this.items.push(new n.Pair(s))}toJSON(s,c){return super.toJSON(s,c,Set)}toString(s,c,l){if(!s)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},s,{allNullValues:!0}),c,l);else throw Error("Set items must all have null values")}static from(s,c,l){let{replacer:a}=l,p=new this(s);if(c&&Symbol.iterator in Object(c))for(let f of c){if(typeof a==="function")f=a.call(c,f,f);p.items.push(n.createPair(f,null,l))}return p}}i.tag="tag:yaml.org,2002:set";var o={collection:"map",identify:(s)=>s instanceof Set,nodeClass:i,default:!1,tag:"tag:yaml.org,2002:set",createNode:(s,c,l)=>i.from(s,c,l),resolve(s,c){if(t.isMap(s))if(s.hasAllNullValues(!0))return Object.assign(new i,s);else c("Set items must all have null values");else c("Expected a mapping for this tag");return s}};e.YAMLSet=i,e.set=o}),hs=C(function(e){var t=mt();function n(c,l){let a=c[0],p=a==="-"||a==="+"?c.substring(1):c,f=(u)=>l?BigInt(u):Number(u),d=p.replace(/_/g,"").split(":").reduce((u,m)=>u*f(60)+f(m),f(0));return a==="-"?f(-1)*d:d}function r(c){let{value:l}=c,a=(u)=>u;if(typeof l==="bigint")a=(u)=>BigInt(u);else if(isNaN(l)||!isFinite(l))return t.stringifyNumber(c);let p="";if(l<0)p="-",l*=a(-1);let f=a(60),d=[l%f];if(l<60)d.unshift(0);else if(l=(l-d[0])/f,d.unshift(l%f),l>=60)l=(l-d[0])/f,d.unshift(l);return p+d.map((u)=>String(u).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var i={identify:(c)=>typeof c==="bigint"||Number.isInteger(c),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(c,l,{intAsBigInt:a})=>n(c,a),stringify:r},o={identify:(c)=>typeof c==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(c)=>n(c,!1),stringify:r},s={identify:(c)=>c instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(c){let l=c.match(s.test);if(!l)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,a,p,f,d,u,m]=l.map(Number),g=l[7]?Number((l[7]+"00").substr(1,3)):0,y=Date.UTC(a,p-1,f,d||0,u||0,m||0,g),w=l[8];if(w&&w!=="Z"){let v=n(w,!1);if(Math.abs(v)<30)v*=60;y-=60000*v}return new Date(y)},stringify:({value:c})=>c?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};e.floatTime=o,e.intTime=i,e.timestamp=s}),Ll=C(function(e){var t=ht(),n=Gn(),r=pt(),i=Qt(),o=us(),s=Pl(),c=Ml(),l=Rl(),a=Vn(),p=ds(),f=Yn(),d=fs(),u=hs(),m=[t.map,r.seq,i.string,n.nullTag,s.trueTag,s.falseTag,l.intBin,l.intOct,l.int,l.intHex,c.floatNaN,c.floatExp,c.float,o.binary,a.merge,p.omap,f.pairs,d.set,u.intTime,u.floatTime,u.timestamp];e.schema=m}),xl=C(function(e){var t=ht(),n=Gn(),r=pt(),i=Qt(),o=as(),s=cs(),c=ls(),l=Il(),a=Cl(),p=us(),f=Vn(),d=ds(),u=Yn(),m=Ll(),g=fs(),y=hs(),w=new Map([["core",l.schema],["failsafe",[t.map,r.seq,i.string]],["json",a.schema],["yaml11",m.schema],["yaml-1.1",m.schema]]),v={binary:p.binary,bool:o.boolTag,float:s.float,floatExp:s.floatExp,floatNaN:s.floatNaN,floatTime:y.floatTime,int:c.int,intHex:c.intHex,intOct:c.intOct,intTime:y.intTime,map:t.map,merge:f.merge,null:n.nullTag,omap:d.omap,pairs:u.pairs,seq:r.seq,set:g.set,timestamp:y.timestamp},b={"tag:yaml.org,2002:binary":p.binary,"tag:yaml.org,2002:merge":f.merge,"tag:yaml.org,2002:omap":d.omap,"tag:yaml.org,2002:pairs":u.pairs,"tag:yaml.org,2002:set":g.set,"tag:yaml.org,2002:timestamp":y.timestamp};function k(_,T,A){let N=w.get(T);if(N&&!_)return A&&!N.includes(f.merge)?N.concat(f.merge):N.slice();let I=N;if(!I)if(Array.isArray(_))I=[];else{let O=Array.from(w.keys()).filter((L)=>L!=="yaml11").map((L)=>JSON.stringify(L)).join(", ");throw Error(`Unknown schema "${T}"; use one of ${O} or define customTags array`)}if(Array.isArray(_))for(let O of _)I=I.concat(O);else if(typeof _==="function")I=_(I.slice());if(A)I=I.concat(f.merge);return I.reduce((O,L)=>{let D=typeof L==="string"?v[L]:L;if(!D){let B=JSON.stringify(L),ne=Object.keys(v).map((Y)=>JSON.stringify(Y)).join(", ");throw Error(`Unknown custom tag ${B}; use one of ${ne}`)}if(!O.includes(D))O.push(D);return O},[])}e.coreKnownTags=b,e.getTags=k}),ps=C(function(e){var t=F(),n=ht(),r=pt(),i=Qt(),o=xl(),s=(l,a)=>l.key<a.key?-1:l.key>a.key?1:0;class c{constructor({compat:l,customTags:a,merge:p,resolveKnownTags:f,schema:d,sortMapEntries:u,toStringDefaults:m}){this.compat=Array.isArray(l)?o.getTags(l,"compat"):l?o.getTags(null,l):null,this.name=typeof d==="string"&&d||"core",this.knownTags=f?o.coreKnownTags:{},this.tags=o.getTags(a,this.name,p),this.toStringOptions=m??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof u==="function"?u:u===!0?s:null}clone(){let l=Object.create(c.prototype,Object.getOwnPropertyDescriptors(this));return l.tags=this.tags.slice(),l}}e.Schema=c}),Dl=C(function(e){var t=F(),n=Xt(),r=Gt();function i(o,s){let c=[],l=s.directives===!0;if(s.directives!==!1&&o.directives){let u=o.directives.toString(o);if(u)c.push(u),l=!0;else if(o.directives.docStart)l=!0}if(l)c.push("---");let a=n.createStringifyContext(o,s),{commentString:p}=a.options;if(o.commentBefore){if(c.length!==1)c.unshift("");let u=p(o.commentBefore);c.unshift(r.indentComment(u,""))}let f=!1,d=null;if(o.contents){if(t.isNode(o.contents)){if(o.contents.spaceBefore&&l)c.push("");if(o.contents.commentBefore){let g=p(o.contents.commentBefore);c.push(r.indentComment(g,""))}a.forceBlockIndent=!!o.comment,d=o.contents.comment}let u=d?void 0:()=>f=!0,m=n.stringify(o.contents,a,()=>d=null,u);if(d)m+=r.lineComment(m,"",p(d));if((m[0]==="|"||m[0]===">")&&c[c.length-1]==="---")c[c.length-1]=`--- ${m}`;else c.push(m)}else c.push(n.stringify(o.contents,a));if(o.directives?.docEnd)if(o.comment){let u=p(o.comment);if(u.includes(`
|
|
61
|
+
${u.comment}`:f.comment}f=d}l.items[p]=t.isPair(f)?f:new n.Pair(f)}else a("Expected a sequence for this tag");return l}function s(l,a,p){let{replacer:f}=p,d=new i.YAMLSeq(l);d.tag="tag:yaml.org,2002:pairs";let u=0;if(a&&Symbol.iterator in Object(a))for(let m of a){if(typeof f==="function")m=f.call(a,String(u++),m);let g,y;if(Array.isArray(m))if(m.length===2)g=m[0],y=m[1];else throw TypeError(`Expected [key, value] tuple: ${m}`);else if(m&&m instanceof Object){let w=Object.keys(m);if(w.length===1)g=w[0],y=m[g];else throw TypeError(`Expected tuple with one key, not ${w.length} keys`)}else g=m;d.items.push(n.createPair(g,y,p))}return d}var c={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:o,createNode:s};e.createPairs=s,e.pairs=c,e.resolvePairs=o}),ds=P(function(e){var t=B(),n=qe(),r=We(),i=Je(),o=Yn();class s extends i.YAMLSeq{constructor(){super();this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=s.tag}toJSON(l,a){if(!a)return super.toJSON(l);let p=new Map;if(a?.onCreate)a.onCreate(p);for(let f of this.items){let d,u;if(t.isPair(f))d=n.toJS(f.key,"",a),u=n.toJS(f.value,d,a);else d=n.toJS(f,"",a);if(p.has(d))throw Error("Ordered maps must not include duplicate keys");p.set(d,u)}return p}static from(l,a,p){let f=o.createPairs(l,a,p),d=new this;return d.items=f.items,d}}s.tag="tag:yaml.org,2002:omap";var c={collection:"seq",identify:(l)=>l instanceof Map,nodeClass:s,default:!1,tag:"tag:yaml.org,2002:omap",resolve(l,a){let p=o.resolvePairs(l,a),f=[];for(let{key:d}of p.items)if(t.isScalar(d))if(f.includes(d.value))a(`Ordered maps must not include duplicate keys: ${d.value}`);else f.push(d.value);return Object.assign(new s,p)},createNode:(l,a,p)=>s.from(l,a,p)};e.YAMLOMap=s,e.omap=c}),Ml=P(function(e){var t=oe();function n({value:o,source:s},c){if(s&&(o?r:i).test.test(s))return s;return o?c.options.trueStr:c.options.falseStr}var r={identify:(o)=>o===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:(o)=>o===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r}),Rl=P(function(e){var t=oe(),n=mt(),r={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(s)=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:n.stringifyNumber},i={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(s)=>parseFloat(s.replace(/_/g,"")),stringify(s){let c=Number(s.value);return isFinite(c)?c.toExponential():n.stringifyNumber(s)}},o={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){let c=new t.Scalar(parseFloat(s.replace(/_/g,""))),l=s.indexOf(".");if(l!==-1){let a=s.substring(l+1).replace(/_/g,"");if(a[a.length-1]==="0")c.minFractionDigits=a.length}return c},stringify:n.stringifyNumber};e.float=o,e.floatExp=i,e.floatNaN=r}),Ll=P(function(e){var t=mt(),n=(a)=>typeof a==="bigint"||Number.isInteger(a);function r(a,p,f,{intAsBigInt:d}){let u=a[0];if(u==="-"||u==="+")p+=1;if(a=a.substring(p).replace(/_/g,""),d){switch(f){case 2:a=`0b${a}`;break;case 8:a=`0o${a}`;break;case 16:a=`0x${a}`;break}let g=BigInt(a);return u==="-"?BigInt(-1)*g:g}let m=parseInt(a,f);return u==="-"?-1*m:m}function i(a,p,f){let{value:d}=a;if(n(d)){let u=d.toString(p);return d<0?"-"+f+u.substr(1):f+u}return t.stringifyNumber(a)}var o={identify:n,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(a,p,f)=>r(a,2,2,f),stringify:(a)=>i(a,2,"0b")},s={identify:n,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(a,p,f)=>r(a,1,8,f),stringify:(a)=>i(a,8,"0")},c={identify:n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(a,p,f)=>r(a,0,10,f),stringify:t.stringifyNumber},l={identify:n,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(a,p,f)=>r(a,2,16,f),stringify:(a)=>i(a,16,"0x")};e.int=c,e.intBin=o,e.intHex=l,e.intOct=s}),fs=P(function(e){var t=B(),n=Ze(),r=We();class i extends r.YAMLMap{constructor(s){super(s);this.tag=i.tag}add(s){let c;if(t.isPair(s))c=s;else if(s&&typeof s==="object"&&"key"in s&&"value"in s&&s.value===null)c=new n.Pair(s.key,null);else c=new n.Pair(s,null);if(!r.findPair(this.items,c.key))this.items.push(c)}get(s,c){let l=r.findPair(this.items,s);return!c&&t.isPair(l)?t.isScalar(l.key)?l.key.value:l.key:l}set(s,c){if(typeof c!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof c}`);let l=r.findPair(this.items,s);if(l&&!c)this.items.splice(this.items.indexOf(l),1);else if(!l&&c)this.items.push(new n.Pair(s))}toJSON(s,c){return super.toJSON(s,c,Set)}toString(s,c,l){if(!s)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},s,{allNullValues:!0}),c,l);else throw Error("Set items must all have null values")}static from(s,c,l){let{replacer:a}=l,p=new this(s);if(c&&Symbol.iterator in Object(c))for(let f of c){if(typeof a==="function")f=a.call(c,f,f);p.items.push(n.createPair(f,null,l))}return p}}i.tag="tag:yaml.org,2002:set";var o={collection:"map",identify:(s)=>s instanceof Set,nodeClass:i,default:!1,tag:"tag:yaml.org,2002:set",createNode:(s,c,l)=>i.from(s,c,l),resolve(s,c){if(t.isMap(s))if(s.hasAllNullValues(!0))return Object.assign(new i,s);else c("Set items must all have null values");else c("Expected a mapping for this tag");return s}};e.YAMLSet=i,e.set=o}),hs=P(function(e){var t=mt();function n(c,l){let a=c[0],p=a==="-"||a==="+"?c.substring(1):c,f=(u)=>l?BigInt(u):Number(u),d=p.replace(/_/g,"").split(":").reduce((u,m)=>u*f(60)+f(m),f(0));return a==="-"?f(-1)*d:d}function r(c){let{value:l}=c,a=(u)=>u;if(typeof l==="bigint")a=(u)=>BigInt(u);else if(isNaN(l)||!isFinite(l))return t.stringifyNumber(c);let p="";if(l<0)p="-",l*=a(-1);let f=a(60),d=[l%f];if(l<60)d.unshift(0);else if(l=(l-d[0])/f,d.unshift(l%f),l>=60)l=(l-d[0])/f,d.unshift(l);return p+d.map((u)=>String(u).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var i={identify:(c)=>typeof c==="bigint"||Number.isInteger(c),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(c,l,{intAsBigInt:a})=>n(c,a),stringify:r},o={identify:(c)=>typeof c==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(c)=>n(c,!1),stringify:r},s={identify:(c)=>c instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(c){let l=c.match(s.test);if(!l)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,a,p,f,d,u,m]=l.map(Number),g=l[7]?Number((l[7]+"00").substr(1,3)):0,y=Date.UTC(a,p-1,f,d||0,u||0,m||0,g),w=l[8];if(w&&w!=="Z"){let v=n(w,!1);if(Math.abs(v)<30)v*=60;y-=60000*v}return new Date(y)},stringify:({value:c})=>c?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};e.floatTime=o,e.intTime=i,e.timestamp=s}),xl=P(function(e){var t=ht(),n=Gn(),r=pt(),i=Qt(),o=us(),s=Ml(),c=Rl(),l=Ll(),a=Vn(),p=ds(),f=Yn(),d=fs(),u=hs(),m=[t.map,r.seq,i.string,n.nullTag,s.trueTag,s.falseTag,l.intBin,l.intOct,l.int,l.intHex,c.floatNaN,c.floatExp,c.float,o.binary,a.merge,p.omap,f.pairs,d.set,u.intTime,u.floatTime,u.timestamp];e.schema=m}),Dl=P(function(e){var t=ht(),n=Gn(),r=pt(),i=Qt(),o=as(),s=cs(),c=ls(),l=Cl(),a=Pl(),p=us(),f=Vn(),d=ds(),u=Yn(),m=xl(),g=fs(),y=hs(),w=new Map([["core",l.schema],["failsafe",[t.map,r.seq,i.string]],["json",a.schema],["yaml11",m.schema],["yaml-1.1",m.schema]]),v={binary:p.binary,bool:o.boolTag,float:s.float,floatExp:s.floatExp,floatNaN:s.floatNaN,floatTime:y.floatTime,int:c.int,intHex:c.intHex,intOct:c.intOct,intTime:y.intTime,map:t.map,merge:f.merge,null:n.nullTag,omap:d.omap,pairs:u.pairs,seq:r.seq,set:g.set,timestamp:y.timestamp},b={"tag:yaml.org,2002:binary":p.binary,"tag:yaml.org,2002:merge":f.merge,"tag:yaml.org,2002:omap":d.omap,"tag:yaml.org,2002:pairs":u.pairs,"tag:yaml.org,2002:set":g.set,"tag:yaml.org,2002:timestamp":y.timestamp};function k(_,E,O){let I=w.get(E);if(I&&!_)return O&&!I.includes(f.merge)?I.concat(f.merge):I.slice();let C=I;if(!C)if(Array.isArray(_))C=[];else{let N=Array.from(w.keys()).filter((L)=>L!=="yaml11").map((L)=>JSON.stringify(L)).join(", ");throw Error(`Unknown schema "${E}"; use one of ${N} or define customTags array`)}if(Array.isArray(_))for(let N of _)C=C.concat(N);else if(typeof _==="function")C=_(C.slice());if(O)C=C.concat(f.merge);return C.reduce((N,L)=>{let D=typeof L==="string"?v[L]:L;if(!D){let K=JSON.stringify(L),ne=Object.keys(v).map((Y)=>JSON.stringify(Y)).join(", ");throw Error(`Unknown custom tag ${K}; use one of ${ne}`)}if(!N.includes(D))N.push(D);return N},[])}e.coreKnownTags=b,e.getTags=k}),ps=P(function(e){var t=B(),n=ht(),r=pt(),i=Qt(),o=Dl(),s=(l,a)=>l.key<a.key?-1:l.key>a.key?1:0;class c{constructor({compat:l,customTags:a,merge:p,resolveKnownTags:f,schema:d,sortMapEntries:u,toStringDefaults:m}){this.compat=Array.isArray(l)?o.getTags(l,"compat"):l?o.getTags(null,l):null,this.name=typeof d==="string"&&d||"core",this.knownTags=f?o.coreKnownTags:{},this.tags=o.getTags(a,this.name,p),this.toStringOptions=m??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof u==="function"?u:u===!0?s:null}clone(){let l=Object.create(c.prototype,Object.getOwnPropertyDescriptors(this));return l.tags=this.tags.slice(),l}}e.Schema=c}),jl=P(function(e){var t=B(),n=Xt(),r=Gt();function i(o,s){let c=[],l=s.directives===!0;if(s.directives!==!1&&o.directives){let u=o.directives.toString(o);if(u)c.push(u),l=!0;else if(o.directives.docStart)l=!0}if(l)c.push("---");let a=n.createStringifyContext(o,s),{commentString:p}=a.options;if(o.commentBefore){if(c.length!==1)c.unshift("");let u=p(o.commentBefore);c.unshift(r.indentComment(u,""))}let f=!1,d=null;if(o.contents){if(t.isNode(o.contents)){if(o.contents.spaceBefore&&l)c.push("");if(o.contents.commentBefore){let g=p(o.contents.commentBefore);c.push(r.indentComment(g,""))}a.forceBlockIndent=!!o.comment,d=o.contents.comment}let u=d?void 0:()=>f=!0,m=n.stringify(o.contents,a,()=>d=null,u);if(d)m+=r.lineComment(m,"",p(d));if((m[0]==="|"||m[0]===">")&&c[c.length-1]==="---")c[c.length-1]=`--- ${m}`;else c.push(m)}else c.push(n.stringify(o.contents,a));if(o.directives?.docEnd)if(o.comment){let u=p(o.comment);if(u.includes(`
|
|
62
62
|
`))c.push("..."),c.push(r.indentComment(u,""));else c.push(`... ${u}`)}else c.push("...");else{let u=o.comment;if(u&&f)u=u.replace(/^\n+/,"");if(u){if((!f||d)&&c[c.length-1]!=="")c.push("");c.push(r.indentComment(p(u),""))}}return c.join(`
|
|
63
63
|
`)+`
|
|
64
|
-
`}e.stringifyDocument=i}),en=
|
|
64
|
+
`}e.stringifyDocument=i}),en=P(function(e){var t=Ht(),n=Hn(),r=B(),i=Ze(),o=qe(),s=ps(),c=jl(),l=Wn(),a=rs(),p=Vt(),f=ns();class d{constructor(m,g,y){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let w=null;if(typeof g==="function"||Array.isArray(g))w=g;else if(y===void 0&&g)y=g,g=void 0;let v=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},y);this.options=v;let{version:b}=v;if(y?._directives){if(this.directives=y._directives.atDocument(),this.directives.yaml.explicit)b=this.directives.yaml.version}else this.directives=new f.Directives({version:b});this.setSchema(b,y),this.contents=m===void 0?null:this.createNode(m,w,y)}clone(){let m=Object.create(d.prototype,{[r.NODE_TYPE]:{value:r.DOC}});if(m.commentBefore=this.commentBefore,m.comment=this.comment,m.errors=this.errors.slice(),m.warnings=this.warnings.slice(),m.options=Object.assign({},this.options),this.directives)m.directives=this.directives.clone();if(m.schema=this.schema.clone(),m.contents=r.isNode(this.contents)?this.contents.clone(m.schema):this.contents,this.range)m.range=this.range.slice();return m}add(m){if(u(this.contents))this.contents.add(m)}addIn(m,g){if(u(this.contents))this.contents.addIn(m,g)}createAlias(m,g){if(!m.anchor){let y=l.anchorNames(this);m.anchor=!g||y.has(g)?l.findNewAnchor(g||"a",y):g}return new t.Alias(m.anchor)}createNode(m,g,y){let w=void 0;if(typeof g==="function")m=g.call({"":m},"",m),w=g;else if(Array.isArray(g)){let K=(Y)=>typeof Y==="number"||Y instanceof String||Y instanceof Number,ne=g.filter(K).map(String);if(ne.length>0)g=g.concat(ne);w=g}else if(y===void 0&&g)y=g,g=void 0;let{aliasDuplicateObjects:v,anchorPrefix:b,flow:k,keepUndefined:_,onTagObj:E,tag:O}=y??{},{onAnchor:I,setAnchors:C,sourceObjects:N}=l.createNodeAnchors(this,b||"a"),L={aliasDuplicateObjects:v??!0,keepUndefined:_??!1,onAnchor:I,onTagObj:E,replacer:w,schema:this.schema,sourceObjects:N},D=p.createNode(m,O,L);if(k&&r.isCollection(D))D.flow=!0;return C(),D}createPair(m,g,y={}){let w=this.createNode(m,null,y),v=this.createNode(g,null,y);return new i.Pair(w,v)}delete(m){return u(this.contents)?this.contents.delete(m):!1}deleteIn(m){if(n.isEmptyPath(m)){if(this.contents==null)return!1;return this.contents=null,!0}return u(this.contents)?this.contents.deleteIn(m):!1}get(m,g){return r.isCollection(this.contents)?this.contents.get(m,g):void 0}getIn(m,g){if(n.isEmptyPath(m))return!g&&r.isScalar(this.contents)?this.contents.value:this.contents;return r.isCollection(this.contents)?this.contents.getIn(m,g):void 0}has(m){return r.isCollection(this.contents)?this.contents.has(m):!1}hasIn(m){if(n.isEmptyPath(m))return this.contents!==void 0;return r.isCollection(this.contents)?this.contents.hasIn(m):!1}set(m,g){if(this.contents==null)this.contents=n.collectionFromPath(this.schema,[m],g);else if(u(this.contents))this.contents.set(m,g)}setIn(m,g){if(n.isEmptyPath(m))this.contents=g;else if(this.contents==null)this.contents=n.collectionFromPath(this.schema,Array.from(m),g);else if(u(this.contents))this.contents.setIn(m,g)}setSchema(m,g={}){if(typeof m==="number")m=String(m);let y;switch(m){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new f.Directives({version:"1.1"});y={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=m;else this.directives=new f.Directives({version:m});y={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;y=null;break;default:{let w=JSON.stringify(m);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${w}`)}}if(g.schema instanceof Object)this.schema=g.schema;else if(y)this.schema=new s.Schema(Object.assign(y,g));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:m,jsonArg:g,mapAsMap:y,maxAliasCount:w,onAnchor:v,reviver:b}={}){let k={anchors:new Map,doc:this,keep:!m,mapAsMap:y===!0,mapKeyWarned:!1,maxAliasCount:typeof w==="number"?w:100},_=o.toJS(this.contents,g??"",k);if(typeof v==="function")for(let{count:E,res:O}of k.anchors.values())v(O,E);return typeof b==="function"?a.applyReviver(b,{"":_},"",_):_}toJSON(m,g){return this.toJS({json:!0,jsonArg:m,mapAsMap:!1,onAnchor:g})}toString(m={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in m&&(!Number.isInteger(m.indent)||Number(m.indent)<=0)){let g=JSON.stringify(m.indent);throw Error(`"indent" option must be a positive integer, not ${g}`)}return c.stringifyDocument(this,m)}}function u(m){if(r.isCollection(m))return!0;throw Error("Expected a YAML collection as document contents")}e.Document=d}),tn=P(function(e){class t extends Error{constructor(o,s,c,l){super();this.name=o,this.code=c,this.message=l,this.pos=s}}class n extends t{constructor(o,s,c){super("YAMLParseError",o,s,c)}}class r extends t{constructor(o,s,c){super("YAMLWarning",o,s,c)}}var i=(o,s)=>(c)=>{if(c.pos[0]===-1)return;c.linePos=c.pos.map((d)=>s.linePos(d));let{line:l,col:a}=c.linePos[0];c.message+=` at line ${l}, column ${a}`;let p=a-1,f=o.substring(s.lineStarts[l-1],s.lineStarts[l]).replace(/[\n\r]+$/,"");if(p>=60&&f.length>80){let d=Math.min(p-39,f.length-79);f="…"+f.substring(d),p-=d-1}if(f.length>80)f=f.substring(0,79)+"…";if(l>1&&/^ *$/.test(f.substring(0,p))){let d=o.substring(s.lineStarts[l-2],s.lineStarts[l-1]);if(d.length>80)d=d.substring(0,79)+`…
|
|
65
65
|
`;f=d+f}if(/[^ ]/.test(f)){let d=1,u=c.linePos[1];if(u?.line===l&&u.col>a)d=Math.max(1,Math.min(u.col-a,80-p));let m=" ".repeat(p)+"^".repeat(d);c.message+=`:
|
|
66
66
|
|
|
67
67
|
${f}
|
|
68
68
|
${m}
|
|
69
|
-
`}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=i}),nn=
|
|
70
|
-
`))return!0;if(n.end){for(let r of n.end)if(r.type==="newline")return!0}return!1;case"flow-collection":for(let r of n.items){for(let i of r.start)if(i.type==="newline")return!0;if(r.sep){for(let i of r.sep)if(i.type==="newline")return!0}if(t(r.key)||t(r.value))return!0}return!1;default:return!0}}e.containsNewline=t}),
|
|
71
|
-
`+
|
|
72
|
-
`+D.comment;else L.comment=D.comment;let
|
|
73
|
-
`+U.comment;else _.comment=U.comment;
|
|
74
|
-
`+
|
|
75
|
-
`+
|
|
76
|
-
`+D.comment;else _.comment=D.comment;_.range=[g.offset,L,D.offset]}else _.range=[g.offset,L,L];return _}e.resolveFlowCollection=f}),
|
|
77
|
-
`.repeat(Math.max(1,f.length-1)):"",_=l+a.length;if(s.source)_+=s.source.length;return{value:k,type:p,comment:a.comment,range:[l,_,_]}}let u=s.indent+a.indent,m=s.offset+a.length,g=0;for(let k=0;k<d;++k){let[_,
|
|
78
|
-
`;for(let k=g;k<d;++k){let[_,
|
|
79
|
-
`;else if(_.length>u||
|
|
69
|
+
`}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=i}),nn=P(function(e){function t(n,{flow:r,indicator:i,next:o,offset:s,onError:c,parentIndent:l,startOnNewline:a}){let p=!1,f=a,d=a,u="",m="",g=!1,y=!1,w=null,v=null,b=null,k=null,_=null,E=null,O=null;for(let N of n){if(y){if(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma")c(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");y=!1}if(w){if(f&&N.type!=="comment"&&N.type!=="newline")c(w,"TAB_AS_INDENT","Tabs are not allowed as indentation");w=null}switch(N.type){case"space":if(!r&&(i!=="doc-start"||o?.type!=="flow-collection")&&N.source.includes("\t"))w=N;d=!0;break;case"comment":{if(!d)c(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=N.source.substring(1)||" ";if(!u)u=L;else u+=m+L;m="",f=!1;break}case"newline":if(f){if(u)u+=N.source;else if(!E||i!=="seq-item-ind")p=!0}else m+=N.source;if(f=!0,g=!0,v||b)k=N;d=!0;break;case"anchor":if(v)c(N,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(N.source.endsWith(":"))c(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);v=N,O??(O=N.offset),f=!1,d=!1,y=!0;break;case"tag":{if(b)c(N,"MULTIPLE_TAGS","A node can have at most one tag");b=N,O??(O=N.offset),f=!1,d=!1,y=!0;break}case i:if(v||b)c(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`);if(E)c(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${r??"collection"}`);E=N,f=i==="seq-item-ind"||i==="explicit-key-ind",d=!1;break;case"comma":if(r){if(_)c(N,"UNEXPECTED_TOKEN",`Unexpected , in ${r}`);_=N,f=!1,d=!1;break}default:c(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),f=!1,d=!1}}let I=n[n.length-1],C=I?I.offset+I.source.length:s;if(y&&o&&o.type!=="space"&&o.type!=="newline"&&o.type!=="comma"&&(o.type!=="scalar"||o.source!==""))c(o.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(w&&(f&&w.indent<=l||o?.type==="block-map"||o?.type==="block-seq"))c(w,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:_,found:E,spaceBefore:p,comment:u,hasNewline:g,anchor:v,tag:b,newlineAfterProp:k,end:C,start:O??C}}e.resolveProps=t}),Xn=P(function(e){function t(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`
|
|
70
|
+
`))return!0;if(n.end){for(let r of n.end)if(r.type==="newline")return!0}return!1;case"flow-collection":for(let r of n.items){for(let i of r.start)if(i.type==="newline")return!0;if(r.sep){for(let i of r.sep)if(i.type==="newline")return!0}if(t(r.key)||t(r.value))return!0}return!1;default:return!0}}e.containsNewline=t}),ms=P(function(e){var t=Xn();function n(r,i,o){if(i?.type==="flow-collection"){let s=i.end[0];if(s.indent===r&&(s.source==="]"||s.source==="}")&&t.containsNewline(i))o(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}e.flowIndentCheck=n}),gs=P(function(e){var t=B();function n(r,i,o){let{uniqueKeys:s}=r.options;if(s===!1)return!1;let c=typeof s==="function"?s:(l,a)=>l===a||t.isScalar(l)&&t.isScalar(a)&&l.value===a.value;return i.some((l)=>c(l.key,o))}e.mapIncludes=n}),Ul=P(function(e){var t=Ze(),n=We(),r=nn(),i=Xn(),o=ms(),s=gs(),c="All mapping items must start at the same column";function l({composeNode:a,composeEmptyNode:p},f,d,u,m){let y=new(m?.nodeClass??n.YAMLMap)(f.schema);if(f.atRoot)f.atRoot=!1;let w=d.offset,v=null;for(let b of d.items){let{start:k,key:_,sep:E,value:O}=b,I=r.resolveProps(k,{indicator:"explicit-key-ind",next:_??E?.[0],offset:w,onError:u,parentIndent:d.indent,startOnNewline:!0}),C=!I.found;if(C){if(_){if(_.type==="block-seq")u(w,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in _&&_.indent!==d.indent)u(w,"BAD_INDENT",c)}if(!I.anchor&&!I.tag&&!E){if(v=I.end,I.comment)if(y.comment)y.comment+=`
|
|
71
|
+
`+I.comment;else y.comment=I.comment;continue}if(I.newlineAfterProp||i.containsNewline(_))u(_??k[k.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(I.found?.indent!==d.indent)u(w,"BAD_INDENT",c);f.atKey=!0;let N=I.end,L=_?a(f,_,I,u):p(f,N,k,null,I,u);if(f.schema.compat)o.flowIndentCheck(d.indent,_,u);if(f.atKey=!1,s.mapIncludes(f,y.items,L))u(N,"DUPLICATE_KEY","Map keys must be unique");let D=r.resolveProps(E??[],{indicator:"map-value-ind",next:O,offset:L.range[2],onError:u,parentIndent:d.indent,startOnNewline:!_||_.type==="block-scalar"});if(w=D.end,D.found){if(C){if(O?.type==="block-map"&&!D.hasNewline)u(w,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(f.options.strict&&I.start<D.found.offset-1024)u(L.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let K=O?a(f,O,D,u):p(f,w,E,null,D,u);if(f.schema.compat)o.flowIndentCheck(d.indent,O,u);w=K.range[2];let ne=new t.Pair(L,K);if(f.options.keepSourceTokens)ne.srcToken=b;y.items.push(ne)}else{if(C)u(L.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(D.comment)if(L.comment)L.comment+=`
|
|
72
|
+
`+D.comment;else L.comment=D.comment;let K=new t.Pair(L);if(f.options.keepSourceTokens)K.srcToken=b;y.items.push(K)}}if(v&&v<w)u(v,"IMPOSSIBLE","Map comment with trailing content");return y.range=[d.offset,w,v??w],y}e.resolveBlockMap=l}),zl=P(function(e){var t=Je(),n=nn(),r=ms();function i({composeNode:o,composeEmptyNode:s},c,l,a,p){let d=new(p?.nodeClass??t.YAMLSeq)(c.schema);if(c.atRoot)c.atRoot=!1;if(c.atKey)c.atKey=!1;let u=l.offset,m=null;for(let{start:g,value:y}of l.items){let w=n.resolveProps(g,{indicator:"seq-item-ind",next:y,offset:u,onError:a,parentIndent:l.indent,startOnNewline:!0});if(!w.found)if(w.anchor||w.tag||y)if(y?.type==="block-seq")a(w.end,"BAD_INDENT","All sequence items must start at the same column");else a(u,"MISSING_CHAR","Sequence item without - indicator");else{if(m=w.end,w.comment)d.comment=w.comment;continue}let v=y?o(c,y,w,a):s(c,w.end,g,null,w,a);if(c.schema.compat)r.flowIndentCheck(l.indent,y,a);u=v.range[2],d.items.push(v)}return d.range=[l.offset,u,m??u],d}e.resolveBlockSeq=i}),gt=P(function(e){function t(n,r,i,o){let s="";if(n){let c=!1,l="";for(let a of n){let{source:p,type:f}=a;switch(f){case"space":c=!0;break;case"comment":{if(i&&!c)o(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=p.substring(1)||" ";if(!s)s=d;else s+=l+d;l="";break}case"newline":if(s)l+=p;c=!0;break;default:o(a,"UNEXPECTED_TOKEN",`Unexpected ${f} at node end`)}r+=p.length}}return{comment:s,offset:r}}e.resolveEnd=t}),Fl=P(function(e){var t=B(),n=Ze(),r=We(),i=Je(),o=gt(),s=nn(),c=Xn(),l=gs(),a="Block collections are not allowed within flow collections",p=(d)=>d&&(d.type==="block-map"||d.type==="block-seq");function f({composeNode:d,composeEmptyNode:u},m,g,y,w){let v=g.start.source==="{",b=v?"flow map":"flow sequence",_=new(w?.nodeClass??(v?r.YAMLMap:i.YAMLSeq))(m.schema);_.flow=!0;let E=m.atRoot;if(E)m.atRoot=!1;if(m.atKey)m.atKey=!1;let O=g.offset+g.start.source.length;for(let D=0;D<g.items.length;++D){let K=g.items[D],{start:ne,key:Y,sep:Ee,value:re}=K,U=s.resolveProps(ne,{flow:b,indicator:"explicit-key-ind",next:Y??Ee?.[0],offset:O,onError:y,parentIndent:g.indent,startOnNewline:!1});if(!U.found){if(!U.anchor&&!U.tag&&!Ee&&!re){if(D===0&&U.comma)y(U.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${b}`);else if(D<g.items.length-1)y(U.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${b}`);if(U.comment)if(_.comment)_.comment+=`
|
|
73
|
+
`+U.comment;else _.comment=U.comment;O=U.end;continue}if(!v&&m.options.strict&&c.containsNewline(Y))y(Y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(D===0){if(U.comma)y(U.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${b}`)}else{if(!U.comma)y(U.start,"MISSING_CHAR",`Missing , between ${b} items`);if(U.comment){let ce="";e:for(let V of ne)switch(V.type){case"comma":case"space":break;case"comment":ce=V.source.substring(1);break e;default:break e}if(ce){let V=_.items[_.items.length-1];if(t.isPair(V))V=V.value??V.key;if(V.comment)V.comment+=`
|
|
74
|
+
`+ce;else V.comment=ce;U.comment=U.comment.substring(ce.length+1)}}}if(!v&&!Ee&&!U.found){let ce=re?d(m,re,U,y):u(m,U.end,Ee,null,U,y);if(_.items.push(ce),O=ce.range[2],p(re))y(ce.range,"BLOCK_IN_FLOW",a)}else{m.atKey=!0;let ce=U.end,V=Y?d(m,Y,U,y):u(m,ce,ne,null,U,y);if(p(Y))y(V.range,"BLOCK_IN_FLOW",a);m.atKey=!1;let fe=s.resolveProps(Ee??[],{flow:b,indicator:"map-value-ind",next:re,offset:V.range[2],onError:y,parentIndent:g.indent,startOnNewline:!1});if(fe.found){if(!v&&!U.found&&m.options.strict){if(Ee)for(let Ae of Ee){if(Ae===fe.found)break;if(Ae.type==="newline"){y(Ae,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(U.start<fe.found.offset-1024)y(fe.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(re)if("source"in re&&re.source?.[0]===":")y(re,"MISSING_CHAR",`Missing space after : in ${b}`);else y(fe.start,"MISSING_CHAR",`Missing , or : between ${b} items`);let Ge=re?d(m,re,fe,y):fe.found?u(m,fe.end,Ee,null,fe,y):null;if(Ge){if(p(re))y(Ge.range,"BLOCK_IN_FLOW",a)}else if(fe.comment)if(V.comment)V.comment+=`
|
|
75
|
+
`+fe.comment;else V.comment=fe.comment;let $n=new n.Pair(V,Ge);if(m.options.keepSourceTokens)$n.srcToken=K;if(v){let Ae=_;if(l.mapIncludes(m,Ae.items,V))y(ce,"DUPLICATE_KEY","Map keys must be unique");Ae.items.push($n)}else{let Ae=new r.YAMLMap(m.schema);Ae.flow=!0,Ae.items.push($n);let Zr=(Ge??V).range;Ae.range=[V.range[0],Zr[1],Zr[2]],_.items.push(Ae)}O=Ge?Ge.range[2]:fe.end}}let I=v?"}":"]",[C,...N]=g.end,L=O;if(C?.source===I)L=C.offset+C.source.length;else{let D=b[0].toUpperCase()+b.substring(1),K=E?`${D} must end with a ${I}`:`${D} in block collection must be sufficiently indented and end with a ${I}`;if(y(O,E?"MISSING_CHAR":"BAD_INDENT",K),C&&C.source.length!==1)N.unshift(C)}if(N.length>0){let D=o.resolveEnd(N,L,m.options.strict,y);if(D.comment)if(_.comment)_.comment+=`
|
|
76
|
+
`+D.comment;else _.comment=D.comment;_.range=[g.offset,L,D.offset]}else _.range=[g.offset,L,L];return _}e.resolveFlowCollection=f}),Bl=P(function(e){var t=B(),n=oe(),r=We(),i=Je(),o=Ul(),s=zl(),c=Fl();function l(p,f,d,u,m,g){let y=d.type==="block-map"?o.resolveBlockMap(p,f,d,u,g):d.type==="block-seq"?s.resolveBlockSeq(p,f,d,u,g):c.resolveFlowCollection(p,f,d,u,g),w=y.constructor;if(m==="!"||m===w.tagName)return y.tag=w.tagName,y;if(m)y.tag=m;return y}function a(p,f,d,u,m){let g=u.tag,y=!g?null:f.directives.tagName(g.source,(E)=>m(g,"TAG_RESOLVE_FAILED",E));if(d.type==="block-seq"){let{anchor:E,newlineAfterProp:O}=u,I=E&&g?E.offset>g.offset?E:g:E??g;if(I&&(!O||O.offset<I.offset))m(I,"MISSING_CHAR","Missing newline after block sequence props")}let w=d.type==="block-map"?"map":d.type==="block-seq"?"seq":d.start.source==="{"?"map":"seq";if(!g||!y||y==="!"||y===r.YAMLMap.tagName&&w==="map"||y===i.YAMLSeq.tagName&&w==="seq")return l(p,f,d,m,y);let v=f.schema.tags.find((E)=>E.tag===y&&E.collection===w);if(!v){let E=f.schema.knownTags[y];if(E?.collection===w)f.schema.tags.push(Object.assign({},E,{default:!1})),v=E;else{if(E)m(g,"BAD_COLLECTION_TYPE",`${E.tag} used for ${w} collection, but expects ${E.collection??"scalar"}`,!0);else m(g,"TAG_RESOLVE_FAILED",`Unresolved tag: ${y}`,!0);return l(p,f,d,m,y)}}let b=l(p,f,d,m,y,v),k=v.resolve?.(b,(E)=>m(g,"TAG_RESOLVE_FAILED",E),f.options)??b,_=t.isNode(k)?k:new n.Scalar(k);if(_.range=b.range,_.tag=y,v?.format)_.format=v.format;return _}e.composeCollection=a}),ys=P(function(e){var t=oe();function n(o,s,c){let l=s.offset,a=r(s,o.options.strict,c);if(!a)return{value:"",type:null,comment:"",range:[l,l,l]};let p=a.mode===">"?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,f=s.source?i(s.source):[],d=f.length;for(let k=f.length-1;k>=0;--k){let _=f[k][1];if(_===""||_==="\r")d=k;else break}if(d===0){let k=a.chomp==="+"&&f.length>0?`
|
|
77
|
+
`.repeat(Math.max(1,f.length-1)):"",_=l+a.length;if(s.source)_+=s.source.length;return{value:k,type:p,comment:a.comment,range:[l,_,_]}}let u=s.indent+a.indent,m=s.offset+a.length,g=0;for(let k=0;k<d;++k){let[_,E]=f[k];if(E===""||E==="\r"){if(a.indent===0&&_.length>u)u=_.length}else{if(_.length<u)c(m+_.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(a.indent===0)u=_.length;if(g=k,u===0&&!o.atRoot)c(m,"BAD_INDENT","Block scalar values in collections must be indented");break}m+=_.length+E.length+1}for(let k=f.length-1;k>=d;--k)if(f[k][0].length>u)d=k+1;let y="",w="",v=!1;for(let k=0;k<g;++k)y+=f[k][0].slice(u)+`
|
|
78
|
+
`;for(let k=g;k<d;++k){let[_,E]=f[k];m+=_.length+E.length+1;let O=E[E.length-1]==="\r";if(O)E=E.slice(0,-1);if(E&&_.length<u){let C=`Block scalar lines must not be less indented than their ${a.indent?"explicit indentation indicator":"first line"}`;c(m-E.length-(O?2:1),"BAD_INDENT",C),_=""}if(p===t.Scalar.BLOCK_LITERAL)y+=w+_.slice(u)+E,w=`
|
|
79
|
+
`;else if(_.length>u||E[0]==="\t"){if(w===" ")w=`
|
|
80
80
|
`;else if(!v&&w===`
|
|
81
81
|
`)w=`
|
|
82
82
|
|
|
83
|
-
`;y+=w+_.slice(u)+
|
|
84
|
-
`,v=!0}else if(
|
|
83
|
+
`;y+=w+_.slice(u)+E,w=`
|
|
84
|
+
`,v=!0}else if(E==="")if(w===`
|
|
85
85
|
`)y+=`
|
|
86
86
|
`;else w=`
|
|
87
|
-
`;else y+=w+
|
|
87
|
+
`;else y+=w+E,w=" ",v=!1}switch(a.chomp){case"-":break;case"+":for(let k=d;k<f.length;++k)y+=`
|
|
88
88
|
`+f[k][0].slice(u);if(y[y.length-1]!==`
|
|
89
89
|
`)y+=`
|
|
90
90
|
`;break;default:y+=`
|
|
91
|
-
`}let b=l+a.length+s.source.length;return{value:y,type:p,comment:a.comment,range:[l,b,b]}}function r({offset:o,props:s},c,l){if(s[0].type!=="block-scalar-header")return l(s[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:a}=s[0],p=a[0],f=0,d="",u=-1;for(let w=1;w<a.length;++w){let v=a[w];if(!d&&(v==="-"||v==="+"))d=v;else{let b=Number(v);if(!f&&b)f=b;else if(u===-1)u=o+w}}if(u!==-1)l(u,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${a}`);let m=!1,g="",y=a.length;for(let w=1;w<s.length;++w){let v=s[w];switch(v.type){case"space":m=!0;case"newline":y+=v.source.length;break;case"comment":if(c&&!m)l(v,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");y+=v.source.length,g=v.source.substring(1);break;case"error":l(v,"UNEXPECTED_TOKEN",v.message),y+=v.source.length;break;default:{let b=`Unexpected token in block scalar header: ${v.type}`;l(v,"UNEXPECTED_TOKEN",b);let k=v.source;if(k&&typeof k==="string")y+=k.length}}}return{mode:p,indent:f,chomp:d,comment:g,length:y}}function i(o){let s=o.split(/\n( *)/),c=s[0],l=c.match(/^( *)/),p=[l?.[1]?[l[1],c.slice(l[1].length)]:["",c]];for(let f=1;f<s.length;f+=2)p.push([s[f],s[f+1]]);return p}e.resolveBlockScalar=n}),
|
|
91
|
+
`}let b=l+a.length+s.source.length;return{value:y,type:p,comment:a.comment,range:[l,b,b]}}function r({offset:o,props:s},c,l){if(s[0].type!=="block-scalar-header")return l(s[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:a}=s[0],p=a[0],f=0,d="",u=-1;for(let w=1;w<a.length;++w){let v=a[w];if(!d&&(v==="-"||v==="+"))d=v;else{let b=Number(v);if(!f&&b)f=b;else if(u===-1)u=o+w}}if(u!==-1)l(u,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${a}`);let m=!1,g="",y=a.length;for(let w=1;w<s.length;++w){let v=s[w];switch(v.type){case"space":m=!0;case"newline":y+=v.source.length;break;case"comment":if(c&&!m)l(v,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");y+=v.source.length,g=v.source.substring(1);break;case"error":l(v,"UNEXPECTED_TOKEN",v.message),y+=v.source.length;break;default:{let b=`Unexpected token in block scalar header: ${v.type}`;l(v,"UNEXPECTED_TOKEN",b);let k=v.source;if(k&&typeof k==="string")y+=k.length}}}return{mode:p,indent:f,chomp:d,comment:g,length:y}}function i(o){let s=o.split(/\n( *)/),c=s[0],l=c.match(/^( *)/),p=[l?.[1]?[l[1],c.slice(l[1].length)]:["",c]];for(let f=1;f<s.length;f+=2)p.push([s[f],s[f+1]]);return p}e.resolveBlockScalar=n}),ws=P(function(e){var t=oe(),n=gt();function r(f,d,u){let{offset:m,type:g,source:y,end:w}=f,v,b,k=(O,I,C)=>u(m+O,I,C);switch(g){case"scalar":v=t.Scalar.PLAIN,b=i(y,k);break;case"single-quoted-scalar":v=t.Scalar.QUOTE_SINGLE,b=o(y,k);break;case"double-quoted-scalar":v=t.Scalar.QUOTE_DOUBLE,b=c(y,k);break;default:return u(f,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${g}`),{value:"",type:null,comment:"",range:[m,m+y.length,m+y.length]}}let _=m+y.length,E=n.resolveEnd(w,_,d,u);return{value:b,type:v,comment:E.comment,range:[m,_,E.offset]}}function i(f,d){let u="";switch(f[0]){case"\t":u="a tab character";break;case",":u="flow indicator character ,";break;case"%":u="directive indicator character %";break;case"|":case">":{u=`block scalar indicator ${f[0]}`;break}case"@":case"`":{u=`reserved character ${f[0]}`;break}}if(u)d(0,"BAD_SCALAR_START",`Plain value cannot start with ${u}`);return s(f)}function o(f,d){if(f[f.length-1]!=="'"||f.length===1)d(f.length,"MISSING_CHAR","Missing closing 'quote");return s(f.slice(1,-1)).replace(/''/g,"'")}function s(f){let d,u;try{d=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
92
92
|
`,"sy"),u=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
93
93
|
`,"sy")}catch{d=/(.*?)[ \t]*\r?\n/sy,u=/[ \t]*(.*?)[ \t]*\r?\n/sy}let m=d.exec(f);if(!m)return f;let g=m[1],y=" ",w=d.lastIndex;u.lastIndex=w;while(m=u.exec(f)){if(m[1]==="")if(y===`
|
|
94
94
|
`)g+=y;else y=`
|
|
@@ -103,24 +103,24 @@ ${m}
|
|
|
103
103
|
`)break;if(m===`
|
|
104
104
|
`)u+=`
|
|
105
105
|
`;d+=1,m=f[d+1]}if(!u)u=" ";return{fold:u,offset:d}}var a={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
106
|
-
`,r:"\r",t:"\t",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function p(f,d,u,m){let g=f.substr(d,u),w=g.length===u&&/^[0-9a-fA-F]+$/.test(g)?parseInt(g,16):NaN;try{return String.fromCodePoint(w)}catch{let v=f.substr(d-2,u+2);return m(d-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${v}`),v}}e.resolveFlowScalar=r}),
|
|
106
|
+
`,r:"\r",t:"\t",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function p(f,d,u,m){let g=f.substr(d,u),w=g.length===u&&/^[0-9a-fA-F]+$/.test(g)?parseInt(g,16):NaN;try{return String.fromCodePoint(w)}catch{let v=f.substr(d-2,u+2);return m(d-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${v}`),v}}e.resolveFlowScalar=r}),Kl=P(function(e){var t=B(),n=oe(),r=ys(),i=ws();function o(l,a,p,f){let{value:d,type:u,comment:m,range:g}=a.type==="block-scalar"?r.resolveBlockScalar(l,a,f):i.resolveFlowScalar(a,l.options.strict,f),y=p?l.directives.tagName(p.source,(b)=>f(p,"TAG_RESOLVE_FAILED",b)):null,w;if(l.options.stringKeys&&l.atKey)w=l.schema[t.SCALAR];else if(y)w=s(l.schema,d,y,p,f);else if(a.type==="scalar")w=c(l,d,a,f);else w=l.schema[t.SCALAR];let v;try{let b=w.resolve(d,(k)=>f(p??a,"TAG_RESOLVE_FAILED",k),l.options);v=t.isScalar(b)?b:new n.Scalar(b)}catch(b){let k=b instanceof Error?b.message:String(b);f(p??a,"TAG_RESOLVE_FAILED",k),v=new n.Scalar(d)}if(v.range=g,v.source=d,u)v.type=u;if(y)v.tag=y;if(w.format)v.format=w.format;if(m)v.comment=m;return v}function s(l,a,p,f,d){if(p==="!")return l[t.SCALAR];let u=[];for(let g of l.tags)if(!g.collection&&g.tag===p)if(g.default&&g.test)u.push(g);else return g;for(let g of u)if(g.test?.test(a))return g;let m=l.knownTags[p];if(m&&!m.collection)return l.tags.push(Object.assign({},m,{default:!1,test:void 0})),m;return d(f,"TAG_RESOLVE_FAILED",`Unresolved tag: ${p}`,p!=="tag:yaml.org,2002:str"),l[t.SCALAR]}function c({atKey:l,directives:a,schema:p},f,d,u){let m=p.tags.find((g)=>(g.default===!0||l&&g.default==="key")&&g.test?.test(f))||p[t.SCALAR];if(p.compat){let g=p.compat.find((y)=>y.default&&y.test?.test(f))??p[t.SCALAR];if(m.tag!==g.tag){let y=a.tagString(m.tag),w=a.tagString(g.tag),v=`Value may be parsed as either ${y} or ${w}`;u(d,"TAG_RESOLVE_FAILED",v,!0)}}return m}e.composeScalar=o}),ql=P(function(e){function t(n,r,i){if(r){i??(i=r.length);for(let o=i-1;o>=0;--o){let s=r[o];switch(s.type){case"space":case"comment":case"newline":n-=s.source.length;continue}s=r[++o];while(s?.type==="space")n+=s.source.length,s=r[++o];break}}return n}e.emptyScalarPosition=t}),Zl=P(function(e){var t=Ht(),n=B(),r=Bl(),i=Kl(),o=gt(),s=ql(),c={composeNode:l,composeEmptyNode:a};function l(f,d,u,m){let g=f.atKey,{spaceBefore:y,comment:w,anchor:v,tag:b}=u,k,_=!0;switch(d.type){case"alias":if(k=p(f,d,m),v||b)m(d,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(k=i.composeScalar(f,d,b,m),v)k.anchor=v.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(k=r.composeCollection(c,f,d,u,m),v)k.anchor=v.source.substring(1)}catch(E){let O=E instanceof Error?E.message:String(E);m(d,"RESOURCE_EXHAUSTION",O)}break;default:{let E=d.type==="error"?d.message:`Unsupported token (type: ${d.type})`;m(d,"UNEXPECTED_TOKEN",E),_=!1}}if(k??(k=a(f,d.offset,void 0,null,u,m)),v&&k.anchor==="")m(v,"BAD_ALIAS","Anchor cannot be an empty string");if(g&&f.options.stringKeys&&(!n.isScalar(k)||typeof k.value!=="string"||k.tag&&k.tag!=="tag:yaml.org,2002:str"))m(b??d,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(y)k.spaceBefore=!0;if(w)if(d.type==="scalar"&&d.source==="")k.comment=w;else k.commentBefore=w;if(f.options.keepSourceTokens&&_)k.srcToken=d;return k}function a(f,d,u,m,{spaceBefore:g,comment:y,anchor:w,tag:v,end:b},k){let _={type:"scalar",offset:s.emptyScalarPosition(d,u,m),indent:-1,source:""},E=i.composeScalar(f,_,v,k);if(w){if(E.anchor=w.source.substring(1),E.anchor==="")k(w,"BAD_ALIAS","Anchor cannot be an empty string")}if(g)E.spaceBefore=!0;if(y)E.comment=y,E.range[2]=b;return E}function p({options:f},{offset:d,source:u,end:m},g){let y=new t.Alias(u.substring(1));if(y.source==="")g(d,"BAD_ALIAS","Alias cannot be an empty string");if(y.source.endsWith(":"))g(d+u.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let w=d+u.length,v=o.resolveEnd(m,w,f.strict,g);if(y.range=[d,w,v.offset],v.comment)y.comment=v.comment;return y}e.composeEmptyNode=a,e.composeNode=l}),Wl=P(function(e){var t=en(),n=Zl(),r=gt(),i=nn();function o(s,c,{offset:l,start:a,value:p,end:f},d){let u=Object.assign({_directives:c},s),m=new t.Document(void 0,u),g={atKey:!1,atRoot:!0,directives:m.directives,options:m.options,schema:m.schema},y=i.resolveProps(a,{indicator:"doc-start",next:p??f?.[0],offset:l,onError:d,parentIndent:0,startOnNewline:!0});if(y.found){if(m.directives.docStart=!0,p&&(p.type==="block-map"||p.type==="block-seq")&&!y.hasNewline)d(y.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}m.contents=p?n.composeNode(g,p,y,d):n.composeEmptyNode(g,y.end,a,null,y,d);let w=m.contents.range[2],v=r.resolveEnd(f,w,!1,d);if(v.comment)m.comment=v.comment;return m.range=[l,w,v.offset],m}e.composeDoc=o}),vs=P(function(e){var t=Wt("process"),n=ns(),r=en(),i=tn(),o=B(),s=Wl(),c=gt();function l(f){if(typeof f==="number")return[f,f+1];if(Array.isArray(f))return f.length===2?f:[f[0],f[1]];let{offset:d,source:u}=f;return[d,d+(typeof u==="string"?u.length:1)]}function a(f){let d="",u=!1,m=!1;for(let g=0;g<f.length;++g){let y=f[g];switch(y[0]){case"#":d+=(d===""?"":m?`
|
|
107
107
|
|
|
108
108
|
`:`
|
|
109
109
|
`)+(y.substring(1)||" "),u=!0,m=!1;break;case"%":if(f[g+1]?.[0]!=="#")g+=1;u=!1;break;default:if(!u)m=!0;u=!1}}return{comment:d,afterEmptyLine:m}}class p{constructor(f={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(d,u,m,g)=>{let y=l(d);if(g)this.warnings.push(new i.YAMLWarning(y,u,m));else this.errors.push(new i.YAMLParseError(y,u,m))},this.directives=new n.Directives({version:f.version||"1.2"}),this.options=f}decorate(f,d){let{comment:u,afterEmptyLine:m}=a(this.prelude);if(u){let g=f.contents;if(d)f.comment=f.comment?`${f.comment}
|
|
110
110
|
${u}`:u;else if(m||f.directives.docStart||!g)f.commentBefore=u;else if(o.isCollection(g)&&!g.flow&&g.items.length>0){let y=g.items[0];if(o.isPair(y))y=y.key;let w=y.commentBefore;y.commentBefore=w?`${u}
|
|
111
111
|
${w}`:u}else{let y=g.commentBefore;g.commentBefore=y?`${u}
|
|
112
112
|
${y}`:u}}if(d){for(let g=0;g<this.errors.length;++g)f.errors.push(this.errors[g]);for(let g=0;g<this.warnings.length;++g)f.warnings.push(this.warnings[g])}else f.errors=this.errors,f.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:a(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(f,d=!1,u=-1){for(let m of f)yield*this.next(m);yield*this.end(d,u)}*next(f){if(t.env.LOG_STREAM)console.dir(f,{depth:null});switch(f.type){case"directive":this.directives.add(f.source,(d,u,m)=>{let g=l(f);g[0]+=d,this.onError(g,"BAD_DIRECTIVE",u,m)}),this.prelude.push(f.source),this.atDirectives=!0;break;case"document":{let d=s.composeDoc(this.options,this.directives,f,this.onError);if(this.atDirectives&&!d.directives.docStart)this.onError(f,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(d,!1),this.doc)yield this.doc;this.doc=d,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(f.source);break;case"error":{let d=f.source?`${f.message}: ${JSON.stringify(f.source)}`:f.message,u=new i.YAMLParseError(l(f),"UNEXPECTED_TOKEN",d);if(this.atDirectives||!this.doc)this.errors.push(u);else this.doc.errors.push(u);break}case"doc-end":{if(!this.doc){this.errors.push(new i.YAMLParseError(l(f),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let d=c.resolveEnd(f.end,f.offset+f.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),d.comment){let u=this.doc.comment;this.doc.comment=u?`${u}
|
|
113
|
-
${d.comment}`:d.comment}this.doc.range[2]=d.offset;break}default:this.errors.push(new i.YAMLParseError(l(f),"UNEXPECTED_TOKEN",`Unsupported token ${f.type}`))}}*end(f=!1,d=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(f){let u=Object.assign({_directives:this.directives},this.options),m=new r.Document(void 0,u);if(this.atDirectives)this.onError(d,"MISSING_CHAR","Missing directives-end indicator line");m.range=[0,d,d],this.decorate(m,!1),yield m}}}e.Composer=p}),
|
|
113
|
+
${d.comment}`:d.comment}this.doc.range[2]=d.offset;break}default:this.errors.push(new i.YAMLParseError(l(f),"UNEXPECTED_TOKEN",`Unsupported token ${f.type}`))}}*end(f=!1,d=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(f){let u=Object.assign({_directives:this.directives},this.options),m=new r.Document(void 0,u);if(this.atDirectives)this.onError(d,"MISSING_CHAR","Missing directives-end indicator line");m.range=[0,d,d],this.decorate(m,!1),yield m}}}e.Composer=p}),Jl=P(function(e){var t=ys(),n=ws(),r=tn(),i=Yt();function o(f,d=!0,u){if(f){let m=(g,y,w)=>{let v=typeof g==="number"?g:Array.isArray(g)?g[0]:g.offset;if(u)u(v,y,w);else throw new r.YAMLParseError([v,v+1],y,w)};switch(f.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return n.resolveFlowScalar(f,d,m);case"block-scalar":return t.resolveBlockScalar({options:{strict:d}},f,m)}}return null}function s(f,d){let{implicitKey:u=!1,indent:m,inFlow:g=!1,offset:y=-1,type:w="PLAIN"}=d,v=i.stringifyString({type:w,value:f},{implicitKey:u,indent:m>0?" ".repeat(m):"",inFlow:g,options:{blockQuote:!0,lineWidth:-1}}),b=d.end??[{type:"newline",offset:-1,indent:m,source:`
|
|
114
114
|
`}];switch(v[0]){case"|":case">":{let k=v.indexOf(`
|
|
115
|
-
`),_=v.substring(0,k),
|
|
116
|
-
`,
|
|
117
|
-
`});return{type:"block-scalar",offset:y,indent:m,props:
|
|
115
|
+
`),_=v.substring(0,k),E=v.substring(k+1)+`
|
|
116
|
+
`,O=[{type:"block-scalar-header",offset:y,indent:m,source:_}];if(!a(O,b))O.push({type:"newline",offset:-1,indent:m,source:`
|
|
117
|
+
`});return{type:"block-scalar",offset:y,indent:m,props:O,source:E}}case'"':return{type:"double-quoted-scalar",offset:y,indent:m,source:v,end:b};case"'":return{type:"single-quoted-scalar",offset:y,indent:m,source:v,end:b};default:return{type:"scalar",offset:y,indent:m,source:v,end:b}}}function c(f,d,u={}){let{afterKey:m=!1,implicitKey:g=!1,inFlow:y=!1,type:w}=u,v="indent"in f?f.indent:null;if(m&&typeof v==="number")v+=2;if(!w)switch(f.type){case"single-quoted-scalar":w="QUOTE_SINGLE";break;case"double-quoted-scalar":w="QUOTE_DOUBLE";break;case"block-scalar":{let k=f.props[0];if(k.type!=="block-scalar-header")throw Error("Invalid block scalar header");w=k.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:w="PLAIN"}let b=i.stringifyString({type:w,value:d},{implicitKey:g||v===null,indent:v!==null&&v>0?" ".repeat(v):"",inFlow:y,options:{blockQuote:!0,lineWidth:-1}});switch(b[0]){case"|":case">":l(f,b);break;case'"':p(f,b,"double-quoted-scalar");break;case"'":p(f,b,"single-quoted-scalar");break;default:p(f,b,"scalar")}}function l(f,d){let u=d.indexOf(`
|
|
118
118
|
`),m=d.substring(0,u),g=d.substring(u+1)+`
|
|
119
119
|
`;if(f.type==="block-scalar"){let y=f.props[0];if(y.type!=="block-scalar-header")throw Error("Invalid block scalar header");y.source=m,f.source=g}else{let{offset:y}=f,w="indent"in f?f.indent:-1,v=[{type:"block-scalar-header",offset:y,indent:w,source:m}];if(!a(v,"end"in f?f.end:void 0))v.push({type:"newline",offset:-1,indent:w,source:`
|
|
120
120
|
`});for(let b of Object.keys(f))if(b!=="type"&&b!=="offset")delete f[b];Object.assign(f,{type:"block-scalar",indent:w,props:v,source:g})}}function a(f,d){if(d)for(let u of d)switch(u.type){case"space":case"comment":f.push(u);break;case"newline":return f.push(u),!0}return!1}function p(f,d,u){switch(f.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":f.type=u,f.source=d;break;case"block-scalar":{let m=f.props.slice(1),g=d.length;if(f.props[0].type==="block-scalar-header")g-=f.props[0].source.length;for(let y of m)y.offset+=g;delete f.props,Object.assign(f,{type:u,source:d,end:m});break}case"block-map":case"block-seq":{let g={type:"newline",offset:f.offset+d.length,indent:f.indent,source:`
|
|
121
|
-
`};delete f.items,Object.assign(f,{type:u,source:d,end:[g]});break}default:{let m="indent"in f?f.indent:-1,g="end"in f&&Array.isArray(f.end)?f.end.filter((y)=>y.type==="space"||y.type==="comment"||y.type==="newline"):[];for(let y of Object.keys(f))if(y!=="type"&&y!=="offset")delete f[y];Object.assign(f,{type:u,indent:m,source:d,end:g})}}}e.createScalarToken=s,e.resolveAsScalar=o,e.setScalarValue=c}),
|
|
121
|
+
`};delete f.items,Object.assign(f,{type:u,source:d,end:[g]});break}default:{let m="indent"in f?f.indent:-1,g="end"in f&&Array.isArray(f.end)?f.end.filter((y)=>y.type==="space"||y.type==="comment"||y.type==="newline"):[];for(let y of Object.keys(f))if(y!=="type"&&y!=="offset")delete f[y];Object.assign(f,{type:u,indent:m,source:d,end:g})}}}e.createScalarToken=s,e.resolveAsScalar=o,e.setScalarValue=c}),Hl=P(function(e){var t=(i)=>("type"in i)?n(i):r(i);function n(i){switch(i.type){case"block-scalar":{let o="";for(let s of i.props)o+=n(s);return o+i.source}case"block-map":case"block-seq":{let o="";for(let s of i.items)o+=r(s);return o}case"flow-collection":{let o=i.start.source;for(let s of i.items)o+=r(s);for(let s of i.end)o+=s.source;return o}case"document":{let o=r(i);if(i.end)for(let s of i.end)o+=s.source;return o}default:{let o=i.source;if("end"in i&&i.end)for(let s of i.end)o+=s.source;return o}}}function r({start:i,key:o,sep:s,value:c}){let l="";for(let a of i)l+=a.source;if(o)l+=n(o);if(s)for(let a of s)l+=a.source;if(c)l+=n(c);return l}e.stringify=t}),Vl=P(function(e){var t=Symbol("break visit"),n=Symbol("skip children"),r=Symbol("remove item");function i(s,c){if("type"in s&&s.type==="document")s={start:s.start,value:s.value};o(Object.freeze([]),s,c)}i.BREAK=t,i.SKIP=n,i.REMOVE=r,i.itemAtPath=(s,c)=>{let l=s;for(let[a,p]of c){let f=l?.[a];if(f&&"items"in f)l=f.items[p];else return}return l},i.parentCollection=(s,c)=>{let l=i.itemAtPath(s,c.slice(0,-1)),a=c[c.length-1][0],p=l?.[a];if(p&&"items"in p)return p;throw Error("Parent collection not found")};function o(s,c,l){let a=l(c,s);if(typeof a==="symbol")return a;for(let p of["key","value"]){let f=c[p];if(f&&"items"in f){for(let d=0;d<f.items.length;++d){let u=o(Object.freeze(s.concat([[p,d]])),f.items[d],l);if(typeof u==="number")d=u-1;else if(u===t)return t;else if(u===r)f.items.splice(d,1),d-=1}if(typeof a==="function"&&p==="key")a=a(c,s)}}return typeof a==="function"?a(c,s):a}e.visit=i}),Qn=P(function(e){var t=Jl(),n=Hl(),r=Vl(),i="\uFEFF",o="\x02",s="\x18",c="\x1F",l=(d)=>!!d&&("items"in d),a=(d)=>!!d&&(d.type==="scalar"||d.type==="single-quoted-scalar"||d.type==="double-quoted-scalar"||d.type==="block-scalar");function p(d){switch(d){case i:return"<BOM>";case o:return"<DOC>";case s:return"<FLOW_END>";case c:return"<SCALAR>";default:return JSON.stringify(d)}}function f(d){switch(d){case i:return"byte-order-mark";case o:return"doc-mode";case s:return"flow-error-end";case c:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
122
122
|
`:case`\r
|
|
123
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(d[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=i,e.DOCUMENT=o,e.FLOW_END=s,e.SCALAR=c,e.isCollection=l,e.isScalar=a,e.prettyToken=p,e.tokenType=f}),
|
|
123
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(d[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=i,e.DOCUMENT=o,e.FLOW_END=s,e.SCALAR=c,e.isCollection=l,e.isScalar=a,e.prettyToken=p,e.tokenType=f}),bs=P(function(e){var t=Qn();function n(a){switch(a){case void 0:case" ":case`
|
|
124
124
|
`:case"\r":case"\t":return!0;default:return!1}}var r=new Set("0123456789ABCDEFabcdef"),i=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),o=new Set(",[]{}"),s=new Set(` ,[]{}
|
|
125
125
|
\r `),c=(a)=>!a||s.has(a);class l{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(a,p=!1){if(a){if(typeof a!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+a:a,this.lineEndPos=null}this.atEnd=!p;let f=this.next??"stream";while(f&&(p||this.hasChars(1)))f=yield*this.parseNext(f)}atLineEnd(){let a=this.pos,p=this.buffer[a];while(p===" "||p==="\t")p=this.buffer[++a];if(!p||p==="#"||p===`
|
|
126
126
|
`)return!0;if(p==="\r")return this.buffer[a+1]===`
|
|
@@ -139,13 +139,13 @@ ${d.comment}`:d.comment}this.doc.range[2]=d.offset;break}default:this.errors.pus
|
|
|
139
139
|
`,u=this.buffer[f+1];else p=f;if(u==="#"||a&&o.has(u))break;if(d===`
|
|
140
140
|
`){let m=this.continueScalar(f+1);if(m===-1)break;f=Math.max(f,m-2)}}else{if(a&&o.has(d))break;p=f}if(!d&&!this.atEnd)return this.setNext("plain-scalar");return yield t.SCALAR,yield*this.pushToIndex(p+1,!0),a?"flow":"doc"}*pushCount(a){if(a>0)return yield this.buffer.substr(this.pos,a),this.pos+=a,a;return 0}*pushToIndex(a,p){let f=this.buffer.slice(this.pos,a);if(f)return yield f,this.pos+=f.length,f.length;else if(p)yield"";return 0}*pushIndicators(){let a=0;e:while(!0){switch(this.charAt(0)){case"!":a+=yield*this.pushTag(),a+=yield*this.pushSpaces(!0);continue e;case"&":a+=yield*this.pushUntil(c),a+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let p=this.flowLevel>0,f=this.charAt(1);if(n(f)||p&&o.has(f)){if(!p)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0);continue e}}}break e}return a}*pushTag(){if(this.charAt(1)==="<"){let a=this.pos+2,p=this.buffer[a];while(!n(p)&&p!==">")p=this.buffer[++a];return yield*this.pushToIndex(p===">"?a+1:a,!1)}else{let a=this.pos+1,p=this.buffer[a];while(p)if(i.has(p))p=this.buffer[++a];else if(p==="%"&&r.has(this.buffer[a+1])&&r.has(this.buffer[a+2]))p=this.buffer[a+=3];else break;return yield*this.pushToIndex(a,!1)}}*pushNewline(){let a=this.buffer[this.pos];if(a===`
|
|
141
141
|
`)return yield*this.pushCount(1);else if(a==="\r"&&this.charAt(1)===`
|
|
142
|
-
`)return yield*this.pushCount(2);else return 0}*pushSpaces(a){let p=this.pos-1,f;do f=this.buffer[++p];while(f===" "||a&&f==="\t");let d=p-this.pos;if(d>0)yield this.buffer.substr(this.pos,d),this.pos=p;return d}*pushUntil(a){let p=this.pos,f=this.buffer[p];while(!a(f))f=this.buffer[++p];return yield*this.pushToIndex(p,!1)}}e.Lexer=l}),
|
|
142
|
+
`)return yield*this.pushCount(2);else return 0}*pushSpaces(a){let p=this.pos-1,f;do f=this.buffer[++p];while(f===" "||a&&f==="\t");let d=p-this.pos;if(d>0)yield this.buffer.substr(this.pos,d),this.pos=p;return d}*pushUntil(a){let p=this.pos,f=this.buffer[p];while(!a(f))f=this.buffer[++p];return yield*this.pushToIndex(p,!1)}}e.Lexer=l}),_s=P(function(e){class t{constructor(){this.lineStarts=[],this.addNewLine=(n)=>this.lineStarts.push(n),this.linePos=(n)=>{let r=0,i=this.lineStarts.length;while(r<i){let s=r+i>>1;if(this.lineStarts[s]<n)r=s+1;else i=s}if(this.lineStarts[r]===n)return{line:r+1,col:1};if(r===0)return{line:0,col:n};let o=this.lineStarts[r-1];return{line:r,col:n-o+1}}}}e.LineCounter=t}),ks=P(function(e){var t=Wt("process"),n=Qn(),r=bs();function i(d,u){for(let m=0;m<d.length;++m)if(d[m].type===u)return!0;return!1}function o(d){for(let u=0;u<d.length;++u)switch(d[u].type){case"space":case"comment":case"newline":break;default:return u}return-1}function s(d){switch(d?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function c(d){switch(d.type){case"document":return d.start;case"block-map":{let u=d.items[d.items.length-1];return u.sep??u.start}case"block-seq":return d.items[d.items.length-1].start;default:return[]}}function l(d){if(d.length===0)return[];let u=d.length;e:while(--u>=0)switch(d[u].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}while(d[++u]?.type==="space");return d.splice(u,d.length)}function a(d,u){if(u.length<1e5)Array.prototype.push.apply(d,u);else for(let m=0;m<u.length;++m)d.push(u[m])}function p(d){if(d.start.type==="flow-seq-start"){for(let u of d.items)if(u.sep&&!u.value&&!i(u.start,"explicit-key-ind")&&!i(u.sep,"map-value-ind")){if(u.key)u.value=u.key;if(delete u.key,s(u.value))if(u.value.end)a(u.value.end,u.sep);else u.value.end=u.sep;else a(u.start,u.sep);delete u.sep}}}class f{constructor(d){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new r.Lexer,this.onNewLine=d}*parse(d,u=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let m of this.lexer.lex(d,u))yield*this.next(m);if(!u)yield*this.end()}*next(d){if(this.source=d,t.env.LOG_TOKENS)console.log("|",n.prettyToken(d));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=d.length;return}let u=n.tokenType(d);if(!u){let m=`Not a YAML token: ${d}`;yield*this.pop({type:"error",offset:this.offset,message:m,source:d}),this.offset+=d.length}else if(u==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=u,yield*this.step(),u){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+d.length);break;case"space":if(this.atNewLine&&d[0]===" ")this.indent+=d.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=d.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=d.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let d=this.peek(1);if(this.type==="doc-end"&&d?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!d)return yield*this.stream();switch(d.type){case"document":return yield*this.document(d);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(d);case"block-scalar":return yield*this.blockScalar(d);case"block-map":return yield*this.blockMap(d);case"block-seq":return yield*this.blockSequence(d);case"flow-collection":return yield*this.flowCollection(d);case"doc-end":return yield*this.documentEnd(d)}yield*this.pop()}peek(d){return this.stack[this.stack.length-d]}*pop(d){let u=d??this.stack.pop();if(!u)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield u;else{let m=this.peek(1);if(u.type==="block-scalar")u.indent="indent"in m?m.indent:0;else if(u.type==="flow-collection"&&m.type==="document")u.indent=0;if(u.type==="flow-collection")p(u);switch(m.type){case"document":m.value=u;break;case"block-scalar":m.props.push(u);break;case"block-map":{let g=m.items[m.items.length-1];if(g.value){m.items.push({start:[],key:u,sep:[]}),this.onKeyLine=!0;return}else if(g.sep)g.value=u;else{Object.assign(g,{key:u,sep:[]}),this.onKeyLine=!g.explicitKey;return}break}case"block-seq":{let g=m.items[m.items.length-1];if(g.value)m.items.push({start:[],value:u});else g.value=u;break}case"flow-collection":{let g=m.items[m.items.length-1];if(!g||g.value)m.items.push({start:[],key:u,sep:[]});else if(g.sep)g.value=u;else Object.assign(g,{key:u,sep:[]});return}default:yield*this.pop(),yield*this.pop(u)}if((m.type==="document"||m.type==="block-map"||m.type==="block-seq")&&(u.type==="block-map"||u.type==="block-seq")){let g=u.items[u.items.length-1];if(g&&!g.sep&&!g.value&&g.start.length>0&&o(g.start)===-1&&(u.indent===0||g.start.every((y)=>y.type!=="comment"||y.indent<u.indent))){if(m.type==="document")m.end=g.start;else m.items.push({start:g.start});u.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let d={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")d.start.push(this.sourceToken);this.stack.push(d);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(d){if(d.value)return yield*this.lineEnd(d);switch(this.type){case"doc-start":{if(o(d.start)!==-1)yield*this.pop(),yield*this.step();else d.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":d.start.push(this.sourceToken);return}let u=this.startBlockValue(d);if(u)this.stack.push(u);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(d){if(this.type==="map-value-ind"){let u=c(this.peek(2)),m=l(u),g;if(d.end)g=d.end,g.push(this.sourceToken),delete d.end;else g=[this.sourceToken];let y={type:"block-map",offset:d.offset,indent:d.indent,items:[{start:m,key:d,sep:g}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=y}else yield*this.lineEnd(d)}*blockScalar(d){switch(this.type){case"space":case"comment":case"newline":d.props.push(this.sourceToken);return;case"scalar":if(d.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let u=this.source.indexOf(`
|
|
143
143
|
`)+1;while(u!==0)this.onNewLine(this.offset+u),u=this.source.indexOf(`
|
|
144
144
|
`,u)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(d){let u=d.items[d.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,u.value){let m="end"in u.value?u.value.end:void 0;if((Array.isArray(m)?m[m.length-1]:void 0)?.type==="comment")m?.push(this.sourceToken);else d.items.push({start:[this.sourceToken]})}else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"space":case"comment":if(u.value)d.items.push({start:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else{if(this.atIndentedComment(u.start,d.indent)){let g=d.items[d.items.length-2]?.value?.end;if(Array.isArray(g)){a(g,u.start),g.push(this.sourceToken),d.items.pop();return}}u.start.push(this.sourceToken)}return}if(this.indent>=d.indent){let m=!this.onKeyLine&&this.indent===d.indent,g=m&&(u.sep||u.explicitKey)&&this.type!=="seq-item-ind",y=[];if(g&&u.sep&&!u.value){let w=[];for(let v=0;v<u.sep.length;++v){let b=u.sep[v];switch(b.type){case"newline":w.push(v);break;case"space":break;case"comment":if(b.indent>d.indent)w.length=0;break;default:w.length=0}}if(w.length>=2)y=u.sep.splice(w[1])}switch(this.type){case"anchor":case"tag":if(g||u.value)y.push(this.sourceToken),d.items.push({start:y}),this.onKeyLine=!0;else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"explicit-key-ind":if(!u.sep&&!u.explicitKey)u.start.push(this.sourceToken),u.explicitKey=!0;else if(g||u.value)y.push(this.sourceToken),d.items.push({start:y,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(u.explicitKey)if(!u.sep)if(i(u.start,"newline"))Object.assign(u,{key:null,sep:[this.sourceToken]});else{let w=l(u.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:w,key:null,sep:[this.sourceToken]}]})}else if(u.value)d.items.push({start:[],key:null,sep:[this.sourceToken]});else if(i(u.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:y,key:null,sep:[this.sourceToken]}]});else if(s(u.key)&&!i(u.sep,"newline")){let w=l(u.start),{key:v,sep:b}=u;b.push(this.sourceToken),delete u.key,delete u.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:w,key:v,sep:b}]})}else if(y.length>0)u.sep=u.sep.concat(y,this.sourceToken);else u.sep.push(this.sourceToken);else if(!u.sep)Object.assign(u,{key:null,sep:[this.sourceToken]});else if(u.value||g)d.items.push({start:y,key:null,sep:[this.sourceToken]});else if(i(u.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else u.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let w=this.flowScalar(this.type);if(g||u.value)d.items.push({start:y,key:w,sep:[]}),this.onKeyLine=!0;else if(u.sep)this.stack.push(w);else Object.assign(u,{key:w,sep:[]}),this.onKeyLine=!0;return}default:{let w=this.startBlockValue(d);if(w){if(w.type==="block-seq"){if(!u.explicitKey&&u.sep&&!i(u.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(m)d.items.push({start:y});this.stack.push(w);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(d){let u=d.items[d.items.length-1];switch(this.type){case"newline":if(u.value){let m="end"in u.value?u.value.end:void 0;if((Array.isArray(m)?m[m.length-1]:void 0)?.type==="comment")m?.push(this.sourceToken);else d.items.push({start:[this.sourceToken]})}else u.start.push(this.sourceToken);return;case"space":case"comment":if(u.value)d.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(u.start,d.indent)){let g=d.items[d.items.length-2]?.value?.end;if(Array.isArray(g)){a(g,u.start),g.push(this.sourceToken),d.items.pop();return}}u.start.push(this.sourceToken)}return;case"anchor":case"tag":if(u.value||this.indent<=d.indent)break;u.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==d.indent)break;if(u.value||i(u.start,"seq-item-ind"))d.items.push({start:[this.sourceToken]});else u.start.push(this.sourceToken);return}if(this.indent>d.indent){let m=this.startBlockValue(d);if(m){this.stack.push(m);return}}yield*this.pop(),yield*this.step()}*flowCollection(d){let u=d.items[d.items.length-1];if(this.type==="flow-error-end"){let m;do yield*this.pop(),m=this.peek(1);while(m?.type==="flow-collection")}else if(d.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!u||u.sep)d.items.push({start:[this.sourceToken]});else u.start.push(this.sourceToken);return;case"map-value-ind":if(!u||u.value)d.items.push({start:[],key:null,sep:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else Object.assign(u,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!u||u.value)d.items.push({start:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let g=this.flowScalar(this.type);if(!u||u.value)d.items.push({start:[],key:g,sep:[]});else if(u.sep)this.stack.push(g);else Object.assign(u,{key:g,sep:[]});return}case"flow-map-end":case"flow-seq-end":d.end.push(this.sourceToken);return}let m=this.startBlockValue(d);if(m)this.stack.push(m);else yield*this.pop(),yield*this.step()}else{let m=this.peek(2);if(m.type==="block-map"&&(this.type==="map-value-ind"&&m.indent===d.indent||this.type==="newline"&&!m.items[m.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&m.type!=="flow-collection"){let g=c(m),y=l(g);p(d);let w=d.end.splice(1,d.end.length);w.push(this.sourceToken);let v={type:"block-map",offset:d.offset,indent:d.indent,items:[{start:y,key:d,sep:w}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=v}else yield*this.lineEnd(d)}}flowScalar(d){if(this.onNewLine){let u=this.source.indexOf(`
|
|
145
145
|
`)+1;while(u!==0)this.onNewLine(this.offset+u),u=this.source.indexOf(`
|
|
146
|
-
`,u)+1}return{type:d,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(d){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let u=c(d),m=l(u);return m.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:m,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let u=c(d),m=l(u);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:m,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(d,u){if(this.type!=="comment")return!1;if(this.indent<=u)return!1;return d.every((m)=>m.type==="newline"||m.type==="space")}*documentEnd(d){if(this.type!=="doc-mode"){if(d.end)d.end.push(this.sourceToken);else d.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(d){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(d.end)d.end.push(this.sourceToken);else d.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}e.Parser=f}),
|
|
146
|
+
`,u)+1}return{type:d,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(d){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let u=c(d),m=l(u);return m.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:m,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let u=c(d),m=l(u);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:m,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(d,u){if(this.type!=="comment")return!1;if(this.indent<=u)return!1;return d.every((m)=>m.type==="newline"||m.type==="space")}*documentEnd(d){if(this.type!=="doc-mode"){if(d.end)d.end.push(this.sourceToken);else d.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(d){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(d.end)d.end.push(this.sourceToken);else d.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}e.Parser=f}),Gl=P(function(e){var t=vs(),n=en(),r=tn(),i=is(),o=B(),s=_s(),c=ks();function l(u){let m=u.prettyErrors!==!1;return{lineCounter:u.lineCounter||m&&new s.LineCounter||null,prettyErrors:m}}function a(u,m={}){let{lineCounter:g,prettyErrors:y}=l(m),w=new c.Parser(g?.addNewLine),v=new t.Composer(m),b=Array.from(v.compose(w.parse(u)));if(y&&g)for(let k of b)k.errors.forEach(r.prettifyError(u,g)),k.warnings.forEach(r.prettifyError(u,g));if(b.length>0)return b;return Object.assign([],{empty:!0},v.streamInfo())}function p(u,m={}){let{lineCounter:g,prettyErrors:y}=l(m),w=new c.Parser(g?.addNewLine),v=new t.Composer(m),b=null;for(let k of v.compose(w.parse(u),!0,u.length))if(!b)b=k;else if(b.options.logLevel!=="silent"){b.errors.push(new r.YAMLParseError(k.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(y&&g)b.errors.forEach(r.prettifyError(u,g)),b.warnings.forEach(r.prettifyError(u,g));return b}function f(u,m,g){let y=void 0;if(typeof m==="function")y=m;else if(g===void 0&&m&&typeof m==="object")g=m;let w=p(u,g);if(!w)return null;if(w.warnings.forEach((v)=>i.warn(w.options.logLevel,v)),w.errors.length>0)if(w.options.logLevel!=="silent")throw w.errors[0];else w.errors=[];return w.toJS(Object.assign({reviver:y},g))}function d(u,m,g){let y=null;if(typeof m==="function"||Array.isArray(m))y=m;else if(g===void 0&&m)g=m;if(typeof g==="string")g=g.length;if(typeof g==="number"){let w=Math.round(g);g=w<1?void 0:w>8?{indent:8}:{indent:w}}if(u===void 0){let{keepUndefined:w}=g??m??{};if(!w)return}if(o.isDocument(u)&&!y)return u.toString(g);return new n.Document(u,y,g).toString(g)}e.parse=f,e.parseAllDocuments=a,e.parseDocument=p,e.stringify=d}),Ql="dispach",eu="Dispach",tu=1;function Ss(e,t){return{slug:e,name:t,envPrefix:`${e.toUpperCase()}_`,stateDir:`.${e}`,apiVersion:`${e}/v${tu}`,packageScope:`@${e}`}}var Rt=Ss(Ql,eu),Lt=`${Rt.envPrefix}BRAND`,nu=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;function ru(e){return e.split("-").map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function iu(e){if(e===void 0)return Rt;let t=e.trim();if(t==="")throw Error(`${Lt} is set but empty. hint: unset ${Lt} entirely to use the default brand — an empty value `+'is treated as a mistake rather than as "no override", because a declared-but-unset variable is usually a container passing through a name it never assigned.');if(!nu.test(t))throw Error(`${Lt}="${t}" is not a usable brand slug. hint: the slug becomes an env var prefix, a dot-directory, an npm scope, and the `+"manifest apiVersion, so it must be lowercase alphanumeric with inner hyphens — "+"e.g. acme or acme-run.");if(t===Rt.slug)return Rt;return Ss(t,ru(t))}var er=iu(process.env[Lt]),su=Symbol.for("dispach.HarnessError");class tr extends Error{static ERROR_NAME="HarnessError";code;hint;field;details;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause});if(this.name=new.target.ERROR_NAME??"HarnessError",this[su]=!0,this.code=e.code,this.hint=e.hint,this.field=e.field,e.detail!==void 0)this.detail=e.detail;this.details=e.details??[]}toDetail(){return{code:this.code,message:this.message,hint:this.hint,...this.field===void 0?{}:{field:this.field},...this.detail===void 0?{}:{detail:this.detail},...this.details.length>1?{details:this.details}:{}}}format(){let e=[`${this.code}: ${this.message}`];if(this.field!==void 0)e.push(` field: ${this.field}`);if(e.push(` hint: ${this.hint}`),this.detail!==void 0)e.push(` detail: ${this.detail}`);if(this.details.length===1)return e.join(`
|
|
147
147
|
`);for(let t of this.details){if(e.push(""),e.push(` ${t.code}: ${t.message}`),t.field!==void 0)e.push(` field: ${t.field}`);e.push(` hint: ${t.hint}`)}return e.join(`
|
|
148
|
-
`)}}class Fn extends tr{static ERROR_NAME="ConfigError"}class
|
|
148
|
+
`)}}class Fn extends tr{static ERROR_NAME="ConfigError"}class rt extends tr{static ERROR_NAME="ToolError"}function ou(e,t){return new rt({code:"workspace_not_editable",message:`${e} is declared editable: ${t}, so it cannot be written to.`,hint:"Point the write at a volatile file whose frontmatter allows it (editable: append or replace), or change that file's frontmatter. Read-only identity is deliberate — it is the most effective known mitigation for persona drift, so this refuses rather than silently doing nothing."})}function au(){return new rt({code:"memory_forget_arguments",message:"memory_forget needs either `query` or `ids`, not both and not neither.",hint:"Call it with `query` first to see what matches, show the person, then call it again with the `ids` they confirm."})}function cu(){return new rt({code:"memory_forget_unavailable",message:"Memory cannot be changed from here: nothing runs turns in this context.",hint:"memory_forget works inside a turn of a running agent."})}function lu(){return new rt({code:"artifact_unavailable",message:"This runtime has no artifact store, so a compacted observation cannot be read back.",hint:"artifact_read only works inside a session backed by a store. If you are seeing a compaction pointer without one, the pointer was written by a different process — report the text of the pointer rather than guessing at what it replaced."})}function uu(e){return new rt({code:"artifact_not_found",message:`No compacted observation is stored under ${JSON.stringify(e)} in this conversation.`,hint:"Copy the id exactly from the pointer in the conversation — it is not guessable and it is scoped to this conversation. If the pointer came from a session you have since switched away from, the observation is not reachable from here."})}var rk="What I already know, carried from before this conversation and kept current. "+"Not a transcript — these are standing facts about the person I work for and my own working notes. "+"If they ask what I know or remember about them, this is the answer.",Oe=(e)=>String.fromCharCode(e),et=Oe(27),$s=Oe(7),ik=new RegExp(`${et}\\[[0-?]*[ -/]*[@-~]`,"g"),sk=new RegExp(`${et}\\][\\s\\S]*?(?:${$s}|${et}\\\\|$)`,"g"),ok=new RegExp(`${et}[P^_X][\\s\\S]*?(?:${et}\\\\|${$s}|$)`,"g"),ak=new RegExp(`${et}[@-Z\\\\-_0-9=><]?`,"g"),ck=new RegExp(`[${Oe(128)}-${Oe(159)}]`,"g"),lk=new RegExp(`[${Oe(0)}-${Oe(8)}${Oe(11)}${Oe(12)}${Oe(14)}-${Oe(31)}${Oe(127)}]`,"g");function du(e){return e==="untrusted"?"obu":"obs"}function fu(e){return e.startsWith(`${du("untrusted")}_`)?"untrusted":"trusted"}var hu=3.8;function pu(e){if(e==="")return 0;let t=0;for(let n=0;n<e.length;n+=1)if(e.charCodeAt(n)===10)t+=1;return Math.ceil(e.length/hu)+t}var mu="<<<",gu=">>>",uk=`# Tools
|
|
149
149
|
|
|
150
150
|
To use a tool, write an ACTION block. Start each line at the left margin, exactly like this:
|
|
151
151
|
|
|
@@ -159,16 +159,16 @@ every field name from that list, spelled exactly as it is written there.
|
|
|
159
159
|
|
|
160
160
|
Rules for a block:
|
|
161
161
|
- One field per line, written as \`name: value\`, where \`name\` is one of that tool's own field names.
|
|
162
|
-
- For a value spanning several lines, open it with \`${
|
|
162
|
+
- For a value spanning several lines, open it with \`${mu}\` and close it with \`${gu}\` alone on its own line.
|
|
163
163
|
- Finish every block with \`END\` alone on its own line.
|
|
164
164
|
- Several blocks are allowed. They run in the order you write them.
|
|
165
165
|
- Use only the tools listed below, only their listed fields, and always give every required field.
|
|
166
166
|
|
|
167
167
|
Anything you write outside a block is shown to the person you are talking to, so keep explanations
|
|
168
168
|
short and keep them out of the block. When no tool fits, simply reply — never invent a tool, and
|
|
169
|
-
never guess a value for a required field you have not been given.`,vi;function E(e,t,n){function r(c,l){if(!c._zod)Object.defineProperty(c,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1});if(c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);let a=s.prototype,p=Object.keys(a);for(let f=0;f<p.length;f++){let d=p[f];if(!(d in c))c[d]=a[d].bind(c)}}let i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(c){var l;let a=n?.Parent?new o:this;r(a,c),(l=a._zod).deferred??(l.deferred=[]);for(let p of a._zod.deferred)p();return a}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:(c)=>{if(n?.Parent&&c instanceof n.Parent)return!0;return c?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var ak=Symbol("zod_brand");class ze extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class nr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(vi=globalThis).__zod_globalConfig??(vi.__zod_globalConfig={});var xt=globalThis.__zod_globalConfig;function Me(e){if(e)Object.assign(xt,e);return xt}function As(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function Bn(e,t){if(typeof t==="bigint")return t.toString();return t}function rr(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function ir(e){return e===null||e===void 0}function sr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function gu(e,t){let n=e/t,r=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<i)return 0;return n-r}var bi=Symbol("evaluating");function z(e,t,n){let r=void 0;Object.defineProperty(e,t,{get(){if(r===bi)return;if(r===void 0)r=bi,r=n();return r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Je(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Le(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function _i(e){return JSON.stringify(e)}function yu(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Os="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Dt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var wu=rr(()=>{if(xt.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function tt(e){if(Dt(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(Dt(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Ns(e){if(tt(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var vu=new Set(["string","number","symbol"]);function nt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xe(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function M(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function bu(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var _u={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ku(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let o=Le(e._zod.def,{get shape(){let s={};for(let c in t){if(!(c in n.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;s[c]=n.shape[c]}return Je(this,"shape",s),s},checks:[]});return xe(e,o)}function Su(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let o=Le(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let c in t){if(!(c in n.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;delete s[c]}return Je(this,"shape",s),s},checks:[]});return xe(e,o)}function Tu(e,t){if(!tt(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=Le(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return Je(this,"shape",o),o}});return xe(e,i)}function $u(e,t){if(!tt(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=Le(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return Je(this,"shape",r),r}});return xe(e,n)}function Eu(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Le(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Je(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return xe(e,n)}function Au(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=Le(t._zod.def,{get shape(){let c=t._zod.def.shape,l={...c};if(n)for(let a in n){if(!(a in c))throw Error(`Unrecognized key: "${a}"`);if(!n[a])continue;l[a]=e?new e({type:"optional",innerType:c[a]}):c[a]}else for(let a in c)l[a]=e?new e({type:"optional",innerType:c[a]}):c[a];return Je(this,"shape",l),l},checks:[]});return xe(t,s)}function Ou(e,t,n){let r=Le(t._zod.def,{get shape(){let i=t._zod.def.shape,o={...i};if(n)for(let s in n){if(!(s in o))throw Error(`Unrecognized key: "${s}"`);if(!n[s])continue;o[s]=new e({type:"nonoptional",innerType:i[s]})}else for(let s in i)o[s]=new e({type:"nonoptional",innerType:i[s]});return Je(this,"shape",o),o}});return xe(t,r)}function Xe(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Nu(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Qe(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Nt(e){return typeof e==="string"?e:e?.message}function Re(e,t,n){let r=e.message?e.message:Nt(e.inst?._zod.def?.error?.(e))??Nt(t?.error?.(e))??Nt(n.customError?.(e))??Nt(n.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:s,...c}=e;if(c.path??(c.path=[]),c.message=r,t?.reportInput)c.input=s;return c}function or(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function ft(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}var Is=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Bn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Cs=E("$ZodError",Is),Ps=E("$ZodError",Is,{Parent:Error});function Iu(e,t=(n)=>n.message){let n={},r=[];for(let i of e.issues)if(i.path.length>0)n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i));else r.push(t(i));return{formErrors:r,fieldErrors:n}}function Cu(e,t=(n)=>n.message){let n={_errors:[]},r=(i,o=[])=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((c)=>r({issues:c},[...o,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...o,...s.path]);else{let c=[...o,...s.path];if(c.length===0)n._errors.push(t(s));else{let l=n,a=0;while(a<c.length){let p=c[a];if(a!==c.length-1)l[p]=l[p]||{_errors:[]};else l[p]=l[p]||{_errors:[]},l[p]._errors.push(t(s));l=l[p],a++}}}};return r(e),n}var ar=(e)=>(t,n,r,i)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new ze;if(s.issues.length){let c=new(i?.Err??e)(s.issues.map((l)=>Re(l,o,Me())));throw Os(c,i?.callee),c}return s.value},cr=(e)=>async(t,n,r,i)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)s=await s;if(s.issues.length){let c=new(i?.Err??e)(s.issues.map((l)=>Re(l,o,Me())));throw Os(c,i?.callee),c}return s.value},rn=(e)=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new ze;return o.issues.length?{success:!1,error:new(e??Cs)(o.issues.map((s)=>Re(s,i,Me())))}:{success:!0,data:o.value}},Pu=rn(Ps),sn=(e)=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)o=await o;return o.issues.length?{success:!1,error:new e(o.issues.map((s)=>Re(s,i,Me())))}:{success:!0,data:o.value}},Mu=sn(Ps),Ru=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return ar(e)(t,n,i)},Lu=(e)=>(t,n,r)=>ar(e)(t,n,r),xu=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return cr(e)(t,n,i)},Du=(e)=>async(t,n,r)=>cr(e)(t,n,r),ju=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return rn(e)(t,n,i)},Uu=(e)=>(t,n,r)=>rn(e)(t,n,r),zu=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return sn(e)(t,n,i)},Fu=(e)=>async(t,n,r)=>sn(e)(t,n,r),Bu=/^[cC][0-9a-z]{6,}$/,Ku=/^[0-9a-z]+$/,qu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Zu=/^[0-9a-vA-V]{20}$/,Wu=/^[A-Za-z0-9]{27}$/,Ju=/^[a-zA-Z0-9_-]{21}$/,Hu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Vu=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ki=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Gu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Yu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Xu(){return new RegExp(Yu,"u")}var Qu=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ed=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,td=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,nd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,rd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ms=/^[A-Za-z0-9_-]*$/,id=/^https?$/,sd=/^\+[1-9]\d{6,14}$/,Rs="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",od=new RegExp(`^${Rs}$`);function Ls(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function ad(e){return new RegExp(`^${Ls(e)}$`)}function cd(e){let t=Ls({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Rs}T(?:${r})$`)}var ld=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},ud=/^-?\d+$/,xs=/^-?\d+(?:\.\d+)?$/,dd=/^(?:true|false)$/i,fd=/^[^A-Z]*$/,hd=/^[^a-z]*$/,me=E("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ds={number:"number",bigint:"bigint",object:"date"},js=E("$ZodCheckLessThan",(e,t)=>{me.init(e,t);let n=Ds[typeof t.value];e._zod.onattach.push((r)=>{let i=r._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<o)if(t.inclusive)i.maximum=t.value;else i.exclusiveMaximum=t.value}),e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Us=E("$ZodCheckGreaterThan",(e,t)=>{me.init(e,t);let n=Ds[typeof t.value];e._zod.onattach.push((r)=>{let i=r._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>o)if(t.inclusive)i.minimum=t.value;else i.exclusiveMinimum=t.value}),e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),pd=E("$ZodCheckMultipleOf",(e,t)=>{me.init(e,t),e._zod.onattach.push((n)=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):gu(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),md=E("$ZodCheckNumberFormat",(e,t)=>{me.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=_u[t.format];e._zod.onattach.push((s)=>{let c=s._zod.bag;if(c.format=t.format,c.minimum=i,c.maximum=o,n)c.pattern=ud}),e._zod.check=(s)=>{let c=s.value;if(n){if(!Number.isInteger(c)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){if(c>0)s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(c<i)s.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort});if(c>o)s.issues.push({origin:"number",input:c,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),gd=E("$ZodCheckMaxLength",(e,t)=>{var n;me.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!ir(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<i)r._zod.bag.maximum=t.maximum}),e._zod.check=(r)=>{let i=r.value;if(i.length<=t.maximum)return;let s=or(i);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),yd=E("$ZodCheckMinLength",(e,t)=>{var n;me.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!ir(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>i)r._zod.bag.minimum=t.minimum}),e._zod.check=(r)=>{let i=r.value;if(i.length>=t.minimum)return;let s=or(i);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wd=E("$ZodCheckLengthEquals",(e,t)=>{var n;me.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!ir(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=(r)=>{let i=r.value,o=i.length;if(o===t.length)return;let s=or(i),c=o>t.length;r.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),on=E("$ZodCheckStringFormat",(e,t)=>{var n,r;if(me.init(e,t),e._zod.onattach.push((i)=>{let o=i._zod.bag;if(o.format=t.format,t.pattern)o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(i)=>{if(t.pattern.lastIndex=0,t.pattern.test(i.value))return;i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),vd=E("$ZodCheckRegex",(e,t)=>{on.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),bd=E("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=fd),on.init(e,t)}),_d=E("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=hd),on.init(e,t)}),kd=E("$ZodCheckIncludes",(e,t)=>{me.init(e,t);let n=nt(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push((i)=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(i)=>{if(i.value.includes(t.includes,t.position))return;i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Sd=E("$ZodCheckStartsWith",(e,t)=>{me.init(e,t);let n=new RegExp(`^${nt(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Td=E("$ZodCheckEndsWith",(e,t)=>{me.init(e,t);let n=new RegExp(`.*${nt(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),$d=E("$ZodCheckOverwrite",(e,t)=>{me.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class zs{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
169
|
+
never guess a value for a required field you have not been given.`,vi;function A(e,t,n){function r(c,l){if(!c._zod)Object.defineProperty(c,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1});if(c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);let a=s.prototype,p=Object.keys(a);for(let f=0;f<p.length;f++){let d=p[f];if(!(d in c))c[d]=a[d].bind(c)}}let i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(c){var l;let a=n?.Parent?new o:this;r(a,c),(l=a._zod).deferred??(l.deferred=[]);for(let p of a._zod.deferred)p();return a}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:(c)=>{if(n?.Parent&&c instanceof n.Parent)return!0;return c?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var dk=Symbol("zod_brand");class Fe extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class nr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(vi=globalThis).__zod_globalConfig??(vi.__zod_globalConfig={});var xt=globalThis.__zod_globalConfig;function Me(e){if(e)Object.assign(xt,e);return xt}function Es(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function Bn(e,t){if(typeof t==="bigint")return t.toString();return t}function rr(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function ir(e){return e===null||e===void 0}function sr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function yu(e,t){let n=e/t,r=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<i)return 0;return n-r}var bi=Symbol("evaluating");function F(e,t,n){let r=void 0;Object.defineProperty(e,t,{get(){if(r===bi)return;if(r===void 0)r=bi,r=n();return r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function He(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Le(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function _i(e){return JSON.stringify(e)}function wu(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var As="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Dt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var vu=rr(()=>{if(xt.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function tt(e){if(Dt(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(Dt(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Os(e){if(tt(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var bu=new Set(["string","number","symbol"]);function nt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function De(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function R(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function _u(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var ku={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Su(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let o=Le(e._zod.def,{get shape(){let s={};for(let c in t){if(!(c in n.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;s[c]=n.shape[c]}return He(this,"shape",s),s},checks:[]});return De(e,o)}function Tu(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let o=Le(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let c in t){if(!(c in n.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;delete s[c]}return He(this,"shape",s),s},checks:[]});return De(e,o)}function $u(e,t){if(!tt(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=Le(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return He(this,"shape",o),o}});return De(e,i)}function Eu(e,t){if(!tt(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=Le(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return He(this,"shape",r),r}});return De(e,n)}function Au(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Le(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return He(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return De(e,n)}function Ou(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=Le(t._zod.def,{get shape(){let c=t._zod.def.shape,l={...c};if(n)for(let a in n){if(!(a in c))throw Error(`Unrecognized key: "${a}"`);if(!n[a])continue;l[a]=e?new e({type:"optional",innerType:c[a]}):c[a]}else for(let a in c)l[a]=e?new e({type:"optional",innerType:c[a]}):c[a];return He(this,"shape",l),l},checks:[]});return De(t,s)}function Nu(e,t,n){let r=Le(t._zod.def,{get shape(){let i=t._zod.def.shape,o={...i};if(n)for(let s in n){if(!(s in o))throw Error(`Unrecognized key: "${s}"`);if(!n[s])continue;o[s]=new e({type:"nonoptional",innerType:i[s]})}else for(let s in i)o[s]=new e({type:"nonoptional",innerType:i[s]});return He(this,"shape",o),o}});return De(t,r)}function Xe(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Iu(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Qe(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Nt(e){return typeof e==="string"?e:e?.message}function Re(e,t,n){let r=e.message?e.message:Nt(e.inst?._zod.def?.error?.(e))??Nt(t?.error?.(e))??Nt(n.customError?.(e))??Nt(n.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:s,...c}=e;if(c.path??(c.path=[]),c.message=r,t?.reportInput)c.input=s;return c}function or(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function ft(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}var Is=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Bn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Cs=A("$ZodError",Is),Ps=A("$ZodError",Is,{Parent:Error});function Cu(e,t=(n)=>n.message){let n={},r=[];for(let i of e.issues)if(i.path.length>0)n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i));else r.push(t(i));return{formErrors:r,fieldErrors:n}}function Pu(e,t=(n)=>n.message){let n={_errors:[]},r=(i,o=[])=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((c)=>r({issues:c},[...o,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...o,...s.path]);else{let c=[...o,...s.path];if(c.length===0)n._errors.push(t(s));else{let l=n,a=0;while(a<c.length){let p=c[a];if(a!==c.length-1)l[p]=l[p]||{_errors:[]};else l[p]=l[p]||{_errors:[]},l[p]._errors.push(t(s));l=l[p],a++}}}};return r(e),n}var ar=(e)=>(t,n,r,i)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Fe;if(s.issues.length){let c=new(i?.Err??e)(s.issues.map((l)=>Re(l,o,Me())));throw As(c,i?.callee),c}return s.value},cr=(e)=>async(t,n,r,i)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)s=await s;if(s.issues.length){let c=new(i?.Err??e)(s.issues.map((l)=>Re(l,o,Me())));throw As(c,i?.callee),c}return s.value},rn=(e)=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Fe;return o.issues.length?{success:!1,error:new(e??Cs)(o.issues.map((s)=>Re(s,i,Me())))}:{success:!0,data:o.value}},Mu=rn(Ps),sn=(e)=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)o=await o;return o.issues.length?{success:!1,error:new e(o.issues.map((s)=>Re(s,i,Me())))}:{success:!0,data:o.value}},Ru=sn(Ps),Lu=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return ar(e)(t,n,i)},xu=(e)=>(t,n,r)=>ar(e)(t,n,r),Du=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return cr(e)(t,n,i)},ju=(e)=>async(t,n,r)=>cr(e)(t,n,r),Uu=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return rn(e)(t,n,i)},zu=(e)=>(t,n,r)=>rn(e)(t,n,r),Fu=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return sn(e)(t,n,i)},Bu=(e)=>async(t,n,r)=>sn(e)(t,n,r),Ku=/^[cC][0-9a-z]{6,}$/,qu=/^[0-9a-z]+$/,Zu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Wu=/^[0-9a-vA-V]{20}$/,Ju=/^[A-Za-z0-9]{27}$/,Hu=/^[a-zA-Z0-9_-]{21}$/,Vu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Gu=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ki=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Yu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Xu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Qu(){return new RegExp(Xu,"u")}var ed=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,td=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,nd=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,rd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,id=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Rs=/^[A-Za-z0-9_-]*$/,sd=/^https?$/,od=/^\+[1-9]\d{6,14}$/,Ls="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ad=new RegExp(`^${Ls}$`);function xs(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function cd(e){return new RegExp(`^${xs(e)}$`)}function ld(e){let t=xs({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Ls}T(?:${r})$`)}var ud=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},dd=/^-?\d+$/,Ds=/^-?\d+(?:\.\d+)?$/,fd=/^(?:true|false)$/i,hd=/^[^A-Z]*$/,pd=/^[^a-z]*$/,ge=A("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),js={number:"number",bigint:"bigint",object:"date"},Us=A("$ZodCheckLessThan",(e,t)=>{ge.init(e,t);let n=js[typeof t.value];e._zod.onattach.push((r)=>{let i=r._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<o)if(t.inclusive)i.maximum=t.value;else i.exclusiveMaximum=t.value}),e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),zs=A("$ZodCheckGreaterThan",(e,t)=>{ge.init(e,t);let n=js[typeof t.value];e._zod.onattach.push((r)=>{let i=r._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>o)if(t.inclusive)i.minimum=t.value;else i.exclusiveMinimum=t.value}),e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),md=A("$ZodCheckMultipleOf",(e,t)=>{ge.init(e,t),e._zod.onattach.push((n)=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):yu(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),gd=A("$ZodCheckNumberFormat",(e,t)=>{ge.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=ku[t.format];e._zod.onattach.push((s)=>{let c=s._zod.bag;if(c.format=t.format,c.minimum=i,c.maximum=o,n)c.pattern=dd}),e._zod.check=(s)=>{let c=s.value;if(n){if(!Number.isInteger(c)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){if(c>0)s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(c<i)s.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort});if(c>o)s.issues.push({origin:"number",input:c,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),yd=A("$ZodCheckMaxLength",(e,t)=>{var n;ge.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!ir(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<i)r._zod.bag.maximum=t.maximum}),e._zod.check=(r)=>{let i=r.value;if(i.length<=t.maximum)return;let s=or(i);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wd=A("$ZodCheckMinLength",(e,t)=>{var n;ge.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!ir(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>i)r._zod.bag.minimum=t.minimum}),e._zod.check=(r)=>{let i=r.value;if(i.length>=t.minimum)return;let s=or(i);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),vd=A("$ZodCheckLengthEquals",(e,t)=>{var n;ge.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!ir(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=(r)=>{let i=r.value,o=i.length;if(o===t.length)return;let s=or(i),c=o>t.length;r.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),on=A("$ZodCheckStringFormat",(e,t)=>{var n,r;if(ge.init(e,t),e._zod.onattach.push((i)=>{let o=i._zod.bag;if(o.format=t.format,t.pattern)o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(i)=>{if(t.pattern.lastIndex=0,t.pattern.test(i.value))return;i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),bd=A("$ZodCheckRegex",(e,t)=>{on.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),_d=A("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=hd),on.init(e,t)}),kd=A("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=pd),on.init(e,t)}),Sd=A("$ZodCheckIncludes",(e,t)=>{ge.init(e,t);let n=nt(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push((i)=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(i)=>{if(i.value.includes(t.includes,t.position))return;i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Td=A("$ZodCheckStartsWith",(e,t)=>{ge.init(e,t);let n=new RegExp(`^${nt(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),$d=A("$ZodCheckEndsWith",(e,t)=>{ge.init(e,t);let n=new RegExp(`.*${nt(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Ed=A("$ZodCheckOverwrite",(e,t)=>{ge.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Fs{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
170
170
|
`).filter((o)=>o),r=Math.min(...n.map((o)=>o.length-o.trimStart().length)),i=n.map((o)=>o.slice(r)).map((o)=>" ".repeat(this.indent*2)+o);for(let o of i)this.content.push(o)}compile(){let e=Function,t=this?.args,r=[...(this?.content??[""]).map((i)=>` ${i}`)];return new e(...t,r.join(`
|
|
171
|
-
`))}}var
|
|
171
|
+
`))}}var Ad={major:4,minor:4,patch:3},Z=A("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ad;let r=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))r.unshift(e);for(let i of r)for(let o of i._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,c,l)=>{let a=Xe(s),p;for(let f of c){if(f._zod.def.when){if(Iu(s))continue;if(!f._zod.def.when(s))continue}else if(a)continue;let d=s.issues.length,u=f._zod.check(s);if(u instanceof Promise&&l?.async===!1)throw new Fe;if(p||u instanceof Promise)p=(p??Promise.resolve()).then(async()=>{if(await u,s.issues.length===d)return;if(!a)a=Xe(s,d)});else{if(s.issues.length===d)continue;if(!a)a=Xe(s,d)}}if(p)return p.then(()=>s);return s},o=(s,c,l)=>{if(Xe(s))return s.aborted=!0,s;let a=i(c,r,l);if(a instanceof Promise){if(l.async===!1)throw new Fe;return a.then((p)=>e._zod.parse(p,l))}return e._zod.parse(a,l)};e._zod.run=(s,c)=>{if(c.skipChecks)return e._zod.parse(s,c);if(c.direction==="backward"){let a=e._zod.parse({value:s.value,issues:[]},{...c,skipChecks:!0});if(a instanceof Promise)return a.then((p)=>o(p,s,c));return o(a,s,c)}let l=e._zod.parse(s,c);if(l instanceof Promise){if(c.async===!1)throw new Fe;return l.then((a)=>i(a,r,c))}return i(l,r,c)}}F(e,"~standard",()=>({validate:(i)=>{try{let o=Mu(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch(o){return Ru(e,i).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),lr=A("$ZodString",(e,t)=>{Z.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ud(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),W=A("$ZodStringFormat",(e,t)=>{on.init(e,t),lr.init(e,t)}),Od=A("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Gu),W.init(e,t)}),Nd=A("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ki(r))}else t.pattern??(t.pattern=ki());W.init(e,t)}),Id=A("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Yu),W.init(e,t)}),Cd=A("$ZodURL",(e,t)=>{W.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===sd.source){if(!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}}let i=new URL(r);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(i.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=i.href;else n.value=r;return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Pd=A("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Qu()),W.init(e,t)}),Md=A("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Hu),W.init(e,t)}),Rd=A("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ku),W.init(e,t)}),Ld=A("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=qu),W.init(e,t)}),xd=A("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Zu),W.init(e,t)}),Dd=A("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Wu),W.init(e,t)}),jd=A("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ju),W.init(e,t)}),Ud=A("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=ld(t)),W.init(e,t)}),zd=A("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ad),W.init(e,t)}),Fd=A("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=cd(t)),W.init(e,t)}),Bd=A("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Vu),W.init(e,t)}),Kd=A("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ed),W.init(e,t),e._zod.bag.format="ipv4"}),qd=A("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=td),W.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(n)=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Zd=A("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=nd),W.init(e,t)}),Wd=A("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=rd),W.init(e,t),e._zod.check=(n)=>{let r=n.value.split("/");try{if(r.length!==2)throw Error();let[i,o]=r;if(!o)throw Error();let s=Number(o);if(`${s}`!==o)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Bs(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Jd=A("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=id),W.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(Bs(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Hd(e){if(!Rs.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Bs(n)}var Vd=A("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Rs),W.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(Hd(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Gd=A("$ZodE164",(e,t)=>{t.pattern??(t.pattern=od),W.init(e,t)});function Yd(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}var Xd=A("$ZodJWT",(e,t)=>{W.init(e,t),e._zod.check=(n)=>{if(Yd(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Ks=A("$ZodNumber",(e,t)=>{Z.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ds,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}let i=n.value;if(typeof i==="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o=typeof i==="number"?Number.isNaN(i)?"NaN":!Number.isFinite(i)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Qd=A("$ZodNumberFormat",(e,t)=>{gd.init(e,t),Ks.init(e,t)}),ef=A("$ZodBoolean",(e,t)=>{Z.init(e,t),e._zod.pattern=fd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}let i=n.value;if(typeof i==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),tf=A("$ZodUnknown",(e,t)=>{Z.init(e,t),e._zod.parse=(n)=>n}),nf=A("$ZodNever",(e,t)=>{Z.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Si(e,t,n){if(e.issues.length)t.issues.push(...Qe(n,e.issues));t.value[n]=e.value}var rf=A("$ZodArray",(e,t)=>{Z.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let c=i[s],l=t.element._zod.run({value:c,issues:[]},r);if(l instanceof Promise)o.push(l.then((a)=>Si(a,n,s)));else Si(l,n,s)}if(o.length)return Promise.all(o).then(()=>n);return n}});function Ut(e,t,n,r,i,o){let s=n in r;if(e.issues.length){if(i&&o&&!s)return;t.issues.push(...Qe(n,e.issues))}if(!s&&!i){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(s)t.value[n]=void 0}else t.value[n]=e.value}function qs(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let n=_u(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Zs(e,t,n,r,i,o){let s=[],c=i.keySet,l=i.catchall._zod,a=l.def.type,p=l.optin==="optional",f=l.optout==="optional";for(let d in t){if(d==="__proto__")continue;if(c.has(d))continue;if(a==="never"){s.push(d);continue}let u=l.run({value:t[d],issues:[]},r);if(u instanceof Promise)e.push(u.then((m)=>Ut(m,n,d,t,p,f)));else Ut(u,n,d,t,p,f)}if(s.length)n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o});if(!e.length)return n;return Promise.all(e).then(()=>n)}var sf=A("$ZodObject",(e,t)=>{if(Z.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}let r=rr(()=>qs(t));F(e._zod,"propValues",()=>{let c=t.shape,l={};for(let a in c){let p=c[a]._zod;if(p.values){l[a]??(l[a]=new Set);for(let f of p.values)l[a].add(f)}}return l});let i=Dt,o=t.catchall,s;e._zod.parse=(c,l)=>{s??(s=r.value);let a=c.value;if(!i(a))return c.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),c;c.value={};let p=[],f=s.shape;for(let d of s.keys){let u=f[d],m=u._zod.optin==="optional",g=u._zod.optout==="optional",y=u._zod.run({value:a[d],issues:[]},l);if(y instanceof Promise)p.push(y.then((w)=>Ut(w,c,d,a,m,g)));else Ut(y,c,d,a,m,g)}if(!o)return p.length?Promise.all(p).then(()=>c):c;return Zs(p,a,c,l,r.value,e)}}),of=A("$ZodObjectJIT",(e,t)=>{sf.init(e,t);let n=e._zod.parse,r=rr(()=>qs(t)),i=(d)=>{let u=new Fs(["shape","payload","ctx"]),m=r.value,g=(b)=>{let k=_i(b);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};u.write("const input = payload.value;");let y=Object.create(null),w=0;for(let b of m.keys)y[b]=`key_${w++}`;u.write("const newResult = {};");for(let b of m.keys){let k=y[b],_=_i(b),E=d[b],O=E?._zod?.optin==="optional",I=E?._zod?.optout==="optional";if(u.write(`const ${k} = ${g(b)};`),O&&I)u.write(`
|
|
172
172
|
if (${k}.issues.length) {
|
|
173
173
|
if (${_} in input) {
|
|
174
174
|
payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
|
|
@@ -186,7 +186,7 @@ never guess a value for a required field you have not been given.`,vi;function E
|
|
|
186
186
|
newResult[${_}] = ${k}.value;
|
|
187
187
|
}
|
|
188
188
|
|
|
189
|
-
`);else if(!
|
|
189
|
+
`);else if(!O)u.write(`
|
|
190
190
|
const ${k}_present = ${_} in input;
|
|
191
191
|
if (${k}.issues.length) {
|
|
192
192
|
payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
|
|
@@ -227,82 +227,82 @@ never guess a value for a required field you have not been given.`,vi;function E
|
|
|
227
227
|
newResult[${_}] = ${k}.value;
|
|
228
228
|
}
|
|
229
229
|
|
|
230
|
-
`)}u.write("payload.value = newResult;"),u.write("return payload;");let v=u.compile();return(b,k)=>v(d,b,k)},o,s=Dt,c=!xt.jitless,a=c&&wu.value,p=t.catchall,f;e._zod.parse=(d,u)=>{f??(f=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),d;if(c&&a&&u?.async===!1&&u.jitless!==!0){if(!o)o=i(t.shape);if(d=o(d,u),!p)return d;return qs([],m,d,u,f,e)}return n(d,u)}});function Ti(e,t,n,r){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let i=e.filter((o)=>!Xe(o));if(i.length===1)return t.value=i[0].value,i[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((o)=>o.issues.map((s)=>Re(s,r,Me())))}),t}var of=E("$ZodUnion",(e,t)=>{q.init(e,t),z(e._zod,"optin",()=>t.options.some((r)=>r._zod.optin==="optional")?"optional":void 0),z(e._zod,"optout",()=>t.options.some((r)=>r._zod.optout==="optional")?"optional":void 0),z(e._zod,"values",()=>{if(t.options.every((r)=>r._zod.values))return new Set(t.options.flatMap((r)=>Array.from(r._zod.values)));return}),z(e._zod,"pattern",()=>{if(t.options.every((r)=>r._zod.pattern)){let r=t.options.map((i)=>i._zod.pattern);return new RegExp(`^(${r.map((i)=>sr(i.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1,s=[];for(let c of t.options){let l=c._zod.run({value:r.value,issues:[]},i);if(l instanceof Promise)s.push(l),o=!0;else{if(l.issues.length===0)return l;s.push(l)}}if(!o)return Ti(s,r,e,i);return Promise.all(s).then((c)=>Ti(c,r,e,i))}}),af=E("$ZodIntersection",(e,t)=>{q.init(e,t),e._zod.parse=(n,r)=>{let i=n.value,o=t.left._zod.run({value:i,issues:[]},r),s=t.right._zod.run({value:i,issues:[]},r);if(o instanceof Promise||s instanceof Promise)return Promise.all([o,s]).then(([l,a])=>$i(n,l,a));return $i(n,o,s)}});function Kn(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(tt(e)&&tt(t)){let n=Object.keys(t),r=Object.keys(e).filter((o)=>n.indexOf(o)!==-1),i={...e,...t};for(let o of r){let s=Kn(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[r],s=Kn(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function $i(e,t,n){let r=new Map,i;for(let c of t.issues)if(c.code==="unrecognized_keys"){i??(i=c);for(let l of c.keys){if(!r.has(l))r.set(l,{});r.get(l).l=!0}}else e.issues.push(c);for(let c of n.issues)if(c.code==="unrecognized_keys")for(let l of c.keys){if(!r.has(l))r.set(l,{});r.get(l).r=!0}else e.issues.push(c);let o=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(o.length&&i)e.issues.push({...i,keys:o});if(Xe(e))return e;let s=Kn(t.value,n.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var cf=E("$ZodRecord",(e,t)=>{q.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!tt(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.value={};let c=new Set;for(let a of s)if(typeof a==="string"||typeof a==="number"||typeof a==="symbol"){c.add(typeof a==="number"?a.toString():a);let p=t.keyType._zod.run({value:a,issues:[]},r);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map((u)=>Re(u,r,Me())),input:a,path:[a],inst:e});continue}let f=p.value,d=t.valueType._zod.run({value:i[a],issues:[]},r);if(d instanceof Promise)o.push(d.then((u)=>{if(u.issues.length)n.issues.push(...Qe(a,u.issues));n.value[f]=u.value}));else{if(d.issues.length)n.issues.push(...Qe(a,d.issues));n.value[f]=d.value}}let l;for(let a in i)if(!c.has(a))l=l??[],l.push(a);if(l&&l.length>0)n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l})}else{n.value={};for(let c of Reflect.ownKeys(i)){if(c==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(i,c))continue;let l=t.keyType._zod.run({value:c,issues:[]},r);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof c==="string"&&xs.test(c)&&l.issues.length){let f=t.keyType._zod.run({value:Number(c),issues:[]},r);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length===0)l=f}if(l.issues.length){if(t.mode==="loose")n.value[c]=i[c];else n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((f)=>Re(f,r,Me())),input:c,path:[c],inst:e});continue}let p=t.valueType._zod.run({value:i[c],issues:[]},r);if(p instanceof Promise)o.push(p.then((f)=>{if(f.issues.length)n.issues.push(...Qe(c,f.issues));n.value[l.value]=f.value}));else{if(p.issues.length)n.issues.push(...Qe(c,p.issues));n.value[l.value]=p.value}}}if(o.length)return Promise.all(o).then(()=>n);return n}}),lf=E("$ZodEnum",(e,t)=>{q.init(e,t);let n=As(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter((i)=>vu.has(typeof i)).map((i)=>typeof i==="string"?nt(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{let s=i.value;if(r.has(s))return i;return i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),uf=E("$ZodLiteral",(e,t)=>{if(q.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map((r)=>typeof r==="string"?nt(r):r?nt(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,i)=>{let o=r.value;if(n.has(o))return r;return r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),df=E("$ZodTransform",(e,t)=>{q.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new nr(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then((s)=>(n.value=s,n.fallback=!0,n));if(i instanceof Promise)throw new ze;return n.value=i,n.fallback=!0,n}});function Ei(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var Zs=E("$ZodOptional",(e,t)=>{q.init(e,t),e._zod.optin="optional",e._zod.optout="optional",z(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),z(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${sr(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let i=n.value,o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>Ei(s,i));return Ei(o,i)}if(n.value===void 0)return n;return t.innerType._zod.run(n,r)}}),ff=E("$ZodExactOptional",(e,t)=>{Zs.init(e,t),z(e._zod,"values",()=>t.innerType._zod.values),z(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),hf=E("$ZodNullable",(e,t)=>{q.init(e,t),z(e._zod,"optin",()=>t.innerType._zod.optin),z(e._zod,"optout",()=>t.innerType._zod.optout),z(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${sr(n.source)}|null)$`):void 0}),z(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),pf=E("$ZodDefault",(e,t)=>{q.init(e,t),e._zod.optin="optional",z(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>Ai(o,t));return Ai(i,t)}});function Ai(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var mf=E("$ZodPrefault",(e,t)=>{q.init(e,t),e._zod.optin="optional",z(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),gf=E("$ZodNonOptional",(e,t)=>{q.init(e,t),z(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter((r)=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>Oi(o,e));return Oi(i,e)}});function Oi(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var yf=E("$ZodCatch",(e,t)=>{q.init(e,t),e._zod.optin="optional",z(e._zod,"optout",()=>t.innerType._zod.optout),z(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>{if(n.value=o.value,o.issues.length)n.value=t.catchValue({...n,error:{issues:o.issues.map((s)=>Re(s,r,Me()))},input:n.value}),n.issues=[],n.fallback=!0;return n});if(n.value=i.value,i.issues.length)n.value=t.catchValue({...n,error:{issues:i.issues.map((o)=>Re(o,r,Me()))},input:n.value}),n.issues=[],n.fallback=!0;return n}}),wf=E("$ZodPipe",(e,t)=>{q.init(e,t),z(e._zod,"values",()=>t.in._zod.values),z(e._zod,"optin",()=>t.in._zod.optin),z(e._zod,"optout",()=>t.out._zod.optout),z(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let o=t.out._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>It(s,t.in,r));return It(o,t.in,r)}let i=t.in._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>It(o,t.out,r));return It(i,t.out,r)}});function It(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var vf=E("$ZodReadonly",(e,t)=>{q.init(e,t),z(e._zod,"propValues",()=>t.innerType._zod.propValues),z(e._zod,"values",()=>t.innerType._zod.values),z(e._zod,"optin",()=>t.innerType?._zod?.optin),z(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then(Ni);return Ni(i)}});function Ni(e){return e.value=Object.freeze(e.value),e}var bf=E("$ZodLazy",(e,t)=>{q.init(e,t),z(e._zod,"innerType",()=>{let n=t;if(!n._cachedInner)n._cachedInner=t.getter();return n._cachedInner}),z(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),z(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),z(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),z(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),_f=E("$ZodCustom",(e,t)=>{me.init(e,t),q.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then((o)=>Ii(o,n,r,e));Ii(i,n,r,e);return}});function Ii(e,t,n,r){if(!e){let i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)i.params=r._zod.def.params;t.issues.push(ft(i))}}var Ci,ck=Symbol("ZodOutput"),lk=Symbol("ZodInput");class Ws{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function kf(){return new Ws}(Ci=globalThis).__zod_globalRegistry??(Ci.__zod_globalRegistry=kf());var dt=globalThis.__zod_globalRegistry;function Sf(e,t){return new e({type:"string",...M(t)})}function Tf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function Pi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function $f(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function Ef(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function Af(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function Of(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function Nf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function If(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function Cf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function Pf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function Mf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function Rf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function Lf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function xf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function Df(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function jf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function Uf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function zf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function Ff(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function Bf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function Kf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function qf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}function Zf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function Wf(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function Jf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function Hf(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function Vf(e,t){return new e({type:"number",checks:[],...M(t)})}function Gf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function Yf(e,t){return new e({type:"boolean",...M(t)})}function Xf(e){return new e({type:"unknown"})}function Qf(e,t){return new e({type:"never",...M(t)})}function Mi(e,t){return new js({check:"less_than",...M(t),value:e,inclusive:!1})}function Rn(e,t){return new js({check:"less_than",...M(t),value:e,inclusive:!0})}function Ri(e,t){return new Us({check:"greater_than",...M(t),value:e,inclusive:!1})}function Ln(e,t){return new Us({check:"greater_than",...M(t),value:e,inclusive:!0})}function Li(e,t){return new pd({check:"multiple_of",...M(t),value:e})}function Js(e,t){return new gd({check:"max_length",...M(t),maximum:e})}function zt(e,t){return new yd({check:"min_length",...M(t),minimum:e})}function Hs(e,t){return new wd({check:"length_equals",...M(t),length:e})}function eh(e,t){return new vd({check:"string_format",format:"regex",...M(t),pattern:e})}function th(e){return new bd({check:"string_format",format:"lowercase",...M(e)})}function nh(e){return new _d({check:"string_format",format:"uppercase",...M(e)})}function rh(e,t){return new kd({check:"string_format",format:"includes",...M(t),includes:e})}function ih(e,t){return new Sd({check:"string_format",format:"starts_with",...M(t),prefix:e})}function sh(e,t){return new Td({check:"string_format",format:"ends_with",...M(t),suffix:e})}function st(e){return new $d({check:"overwrite",tx:e})}function oh(e){return st((t)=>t.normalize(e))}function ah(){return st((e)=>e.trim())}function ch(){return st((e)=>e.toLowerCase())}function lh(){return st((e)=>e.toUpperCase())}function uh(){return st((e)=>yu(e))}function dh(e,t,n){return new e({type:"array",element:t,...M(n)})}function fh(e,t,n){return new e({type:"custom",check:"custom",fn:t,...M(n)})}function hh(e,t){let n=ph((r)=>(r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(ft(i,r.value,n._zod.def));else{let o=i;if(o.fatal)o.continue=!1;o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),r.issues.push(ft(o))}},e(r.value,r)),t);return n}function ph(e,t){let n=new me({check:"custom",...M(t)});return n._zod.check=e,n}function Vs(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??dt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function X(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,o=t.seen.get(e);if(o){if(o.count++,n.schemaPath.includes(e))o.cycle=n.path;return o.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);let c=e._zod.toJSONSchema?.();if(c)s.schema=c;else{let p={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,p);else{let d=s.schema,u=t.processors[i.type];if(!u)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);u(e,t,d,p)}let f=e._zod.parent;if(f){if(!s.ref)s.ref=f;X(f,t,p),t.seen.get(f).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(s.schema,l);if(t.io==="input"&&de(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(r=s.schema).default??(r.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Gs(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let s of e.seen.entries()){let c=e.metadataRegistry.get(s[0])?.id;if(c){let l=r.get(c);if(l&&l!==s[0])throw Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(c,s[0])}}let i=(s)=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(s[0])?.id,d=e.external.uri??((m)=>m);if(f)return{ref:d(f)};let u=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=u,{defId:u,ref:`${d("__shared")}#/${c}/${u}`}}if(s[1]===n)return{ref:"#"};let a=`${"#"}/${c}/`,p=s[1].schema.id??`__schema${e.counter++}`;return{defId:p,ref:a+p}},o=(s)=>{if(s[1].schema.$ref)return;let c=s[1],{ref:l,defId:a}=i(s);if(c.def={...c.schema},a)c.defId=a;let p=c.schema;for(let f in p)delete p[f];p.$ref=l};if(e.cycles==="throw")for(let s of e.seen.entries()){let c=s[1];if(c.cycle)throw Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
230
|
+
`)}u.write("payload.value = newResult;"),u.write("return payload;");let v=u.compile();return(b,k)=>v(d,b,k)},o,s=Dt,c=!xt.jitless,a=c&&vu.value,p=t.catchall,f;e._zod.parse=(d,u)=>{f??(f=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),d;if(c&&a&&u?.async===!1&&u.jitless!==!0){if(!o)o=i(t.shape);if(d=o(d,u),!p)return d;return Zs([],m,d,u,f,e)}return n(d,u)}});function Ti(e,t,n,r){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let i=e.filter((o)=>!Xe(o));if(i.length===1)return t.value=i[0].value,i[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((o)=>o.issues.map((s)=>Re(s,r,Me())))}),t}var af=A("$ZodUnion",(e,t)=>{Z.init(e,t),F(e._zod,"optin",()=>t.options.some((r)=>r._zod.optin==="optional")?"optional":void 0),F(e._zod,"optout",()=>t.options.some((r)=>r._zod.optout==="optional")?"optional":void 0),F(e._zod,"values",()=>{if(t.options.every((r)=>r._zod.values))return new Set(t.options.flatMap((r)=>Array.from(r._zod.values)));return}),F(e._zod,"pattern",()=>{if(t.options.every((r)=>r._zod.pattern)){let r=t.options.map((i)=>i._zod.pattern);return new RegExp(`^(${r.map((i)=>sr(i.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1,s=[];for(let c of t.options){let l=c._zod.run({value:r.value,issues:[]},i);if(l instanceof Promise)s.push(l),o=!0;else{if(l.issues.length===0)return l;s.push(l)}}if(!o)return Ti(s,r,e,i);return Promise.all(s).then((c)=>Ti(c,r,e,i))}}),cf=A("$ZodIntersection",(e,t)=>{Z.init(e,t),e._zod.parse=(n,r)=>{let i=n.value,o=t.left._zod.run({value:i,issues:[]},r),s=t.right._zod.run({value:i,issues:[]},r);if(o instanceof Promise||s instanceof Promise)return Promise.all([o,s]).then(([l,a])=>$i(n,l,a));return $i(n,o,s)}});function Kn(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(tt(e)&&tt(t)){let n=Object.keys(t),r=Object.keys(e).filter((o)=>n.indexOf(o)!==-1),i={...e,...t};for(let o of r){let s=Kn(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[r],s=Kn(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function $i(e,t,n){let r=new Map,i;for(let c of t.issues)if(c.code==="unrecognized_keys"){i??(i=c);for(let l of c.keys){if(!r.has(l))r.set(l,{});r.get(l).l=!0}}else e.issues.push(c);for(let c of n.issues)if(c.code==="unrecognized_keys")for(let l of c.keys){if(!r.has(l))r.set(l,{});r.get(l).r=!0}else e.issues.push(c);let o=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(o.length&&i)e.issues.push({...i,keys:o});if(Xe(e))return e;let s=Kn(t.value,n.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var lf=A("$ZodRecord",(e,t)=>{Z.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!tt(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.value={};let c=new Set;for(let a of s)if(typeof a==="string"||typeof a==="number"||typeof a==="symbol"){c.add(typeof a==="number"?a.toString():a);let p=t.keyType._zod.run({value:a,issues:[]},r);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map((u)=>Re(u,r,Me())),input:a,path:[a],inst:e});continue}let f=p.value,d=t.valueType._zod.run({value:i[a],issues:[]},r);if(d instanceof Promise)o.push(d.then((u)=>{if(u.issues.length)n.issues.push(...Qe(a,u.issues));n.value[f]=u.value}));else{if(d.issues.length)n.issues.push(...Qe(a,d.issues));n.value[f]=d.value}}let l;for(let a in i)if(!c.has(a))l=l??[],l.push(a);if(l&&l.length>0)n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l})}else{n.value={};for(let c of Reflect.ownKeys(i)){if(c==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(i,c))continue;let l=t.keyType._zod.run({value:c,issues:[]},r);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof c==="string"&&Ds.test(c)&&l.issues.length){let f=t.keyType._zod.run({value:Number(c),issues:[]},r);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length===0)l=f}if(l.issues.length){if(t.mode==="loose")n.value[c]=i[c];else n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((f)=>Re(f,r,Me())),input:c,path:[c],inst:e});continue}let p=t.valueType._zod.run({value:i[c],issues:[]},r);if(p instanceof Promise)o.push(p.then((f)=>{if(f.issues.length)n.issues.push(...Qe(c,f.issues));n.value[l.value]=f.value}));else{if(p.issues.length)n.issues.push(...Qe(c,p.issues));n.value[l.value]=p.value}}}if(o.length)return Promise.all(o).then(()=>n);return n}}),uf=A("$ZodEnum",(e,t)=>{Z.init(e,t);let n=Es(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter((i)=>bu.has(typeof i)).map((i)=>typeof i==="string"?nt(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{let s=i.value;if(r.has(s))return i;return i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),df=A("$ZodLiteral",(e,t)=>{if(Z.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map((r)=>typeof r==="string"?nt(r):r?nt(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,i)=>{let o=r.value;if(n.has(o))return r;return r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),ff=A("$ZodTransform",(e,t)=>{Z.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new nr(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then((s)=>(n.value=s,n.fallback=!0,n));if(i instanceof Promise)throw new Fe;return n.value=i,n.fallback=!0,n}});function Ei(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var Ws=A("$ZodOptional",(e,t)=>{Z.init(e,t),e._zod.optin="optional",e._zod.optout="optional",F(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),F(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${sr(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let i=n.value,o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>Ei(s,i));return Ei(o,i)}if(n.value===void 0)return n;return t.innerType._zod.run(n,r)}}),hf=A("$ZodExactOptional",(e,t)=>{Ws.init(e,t),F(e._zod,"values",()=>t.innerType._zod.values),F(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),pf=A("$ZodNullable",(e,t)=>{Z.init(e,t),F(e._zod,"optin",()=>t.innerType._zod.optin),F(e._zod,"optout",()=>t.innerType._zod.optout),F(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${sr(n.source)}|null)$`):void 0}),F(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),mf=A("$ZodDefault",(e,t)=>{Z.init(e,t),e._zod.optin="optional",F(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>Ai(o,t));return Ai(i,t)}});function Ai(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var gf=A("$ZodPrefault",(e,t)=>{Z.init(e,t),e._zod.optin="optional",F(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),yf=A("$ZodNonOptional",(e,t)=>{Z.init(e,t),F(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter((r)=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>Oi(o,e));return Oi(i,e)}});function Oi(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var wf=A("$ZodCatch",(e,t)=>{Z.init(e,t),e._zod.optin="optional",F(e._zod,"optout",()=>t.innerType._zod.optout),F(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>{if(n.value=o.value,o.issues.length)n.value=t.catchValue({...n,error:{issues:o.issues.map((s)=>Re(s,r,Me()))},input:n.value}),n.issues=[],n.fallback=!0;return n});if(n.value=i.value,i.issues.length)n.value=t.catchValue({...n,error:{issues:i.issues.map((o)=>Re(o,r,Me()))},input:n.value}),n.issues=[],n.fallback=!0;return n}}),vf=A("$ZodPipe",(e,t)=>{Z.init(e,t),F(e._zod,"values",()=>t.in._zod.values),F(e._zod,"optin",()=>t.in._zod.optin),F(e._zod,"optout",()=>t.out._zod.optout),F(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let o=t.out._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>It(s,t.in,r));return It(o,t.in,r)}let i=t.in._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>It(o,t.out,r));return It(i,t.out,r)}});function It(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var bf=A("$ZodReadonly",(e,t)=>{Z.init(e,t),F(e._zod,"propValues",()=>t.innerType._zod.propValues),F(e._zod,"values",()=>t.innerType._zod.values),F(e._zod,"optin",()=>t.innerType?._zod?.optin),F(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then(Ni);return Ni(i)}});function Ni(e){return e.value=Object.freeze(e.value),e}var _f=A("$ZodLazy",(e,t)=>{Z.init(e,t),F(e._zod,"innerType",()=>{let n=t;if(!n._cachedInner)n._cachedInner=t.getter();return n._cachedInner}),F(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),F(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),F(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),F(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),kf=A("$ZodCustom",(e,t)=>{ge.init(e,t),Z.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then((o)=>Ii(o,n,r,e));Ii(i,n,r,e);return}});function Ii(e,t,n,r){if(!e){let i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)i.params=r._zod.def.params;t.issues.push(ft(i))}}var Ci,fk=Symbol("ZodOutput"),hk=Symbol("ZodInput");class Js{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Sf(){return new Js}(Ci=globalThis).__zod_globalRegistry??(Ci.__zod_globalRegistry=Sf());var dt=globalThis.__zod_globalRegistry;function Tf(e,t){return new e({type:"string",...R(t)})}function $f(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}function Pi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function Ef(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}function Af(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}function Of(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}function Nf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}function If(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}function Cf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}function Pf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}function Mf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}function Rf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}function Lf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}function xf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}function Df(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}function jf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}function Uf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}function zf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}function Ff(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}function Bf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}function Kf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}function qf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}function Zf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}function Wf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}function Jf(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}function Hf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}function Vf(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}function Gf(e,t){return new e({type:"number",checks:[],...R(t)})}function Yf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}function Xf(e,t){return new e({type:"boolean",...R(t)})}function Qf(e){return new e({type:"unknown"})}function eh(e,t){return new e({type:"never",...R(t)})}function Mi(e,t){return new Us({check:"less_than",...R(t),value:e,inclusive:!1})}function Rn(e,t){return new Us({check:"less_than",...R(t),value:e,inclusive:!0})}function Ri(e,t){return new zs({check:"greater_than",...R(t),value:e,inclusive:!1})}function Ln(e,t){return new zs({check:"greater_than",...R(t),value:e,inclusive:!0})}function Li(e,t){return new md({check:"multiple_of",...R(t),value:e})}function Hs(e,t){return new yd({check:"max_length",...R(t),maximum:e})}function zt(e,t){return new wd({check:"min_length",...R(t),minimum:e})}function Vs(e,t){return new vd({check:"length_equals",...R(t),length:e})}function th(e,t){return new bd({check:"string_format",format:"regex",...R(t),pattern:e})}function nh(e){return new _d({check:"string_format",format:"lowercase",...R(e)})}function rh(e){return new kd({check:"string_format",format:"uppercase",...R(e)})}function ih(e,t){return new Sd({check:"string_format",format:"includes",...R(t),includes:e})}function sh(e,t){return new Td({check:"string_format",format:"starts_with",...R(t),prefix:e})}function oh(e,t){return new $d({check:"string_format",format:"ends_with",...R(t),suffix:e})}function it(e){return new Ed({check:"overwrite",tx:e})}function ah(e){return it((t)=>t.normalize(e))}function ch(){return it((e)=>e.trim())}function lh(){return it((e)=>e.toLowerCase())}function uh(){return it((e)=>e.toUpperCase())}function dh(){return it((e)=>wu(e))}function fh(e,t,n){return new e({type:"array",element:t,...R(n)})}function hh(e,t,n){return new e({type:"custom",check:"custom",fn:t,...R(n)})}function ph(e,t){let n=mh((r)=>(r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(ft(i,r.value,n._zod.def));else{let o=i;if(o.fatal)o.continue=!1;o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),r.issues.push(ft(o))}},e(r.value,r)),t);return n}function mh(e,t){let n=new ge({check:"custom",...R(t)});return n._zod.check=e,n}function Gs(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??dt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Q(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,o=t.seen.get(e);if(o){if(o.count++,n.schemaPath.includes(e))o.cycle=n.path;return o.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);let c=e._zod.toJSONSchema?.();if(c)s.schema=c;else{let p={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,p);else{let d=s.schema,u=t.processors[i.type];if(!u)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);u(e,t,d,p)}let f=e._zod.parent;if(f){if(!s.ref)s.ref=f;Q(f,t,p),t.seen.get(f).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(s.schema,l);if(t.io==="input"&&he(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(r=s.schema).default??(r.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Ys(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let s of e.seen.entries()){let c=e.metadataRegistry.get(s[0])?.id;if(c){let l=r.get(c);if(l&&l!==s[0])throw Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(c,s[0])}}let i=(s)=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(s[0])?.id,d=e.external.uri??((m)=>m);if(f)return{ref:d(f)};let u=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=u,{defId:u,ref:`${d("__shared")}#/${c}/${u}`}}if(s[1]===n)return{ref:"#"};let a=`${"#"}/${c}/`,p=s[1].schema.id??`__schema${e.counter++}`;return{defId:p,ref:a+p}},o=(s)=>{if(s[1].schema.$ref)return;let c=s[1],{ref:l,defId:a}=i(s);if(c.def={...c.schema},a)c.defId=a;let p=c.schema;for(let f in p)delete p[f];p.$ref=l};if(e.cycles==="throw")for(let s of e.seen.entries()){let c=s[1];if(c.cycle)throw Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
231
231
|
|
|
232
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let c=s[1];if(t===s[0]){o(s);continue}if(e.external){let a=e.external.registry.get(s[0])?.id;if(t!==s[0]&&a){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(c.cycle){o(s);continue}if(c.count>1){if(e.reused==="ref"){o(s);continue}}}}function Ys(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(c)=>{let l=e.seen.get(c);if(l.ref===null)return;let a=l.def??l.schema,p={...a},f=l.ref;if(l.ref=null,f){r(f);let u=e.seen.get(f),m=u.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))a.allOf=a.allOf??[],a.allOf.push(m);else Object.assign(a,m);if(Object.assign(a,p),c._zod.parent===f)for(let y in a){if(y==="$ref"||y==="allOf")continue;if(!(y in p))delete a[y]}if(m.$ref&&u.def)for(let y in a){if(y==="$ref"||y==="allOf")continue;if(y in u.def&&JSON.stringify(a[y])===JSON.stringify(u.def[y]))delete a[y]}}let d=c._zod.parent;if(d&&d!==f){r(d);let u=e.seen.get(d);if(u?.schema.$ref){if(a.$ref=u.schema.$ref,u.def)for(let m in a){if(m==="$ref"||m==="allOf")continue;if(m in u.def&&JSON.stringify(a[m])===JSON.stringify(u.def[m]))delete a[m]}}}e.override({zodSchema:c,jsonSchema:a,path:l.path??[]})};for(let c of[...e.seen.entries()].reverse())r(c[0]);let i={};if(e.target==="draft-2020-12")i.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")i.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")i.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let c=e.external.registry.get(t)?.id;if(!c)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(c)}Object.assign(i,n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;if(o!==void 0&&i.id===o)delete i.id;let s=e.external?.defs??{};for(let c of e.seen.entries()){let l=c[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;s[l.defId]=l.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")i.$defs=s;else i.definitions=s;try{let c=JSON.parse(JSON.stringify(i));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ft(t,"input",e.processors),output:Ft(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch(c){throw Error("Error converting schema to JSON.")}}function de(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return de(r.element,n);if(r.type==="set")return de(r.valueType,n);if(r.type==="lazy")return de(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return de(r.innerType,n);if(r.type==="intersection")return de(r.left,n)||de(r.right,n);if(r.type==="record"||r.type==="map")return de(r.keyType,n)||de(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return de(r.in,n)||de(r.out,n)}if(r.type==="object"){for(let i in r.shape)if(de(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(de(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(de(i,n))return!0;if(r.rest&&de(r.rest,n))return!0;return!1}return!1}var mh=(e,t={})=>(n)=>{let r=Vs({...n,processors:t});return X(e,r),Gs(r,e),Ys(r,e)},Ft=(e,t,n={})=>(r)=>{let{libraryOptions:i,target:o}=r??{},s=Vs({...i??{},target:o,io:t,processors:n});return X(e,s),Gs(s,e),Ys(s,e)},gh={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yh=(e,t,n,r)=>{let i=n;i.type="string";let{minimum:o,maximum:s,format:c,patterns:l,contentEncoding:a}=e._zod.bag;if(typeof o==="number")i.minLength=o;if(typeof s==="number")i.maxLength=s;if(c){if(i.format=gh[c]??c,i.format==="")delete i.format;if(c==="time")delete i.format}if(a)i.contentEncoding=a;if(l&&l.size>0){let p=[...l];if(p.length===1)i.pattern=p[0].source;else if(p.length>1)i.allOf=[...p.map((f)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}},wh=(e,t,n,r)=>{let i=n,{minimum:o,maximum:s,format:c,multipleOf:l,exclusiveMaximum:a,exclusiveMinimum:p}=e._zod.bag;if(typeof c==="string"&&c.includes("int"))i.type="integer";else i.type="number";let f=typeof p==="number"&&p>=(o??Number.NEGATIVE_INFINITY),d=typeof a==="number"&&a<=(s??Number.POSITIVE_INFINITY),u=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(u)i.minimum=p,i.exclusiveMinimum=!0;else i.exclusiveMinimum=p;else if(typeof o==="number")i.minimum=o;if(d)if(u)i.maximum=a,i.exclusiveMaximum=!0;else i.exclusiveMaximum=a;else if(typeof s==="number")i.maximum=s;if(typeof l==="number")i.multipleOf=l},vh=(e,t,n,r)=>{n.type="boolean"},bh=(e,t,n,r)=>{n.not={}},_h=(e,t,n,r)=>{},kh=(e,t,n,r)=>{let i=e._zod.def,o=As(i.entries);if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";n.enum=o},Sh=(e,t,n,r)=>{let i=e._zod.def,o=[];for(let s of i.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else o.push(Number(s));else o.push(s);if(o.length===0);else if(o.length===1){let s=o[0];if(n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[s];else n.const=s}else{if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";if(o.every((s)=>typeof s==="boolean"))n.type="boolean";if(o.every((s)=>s===null))n.type="null";n.enum=o}},Th=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},$h=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Eh=(e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:c}=e._zod.bag;if(typeof s==="number")i.minItems=s;if(typeof c==="number")i.maxItems=c;i.type="array",i.items=X(o.element,t,{...r,path:[...r.path,"items"]})},Ah=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object",i.properties={};let s=o.shape;for(let a in s)i.properties[a]=X(s[a],t,{...r,path:[...r.path,"properties",a]});let c=new Set(Object.keys(s)),l=new Set([...c].filter((a)=>{let p=o.shape[a]._zod;if(t.io==="input")return p.optin===void 0;else return p.optout===void 0}));if(l.size>0)i.required=Array.from(l);if(o.catchall?._zod.def.type==="never")i.additionalProperties=!1;else if(!o.catchall){if(t.io==="output")i.additionalProperties=!1}else if(o.catchall)i.additionalProperties=X(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},Oh=(e,t,n,r)=>{let i=e._zod.def,o=i.inclusive===!1,s=i.options.map((c,l)=>X(c,t,{...r,path:[...r.path,o?"oneOf":"anyOf",l]}));if(o)n.oneOf=s;else n.anyOf=s},Nh=(e,t,n,r)=>{let i=e._zod.def,o=X(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=X(i.right,t,{...r,path:[...r.path,"allOf",1]}),c=(a)=>("allOf"in a)&&Object.keys(a).length===1,l=[...c(o)?o.allOf:[o],...c(s)?s.allOf:[s]];n.allOf=l},Ih=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object";let s=o.keyType,l=s._zod.bag?.patterns;if(o.mode==="loose"&&l&&l.size>0){let p=X(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let f of l)i.patternProperties[f.source]=p}else{if(t.target==="draft-07"||t.target==="draft-2020-12")i.propertyNames=X(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});i.additionalProperties=X(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let a=s._zod.values;if(a){let p=[...a].filter((f)=>typeof f==="string"||typeof f==="number");if(p.length>0)i.required=p}},Ch=(e,t,n,r)=>{let i=e._zod.def,o=X(i.innerType,t,r),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=i.innerType,n.nullable=!0;else n.anyOf=[o,{type:"null"}]},Ph=(e,t,n,r)=>{let i=e._zod.def;X(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},Mh=(e,t,n,r)=>{let i=e._zod.def;X(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Rh=(e,t,n,r)=>{let i=e._zod.def;X(i.innerType,t,r);let o=t.seen.get(e);if(o.ref=i.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(i.defaultValue))},Lh=(e,t,n,r)=>{let i=e._zod.def;X(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},xh=(e,t,n,r)=>{let i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?i.out:i.in:i.out;X(s,t,r);let c=t.seen.get(e);c.ref=s},Dh=(e,t,n,r)=>{let i=e._zod.def;X(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},Xs=(e,t,n,r)=>{let i=e._zod.def;X(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},jh=(e,t,n,r)=>{let i=e._zod.innerType;X(i,t,r);let o=t.seen.get(e);o.ref=i},Uh=E("ZodISODateTime",(e,t)=>{jd.init(e,t),G.init(e,t)});function zh(e){return Zf(Uh,e)}var Fh=E("ZodISODate",(e,t)=>{Ud.init(e,t),G.init(e,t)});function Bh(e){return Wf(Fh,e)}var Kh=E("ZodISOTime",(e,t)=>{zd.init(e,t),G.init(e,t)});function qh(e){return Jf(Kh,e)}var Zh=E("ZodISODuration",(e,t)=>{Fd.init(e,t),G.init(e,t)});function Wh(e){return Hf(Zh,e)}var Jh=(e,t)=>{Cs.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>Cu(e,n)},flatten:{value:(n)=>Iu(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Bn,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Bn,2)}},isEmpty:{get(){return e.issues.length===0}}})},Te=E("ZodError",Jh,{Parent:Error}),Hh=ar(Te),Vh=cr(Te),Gh=rn(Te),Yh=sn(Te),Xh=Ru(Te),Qh=Lu(Te),ep=xu(Te),tp=Du(Te),np=ju(Te),rp=Uu(Te),ip=zu(Te),sp=Fu(Te),xi=new WeakMap;function yt(e,t,n){let r=Object.getPrototypeOf(e),i=xi.get(r);if(!i)i=new Set,xi.set(r,i);if(i.has(t))return;i.add(t);for(let o in n){let s=n[o];Object.defineProperty(r,o,{configurable:!0,enumerable:!1,get(){let c=s.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}var J=E("ZodType",(e,t)=>(q.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ft(e,"input"),output:Ft(e,"output")}}),e.toJSONSchema=mh(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>Hh(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Gh(e,n,r),e.parseAsync=async(n,r)=>Vh(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Yh(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>Xh(e,n,r),e.decode=(n,r)=>Qh(e,n,r),e.encodeAsync=async(n,r)=>ep(e,n,r),e.decodeAsync=async(n,r)=>tp(e,n,r),e.safeEncode=(n,r)=>np(e,n,r),e.safeDecode=(n,r)=>rp(e,n,r),e.safeEncodeAsync=async(n,r)=>ip(e,n,r),e.safeDecodeAsync=async(n,r)=>sp(e,n,r),yt(e,"ZodType",{check(...n){let r=this.def;return this.clone(Le(r,{checks:[...r.checks??[],...n.map((i)=>typeof i==="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return xe(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Qp(n,r))},superRefine(n,r){return this.check(em(n,r))},overwrite(n){return this.check(st(n))},optional(){return zi(this)},exactOptional(){return jp(this)},nullable(){return Fi(this)},nullish(){return zi(Fi(this))},nonoptional(n){return qp(this,n)},array(){return K(this)},or(n){return wt([this,n])},and(n){return Mp(this,n)},transform(n){return Bi(this,xp(n))},default(n){return Fp(this,n)},prefault(n){return Kp(this,n)},catch(n){return Wp(this,n)},pipe(n){return Bi(this,n)},readonly(){return Vp(this)},describe(n){let r=this.clone();return dt.add(r,{description:n}),r},meta(...n){if(n.length===0)return dt.get(this);let r=this.clone();return dt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return dt.get(e)?.description},configurable:!0}),e)),eo=E("_ZodString",(e,t)=>{lr.init(e,t),J.init(e,t),e._zod.processJSONSchema=(r,i,o)=>yh(e,r,i,o);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,yt(e,"_ZodString",{regex(...r){return this.check(eh(...r))},includes(...r){return this.check(rh(...r))},startsWith(...r){return this.check(ih(...r))},endsWith(...r){return this.check(sh(...r))},min(...r){return this.check(zt(...r))},max(...r){return this.check(Js(...r))},length(...r){return this.check(Hs(...r))},nonempty(...r){return this.check(zt(1,...r))},lowercase(r){return this.check(th(r))},uppercase(r){return this.check(nh(r))},trim(){return this.check(ah())},normalize(...r){return this.check(oh(...r))},toLowerCase(){return this.check(ch())},toUpperCase(){return this.check(lh())},slugify(){return this.check(uh())}})}),op=E("ZodString",(e,t)=>{lr.init(e,t),eo.init(e,t),e.email=(n)=>e.check(Tf(ap,n)),e.url=(n)=>e.check(Nf(cp,n)),e.jwt=(n)=>e.check(qf(Sp,n)),e.emoji=(n)=>e.check(If(lp,n)),e.guid=(n)=>e.check(Pi(Di,n)),e.uuid=(n)=>e.check($f(Ct,n)),e.uuidv4=(n)=>e.check(Ef(Ct,n)),e.uuidv6=(n)=>e.check(Af(Ct,n)),e.uuidv7=(n)=>e.check(Of(Ct,n)),e.nanoid=(n)=>e.check(Cf(up,n)),e.guid=(n)=>e.check(Pi(Di,n)),e.cuid=(n)=>e.check(Pf(dp,n)),e.cuid2=(n)=>e.check(Mf(fp,n)),e.ulid=(n)=>e.check(Rf(hp,n)),e.base64=(n)=>e.check(Ff(bp,n)),e.base64url=(n)=>e.check(Bf(_p,n)),e.xid=(n)=>e.check(Lf(pp,n)),e.ksuid=(n)=>e.check(xf(mp,n)),e.ipv4=(n)=>e.check(Df(gp,n)),e.ipv6=(n)=>e.check(jf(yp,n)),e.cidrv4=(n)=>e.check(Uf(wp,n)),e.cidrv6=(n)=>e.check(zf(vp,n)),e.e164=(n)=>e.check(Kf(kp,n)),e.datetime=(n)=>e.check(zh(n)),e.date=(n)=>e.check(Bh(n)),e.time=(n)=>e.check(qh(n)),e.duration=(n)=>e.check(Wh(n))});function P(e){return Sf(op,e)}var G=E("ZodStringFormat",(e,t)=>{Z.init(e,t),eo.init(e,t)}),ap=E("ZodEmail",(e,t)=>{Nd.init(e,t),G.init(e,t)}),Di=E("ZodGUID",(e,t)=>{Ad.init(e,t),G.init(e,t)}),Ct=E("ZodUUID",(e,t)=>{Od.init(e,t),G.init(e,t)}),cp=E("ZodURL",(e,t)=>{Id.init(e,t),G.init(e,t)}),lp=E("ZodEmoji",(e,t)=>{Cd.init(e,t),G.init(e,t)}),up=E("ZodNanoID",(e,t)=>{Pd.init(e,t),G.init(e,t)}),dp=E("ZodCUID",(e,t)=>{Md.init(e,t),G.init(e,t)}),fp=E("ZodCUID2",(e,t)=>{Rd.init(e,t),G.init(e,t)}),hp=E("ZodULID",(e,t)=>{Ld.init(e,t),G.init(e,t)}),pp=E("ZodXID",(e,t)=>{xd.init(e,t),G.init(e,t)}),mp=E("ZodKSUID",(e,t)=>{Dd.init(e,t),G.init(e,t)}),gp=E("ZodIPv4",(e,t)=>{Bd.init(e,t),G.init(e,t)}),yp=E("ZodIPv6",(e,t)=>{Kd.init(e,t),G.init(e,t)}),wp=E("ZodCIDRv4",(e,t)=>{qd.init(e,t),G.init(e,t)}),vp=E("ZodCIDRv6",(e,t)=>{Zd.init(e,t),G.init(e,t)}),bp=E("ZodBase64",(e,t)=>{Wd.init(e,t),G.init(e,t)}),_p=E("ZodBase64URL",(e,t)=>{Hd.init(e,t),G.init(e,t)}),kp=E("ZodE164",(e,t)=>{Vd.init(e,t),G.init(e,t)}),Sp=E("ZodJWT",(e,t)=>{Yd.init(e,t),G.init(e,t)}),to=E("ZodNumber",(e,t)=>{Bs.init(e,t),J.init(e,t),e._zod.processJSONSchema=(r,i,o)=>wh(e,r,i,o),yt(e,"ZodNumber",{gt(r,i){return this.check(Ri(r,i))},gte(r,i){return this.check(Ln(r,i))},min(r,i){return this.check(Ln(r,i))},lt(r,i){return this.check(Mi(r,i))},lte(r,i){return this.check(Rn(r,i))},max(r,i){return this.check(Rn(r,i))},int(r){return this.check(ji(r))},safe(r){return this.check(ji(r))},positive(r){return this.check(Ri(0,r))},nonnegative(r){return this.check(Ln(0,r))},negative(r){return this.check(Mi(0,r))},nonpositive(r){return this.check(Rn(0,r))},multipleOf(r,i){return this.check(Li(r,i))},step(r,i){return this.check(Li(r,i))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??0.5),e.isFinite=!0,e.format=n.format??null});function x(e){return Vf(to,e)}var Tp=E("ZodNumberFormat",(e,t)=>{Xd.init(e,t),to.init(e,t)});function ji(e){return Gf(Tp,e)}var $p=E("ZodBoolean",(e,t)=>{Qd.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vh(e,n,r,i)});function pe(e){return Yf($p,e)}var Ep=E("ZodUnknown",(e,t)=>{ef.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_h(e,n,r,i)});function Fe(){return Xf(Ep)}var Ap=E("ZodNever",(e,t)=>{tf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bh(e,n,r,i)});function Op(e){return Qf(Ap,e)}var Np=E("ZodArray",(e,t)=>{nf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Eh(e,n,r,i),e.element=t.element,yt(e,"ZodArray",{min(n,r){return this.check(zt(n,r))},nonempty(n){return this.check(zt(1,n))},max(n,r){return this.check(Js(n,r))},length(n,r){return this.check(Hs(n,r))},unwrap(){return this.element}})});function K(e,t){return dh(Np,e,t)}var Ip=E("ZodObject",(e,t)=>{sf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ah(e,n,r,i),z(e,"shape",()=>t.shape),yt(e,"ZodObject",{keyof(){return Q(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Fe()})},loose(){return this.clone({...this._zod.def,catchall:Fe()})},strict(){return this.clone({...this._zod.def,catchall:Op()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return Tu(this,n)},safeExtend(n){return $u(this,n)},merge(n){return Eu(this,n)},pick(n){return ku(this,n)},omit(n){return Su(this,n)},partial(...n){return Au(ro,this,n[0])},required(...n){return Ou(ao,this,n[0])}})});function j(e,t){let n={type:"object",shape:e??{},...M(t)};return new Ip(n)}var Cp=E("ZodUnion",(e,t)=>{of.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Oh(e,n,r,i),e.options=t.options});function wt(e,t){return new Cp({type:"union",options:e,...M(t)})}var Pp=E("ZodIntersection",(e,t)=>{af.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Nh(e,n,r,i)});function Mp(e,t){return new Pp({type:"intersection",left:e,right:t})}var Ui=E("ZodRecord",(e,t)=>{cf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ih(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function ke(e,t,n){if(!t||!t._zod)return new Ui({type:"record",keyType:P(),valueType:e,...M(t)});return new Ui({type:"record",keyType:e,valueType:t,...M(n)})}var qn=E("ZodEnum",(e,t)=>{lf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(r,i,o)=>kh(e,r,i,o),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{let o={};for(let s of r)if(n.has(s))o[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new qn({...t,checks:[],...M(i),entries:o})},e.exclude=(r,i)=>{let o={...t.entries};for(let s of r)if(n.has(s))delete o[s];else throw Error(`Key ${s} not found in enum`);return new qn({...t,checks:[],...M(i),entries:o})}});function Q(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new qn({type:"enum",entries:n,...M(t)})}var Rp=E("ZodLiteral",(e,t)=>{uf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Sh(e,n,r,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Bt(e,t){return new Rp({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}var Lp=E("ZodTransform",(e,t)=>{df.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>$h(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new nr(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(ft(o,n.value,t));else{let s=o;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(ft(s))}};let i=t.transform(n.value,n);if(i instanceof Promise)return i.then((o)=>(n.value=o,n.fallback=!0,n));return n.value=i,n.fallback=!0,n}});function xp(e){return new Lp({type:"transform",transform:e})}var ro=E("ZodOptional",(e,t)=>{Zs.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Xs(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function zi(e){return new ro({type:"optional",innerType:e})}var Dp=E("ZodExactOptional",(e,t)=>{ff.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Xs(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function jp(e){return new Dp({type:"optional",innerType:e})}var Up=E("ZodNullable",(e,t)=>{hf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ch(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Fi(e){return new Up({type:"nullable",innerType:e})}var zp=E("ZodDefault",(e,t)=>{pf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Mh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Fp(e,t){return new zp({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Ns(t)}})}var Bp=E("ZodPrefault",(e,t)=>{mf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Rh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Kp(e,t){return new Bp({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Ns(t)}})}var ao=E("ZodNonOptional",(e,t)=>{gf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ph(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function qp(e,t){return new ao({type:"nonoptional",innerType:e,...M(t)})}var Zp=E("ZodCatch",(e,t)=>{yf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Lh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wp(e,t){return new Zp({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var Jp=E("ZodPipe",(e,t)=>{wf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xh(e,n,r,i),e.in=t.in,e.out=t.out});function Bi(e,t){return new Jp({type:"pipe",in:e,out:t})}var Hp=E("ZodReadonly",(e,t)=>{vf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Dh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Vp(e){return new Hp({type:"readonly",innerType:e})}var Gp=E("ZodLazy",(e,t)=>{bf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jh(e,n,r,i),e.unwrap=()=>e._zod.def.getter()});function Yp(e){return new Gp({type:"lazy",getter:e})}var Xp=E("ZodCustom",(e,t)=>{_f.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Th(e,n,r,i)});function Qp(e,t={}){return fh(Xp,e,t)}function em(e,t){return hh(e,t)}var tm=_s(),nm=en(),rm=ps(),ur=tn(),im=Ht(),De=F(),sm=qe(),om=se(),am=Ze(),cm=We(),uk=Qn(),lm=ks(),um=Ss(),dm=Ts(),an=Vl(),co=Jt(),dk=tm.Composer,fk=nm.Document,hk=rm.Schema,{YAMLError:pk,YAMLParseError:mk,YAMLWarning:gk}=ur,yk=im.Alias,{isAlias:wk,isCollection:vk,isDocument:bk,isMap:_k,isNode:kk,isPair:Sk,isScalar:Tk,isSeq:$k}=De,Ek=sm.Pair,Ak=om.Scalar,Ok=am.YAMLMap,Nk=cm.YAMLSeq,Ik=lm.Lexer,Ck=um.LineCounter,Pk=dm.Parser,{parse:Mk,parseAllDocuments:Rk,parseDocument:Lk,stringify:xk}=an,{visit:Dk,visitAsync:jk}=co,Kk=`${er.slug}_`,qk=new RegExp("[\\u0000-\\u001f\\u007f]");function wm(e,t=""){let n="",r=0;for(;;){let i=e.indexOf("<!--",r);if(i===-1)break;let o=e.indexOf("-->",i+4);if(o===-1)break;n+=e.slice(r,i)+t,r=o+3}return n+e.slice(r)}var vm=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,bm=/\n{3,}/g;function _m(e){let t=vm.exec(e);return t===null||t===void 0?e:e.slice(t[0].length)}function km(e){return wm(e).replace(bm,`
|
|
232
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let c=s[1];if(t===s[0]){o(s);continue}if(e.external){let a=e.external.registry.get(s[0])?.id;if(t!==s[0]&&a){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(c.cycle){o(s);continue}if(c.count>1){if(e.reused==="ref"){o(s);continue}}}}function Xs(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(c)=>{let l=e.seen.get(c);if(l.ref===null)return;let a=l.def??l.schema,p={...a},f=l.ref;if(l.ref=null,f){r(f);let u=e.seen.get(f),m=u.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))a.allOf=a.allOf??[],a.allOf.push(m);else Object.assign(a,m);if(Object.assign(a,p),c._zod.parent===f)for(let y in a){if(y==="$ref"||y==="allOf")continue;if(!(y in p))delete a[y]}if(m.$ref&&u.def)for(let y in a){if(y==="$ref"||y==="allOf")continue;if(y in u.def&&JSON.stringify(a[y])===JSON.stringify(u.def[y]))delete a[y]}}let d=c._zod.parent;if(d&&d!==f){r(d);let u=e.seen.get(d);if(u?.schema.$ref){if(a.$ref=u.schema.$ref,u.def)for(let m in a){if(m==="$ref"||m==="allOf")continue;if(m in u.def&&JSON.stringify(a[m])===JSON.stringify(u.def[m]))delete a[m]}}}e.override({zodSchema:c,jsonSchema:a,path:l.path??[]})};for(let c of[...e.seen.entries()].reverse())r(c[0]);let i={};if(e.target==="draft-2020-12")i.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")i.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")i.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let c=e.external.registry.get(t)?.id;if(!c)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(c)}Object.assign(i,n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;if(o!==void 0&&i.id===o)delete i.id;let s=e.external?.defs??{};for(let c of e.seen.entries()){let l=c[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;s[l.defId]=l.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")i.$defs=s;else i.definitions=s;try{let c=JSON.parse(JSON.stringify(i));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ft(t,"input",e.processors),output:Ft(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch(c){throw Error("Error converting schema to JSON.")}}function he(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return he(r.element,n);if(r.type==="set")return he(r.valueType,n);if(r.type==="lazy")return he(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return he(r.innerType,n);if(r.type==="intersection")return he(r.left,n)||he(r.right,n);if(r.type==="record"||r.type==="map")return he(r.keyType,n)||he(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return he(r.in,n)||he(r.out,n)}if(r.type==="object"){for(let i in r.shape)if(he(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(he(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(he(i,n))return!0;if(r.rest&&he(r.rest,n))return!0;return!1}return!1}var gh=(e,t={})=>(n)=>{let r=Gs({...n,processors:t});return Q(e,r),Ys(r,e),Xs(r,e)},Ft=(e,t,n={})=>(r)=>{let{libraryOptions:i,target:o}=r??{},s=Gs({...i??{},target:o,io:t,processors:n});return Q(e,s),Ys(s,e),Xs(s,e)},yh={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},wh=(e,t,n,r)=>{let i=n;i.type="string";let{minimum:o,maximum:s,format:c,patterns:l,contentEncoding:a}=e._zod.bag;if(typeof o==="number")i.minLength=o;if(typeof s==="number")i.maxLength=s;if(c){if(i.format=yh[c]??c,i.format==="")delete i.format;if(c==="time")delete i.format}if(a)i.contentEncoding=a;if(l&&l.size>0){let p=[...l];if(p.length===1)i.pattern=p[0].source;else if(p.length>1)i.allOf=[...p.map((f)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}},vh=(e,t,n,r)=>{let i=n,{minimum:o,maximum:s,format:c,multipleOf:l,exclusiveMaximum:a,exclusiveMinimum:p}=e._zod.bag;if(typeof c==="string"&&c.includes("int"))i.type="integer";else i.type="number";let f=typeof p==="number"&&p>=(o??Number.NEGATIVE_INFINITY),d=typeof a==="number"&&a<=(s??Number.POSITIVE_INFINITY),u=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(u)i.minimum=p,i.exclusiveMinimum=!0;else i.exclusiveMinimum=p;else if(typeof o==="number")i.minimum=o;if(d)if(u)i.maximum=a,i.exclusiveMaximum=!0;else i.exclusiveMaximum=a;else if(typeof s==="number")i.maximum=s;if(typeof l==="number")i.multipleOf=l},bh=(e,t,n,r)=>{n.type="boolean"},_h=(e,t,n,r)=>{n.not={}},kh=(e,t,n,r)=>{},Sh=(e,t,n,r)=>{let i=e._zod.def,o=Es(i.entries);if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";n.enum=o},Th=(e,t,n,r)=>{let i=e._zod.def,o=[];for(let s of i.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else o.push(Number(s));else o.push(s);if(o.length===0);else if(o.length===1){let s=o[0];if(n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[s];else n.const=s}else{if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";if(o.every((s)=>typeof s==="boolean"))n.type="boolean";if(o.every((s)=>s===null))n.type="null";n.enum=o}},$h=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Eh=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Ah=(e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:c}=e._zod.bag;if(typeof s==="number")i.minItems=s;if(typeof c==="number")i.maxItems=c;i.type="array",i.items=Q(o.element,t,{...r,path:[...r.path,"items"]})},Oh=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object",i.properties={};let s=o.shape;for(let a in s)i.properties[a]=Q(s[a],t,{...r,path:[...r.path,"properties",a]});let c=new Set(Object.keys(s)),l=new Set([...c].filter((a)=>{let p=o.shape[a]._zod;if(t.io==="input")return p.optin===void 0;else return p.optout===void 0}));if(l.size>0)i.required=Array.from(l);if(o.catchall?._zod.def.type==="never")i.additionalProperties=!1;else if(!o.catchall){if(t.io==="output")i.additionalProperties=!1}else if(o.catchall)i.additionalProperties=Q(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},Nh=(e,t,n,r)=>{let i=e._zod.def,o=i.inclusive===!1,s=i.options.map((c,l)=>Q(c,t,{...r,path:[...r.path,o?"oneOf":"anyOf",l]}));if(o)n.oneOf=s;else n.anyOf=s},Ih=(e,t,n,r)=>{let i=e._zod.def,o=Q(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Q(i.right,t,{...r,path:[...r.path,"allOf",1]}),c=(a)=>("allOf"in a)&&Object.keys(a).length===1,l=[...c(o)?o.allOf:[o],...c(s)?s.allOf:[s]];n.allOf=l},Ch=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object";let s=o.keyType,l=s._zod.bag?.patterns;if(o.mode==="loose"&&l&&l.size>0){let p=Q(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let f of l)i.patternProperties[f.source]=p}else{if(t.target==="draft-07"||t.target==="draft-2020-12")i.propertyNames=Q(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});i.additionalProperties=Q(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let a=s._zod.values;if(a){let p=[...a].filter((f)=>typeof f==="string"||typeof f==="number");if(p.length>0)i.required=p}},Ph=(e,t,n,r)=>{let i=e._zod.def,o=Q(i.innerType,t,r),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=i.innerType,n.nullable=!0;else n.anyOf=[o,{type:"null"}]},Mh=(e,t,n,r)=>{let i=e._zod.def;Q(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},Rh=(e,t,n,r)=>{let i=e._zod.def;Q(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Lh=(e,t,n,r)=>{let i=e._zod.def;Q(i.innerType,t,r);let o=t.seen.get(e);if(o.ref=i.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(i.defaultValue))},xh=(e,t,n,r)=>{let i=e._zod.def;Q(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},Dh=(e,t,n,r)=>{let i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?i.out:i.in:i.out;Q(s,t,r);let c=t.seen.get(e);c.ref=s},jh=(e,t,n,r)=>{let i=e._zod.def;Q(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},Qs=(e,t,n,r)=>{let i=e._zod.def;Q(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},Uh=(e,t,n,r)=>{let i=e._zod.innerType;Q(i,t,r);let o=t.seen.get(e);o.ref=i},zh=A("ZodISODateTime",(e,t)=>{Ud.init(e,t),G.init(e,t)});function Fh(e){return Wf(zh,e)}var Bh=A("ZodISODate",(e,t)=>{zd.init(e,t),G.init(e,t)});function Kh(e){return Jf(Bh,e)}var qh=A("ZodISOTime",(e,t)=>{Fd.init(e,t),G.init(e,t)});function Zh(e){return Hf(qh,e)}var Wh=A("ZodISODuration",(e,t)=>{Bd.init(e,t),G.init(e,t)});function Jh(e){return Vf(Wh,e)}var Hh=(e,t)=>{Cs.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>Pu(e,n)},flatten:{value:(n)=>Cu(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Bn,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Bn,2)}},isEmpty:{get(){return e.issues.length===0}}})},$e=A("ZodError",Hh,{Parent:Error}),Vh=ar($e),Gh=cr($e),Yh=rn($e),Xh=sn($e),Qh=Lu($e),ep=xu($e),tp=Du($e),np=ju($e),rp=Uu($e),ip=zu($e),sp=Fu($e),op=Bu($e),xi=new WeakMap;function yt(e,t,n){let r=Object.getPrototypeOf(e),i=xi.get(r);if(!i)i=new Set,xi.set(r,i);if(i.has(t))return;i.add(t);for(let o in n){let s=n[o];Object.defineProperty(r,o,{configurable:!0,enumerable:!1,get(){let c=s.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}var J=A("ZodType",(e,t)=>(Z.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ft(e,"input"),output:Ft(e,"output")}}),e.toJSONSchema=gh(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>Vh(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Yh(e,n,r),e.parseAsync=async(n,r)=>Gh(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Xh(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>Qh(e,n,r),e.decode=(n,r)=>ep(e,n,r),e.encodeAsync=async(n,r)=>tp(e,n,r),e.decodeAsync=async(n,r)=>np(e,n,r),e.safeEncode=(n,r)=>rp(e,n,r),e.safeDecode=(n,r)=>ip(e,n,r),e.safeEncodeAsync=async(n,r)=>sp(e,n,r),e.safeDecodeAsync=async(n,r)=>op(e,n,r),yt(e,"ZodType",{check(...n){let r=this.def;return this.clone(Le(r,{checks:[...r.checks??[],...n.map((i)=>typeof i==="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return De(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(em(n,r))},superRefine(n,r){return this.check(tm(n,r))},overwrite(n){return this.check(it(n))},optional(){return zi(this)},exactOptional(){return Up(this)},nullable(){return Fi(this)},nullish(){return zi(Fi(this))},nonoptional(n){return Zp(this,n)},array(){return q(this)},or(n){return wt([this,n])},and(n){return Rp(this,n)},transform(n){return Bi(this,Dp(n))},default(n){return Bp(this,n)},prefault(n){return qp(this,n)},catch(n){return Jp(this,n)},pipe(n){return Bi(this,n)},readonly(){return Gp(this)},describe(n){let r=this.clone();return dt.add(r,{description:n}),r},meta(...n){if(n.length===0)return dt.get(this);let r=this.clone();return dt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return dt.get(e)?.description},configurable:!0}),e)),eo=A("_ZodString",(e,t)=>{lr.init(e,t),J.init(e,t),e._zod.processJSONSchema=(r,i,o)=>wh(e,r,i,o);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,yt(e,"_ZodString",{regex(...r){return this.check(th(...r))},includes(...r){return this.check(ih(...r))},startsWith(...r){return this.check(sh(...r))},endsWith(...r){return this.check(oh(...r))},min(...r){return this.check(zt(...r))},max(...r){return this.check(Hs(...r))},length(...r){return this.check(Vs(...r))},nonempty(...r){return this.check(zt(1,...r))},lowercase(r){return this.check(nh(r))},uppercase(r){return this.check(rh(r))},trim(){return this.check(ch())},normalize(...r){return this.check(ah(...r))},toLowerCase(){return this.check(lh())},toUpperCase(){return this.check(uh())},slugify(){return this.check(dh())}})}),ap=A("ZodString",(e,t)=>{lr.init(e,t),eo.init(e,t),e.email=(n)=>e.check($f(cp,n)),e.url=(n)=>e.check(If(lp,n)),e.jwt=(n)=>e.check(Zf(Tp,n)),e.emoji=(n)=>e.check(Cf(up,n)),e.guid=(n)=>e.check(Pi(Di,n)),e.uuid=(n)=>e.check(Ef(Ct,n)),e.uuidv4=(n)=>e.check(Af(Ct,n)),e.uuidv6=(n)=>e.check(Of(Ct,n)),e.uuidv7=(n)=>e.check(Nf(Ct,n)),e.nanoid=(n)=>e.check(Pf(dp,n)),e.guid=(n)=>e.check(Pi(Di,n)),e.cuid=(n)=>e.check(Mf(fp,n)),e.cuid2=(n)=>e.check(Rf(hp,n)),e.ulid=(n)=>e.check(Lf(pp,n)),e.base64=(n)=>e.check(Bf(_p,n)),e.base64url=(n)=>e.check(Kf(kp,n)),e.xid=(n)=>e.check(xf(mp,n)),e.ksuid=(n)=>e.check(Df(gp,n)),e.ipv4=(n)=>e.check(jf(yp,n)),e.ipv6=(n)=>e.check(Uf(wp,n)),e.cidrv4=(n)=>e.check(zf(vp,n)),e.cidrv6=(n)=>e.check(Ff(bp,n)),e.e164=(n)=>e.check(qf(Sp,n)),e.datetime=(n)=>e.check(Fh(n)),e.date=(n)=>e.check(Kh(n)),e.time=(n)=>e.check(Zh(n)),e.duration=(n)=>e.check(Jh(n))});function M(e){return Tf(ap,e)}var G=A("ZodStringFormat",(e,t)=>{W.init(e,t),eo.init(e,t)}),cp=A("ZodEmail",(e,t)=>{Id.init(e,t),G.init(e,t)}),Di=A("ZodGUID",(e,t)=>{Od.init(e,t),G.init(e,t)}),Ct=A("ZodUUID",(e,t)=>{Nd.init(e,t),G.init(e,t)}),lp=A("ZodURL",(e,t)=>{Cd.init(e,t),G.init(e,t)}),up=A("ZodEmoji",(e,t)=>{Pd.init(e,t),G.init(e,t)}),dp=A("ZodNanoID",(e,t)=>{Md.init(e,t),G.init(e,t)}),fp=A("ZodCUID",(e,t)=>{Rd.init(e,t),G.init(e,t)}),hp=A("ZodCUID2",(e,t)=>{Ld.init(e,t),G.init(e,t)}),pp=A("ZodULID",(e,t)=>{xd.init(e,t),G.init(e,t)}),mp=A("ZodXID",(e,t)=>{Dd.init(e,t),G.init(e,t)}),gp=A("ZodKSUID",(e,t)=>{jd.init(e,t),G.init(e,t)}),yp=A("ZodIPv4",(e,t)=>{Kd.init(e,t),G.init(e,t)}),wp=A("ZodIPv6",(e,t)=>{qd.init(e,t),G.init(e,t)}),vp=A("ZodCIDRv4",(e,t)=>{Zd.init(e,t),G.init(e,t)}),bp=A("ZodCIDRv6",(e,t)=>{Wd.init(e,t),G.init(e,t)}),_p=A("ZodBase64",(e,t)=>{Jd.init(e,t),G.init(e,t)}),kp=A("ZodBase64URL",(e,t)=>{Vd.init(e,t),G.init(e,t)}),Sp=A("ZodE164",(e,t)=>{Gd.init(e,t),G.init(e,t)}),Tp=A("ZodJWT",(e,t)=>{Xd.init(e,t),G.init(e,t)}),to=A("ZodNumber",(e,t)=>{Ks.init(e,t),J.init(e,t),e._zod.processJSONSchema=(r,i,o)=>vh(e,r,i,o),yt(e,"ZodNumber",{gt(r,i){return this.check(Ri(r,i))},gte(r,i){return this.check(Ln(r,i))},min(r,i){return this.check(Ln(r,i))},lt(r,i){return this.check(Mi(r,i))},lte(r,i){return this.check(Rn(r,i))},max(r,i){return this.check(Rn(r,i))},int(r){return this.check(ji(r))},safe(r){return this.check(ji(r))},positive(r){return this.check(Ri(0,r))},nonnegative(r){return this.check(Ln(0,r))},negative(r){return this.check(Mi(0,r))},nonpositive(r){return this.check(Rn(0,r))},multipleOf(r,i){return this.check(Li(r,i))},step(r,i){return this.check(Li(r,i))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??0.5),e.isFinite=!0,e.format=n.format??null});function x(e){return Gf(to,e)}var $p=A("ZodNumberFormat",(e,t)=>{Qd.init(e,t),to.init(e,t)});function ji(e){return Yf($p,e)}var Ep=A("ZodBoolean",(e,t)=>{ef.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bh(e,n,r,i)});function ae(e){return Xf(Ep,e)}var Ap=A("ZodUnknown",(e,t)=>{tf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kh(e,n,r,i)});function Ke(){return Qf(Ap)}var Op=A("ZodNever",(e,t)=>{nf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_h(e,n,r,i)});function Np(e){return eh(Op,e)}var Ip=A("ZodArray",(e,t)=>{rf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ah(e,n,r,i),e.element=t.element,yt(e,"ZodArray",{min(n,r){return this.check(zt(n,r))},nonempty(n){return this.check(zt(1,n))},max(n,r){return this.check(Hs(n,r))},length(n,r){return this.check(Vs(n,r))},unwrap(){return this.element}})});function q(e,t){return fh(Ip,e,t)}var Cp=A("ZodObject",(e,t)=>{of.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Oh(e,n,r,i),F(e,"shape",()=>t.shape),yt(e,"ZodObject",{keyof(){return X(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Ke()})},loose(){return this.clone({...this._zod.def,catchall:Ke()})},strict(){return this.clone({...this._zod.def,catchall:Np()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return $u(this,n)},safeExtend(n){return Eu(this,n)},merge(n){return Au(this,n)},pick(n){return Su(this,n)},omit(n){return Tu(this,n)},partial(...n){return Ou(no,this,n[0])},required(...n){return Nu(so,this,n[0])}})});function j(e,t){let n={type:"object",shape:e??{},...R(t)};return new Cp(n)}var Pp=A("ZodUnion",(e,t)=>{af.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Nh(e,n,r,i),e.options=t.options});function wt(e,t){return new Pp({type:"union",options:e,...R(t)})}var Mp=A("ZodIntersection",(e,t)=>{cf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ih(e,n,r,i)});function Rp(e,t){return new Mp({type:"intersection",left:e,right:t})}var Ui=A("ZodRecord",(e,t)=>{lf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ch(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function Te(e,t,n){if(!t||!t._zod)return new Ui({type:"record",keyType:M(),valueType:e,...R(t)});return new Ui({type:"record",keyType:e,valueType:t,...R(n)})}var qn=A("ZodEnum",(e,t)=>{uf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(r,i,o)=>Sh(e,r,i,o),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{let o={};for(let s of r)if(n.has(s))o[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new qn({...t,checks:[],...R(i),entries:o})},e.exclude=(r,i)=>{let o={...t.entries};for(let s of r)if(n.has(s))delete o[s];else throw Error(`Key ${s} not found in enum`);return new qn({...t,checks:[],...R(i),entries:o})}});function X(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new qn({type:"enum",entries:n,...R(t)})}var Lp=A("ZodLiteral",(e,t)=>{df.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Th(e,n,r,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Bt(e,t){return new Lp({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}var xp=A("ZodTransform",(e,t)=>{ff.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Eh(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new nr(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(ft(o,n.value,t));else{let s=o;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(ft(s))}};let i=t.transform(n.value,n);if(i instanceof Promise)return i.then((o)=>(n.value=o,n.fallback=!0,n));return n.value=i,n.fallback=!0,n}});function Dp(e){return new xp({type:"transform",transform:e})}var no=A("ZodOptional",(e,t)=>{Ws.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Qs(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function zi(e){return new no({type:"optional",innerType:e})}var jp=A("ZodExactOptional",(e,t)=>{hf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Qs(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Up(e){return new jp({type:"optional",innerType:e})}var zp=A("ZodNullable",(e,t)=>{pf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ph(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Fi(e){return new zp({type:"nullable",innerType:e})}var Fp=A("ZodDefault",(e,t)=>{mf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Rh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bp(e,t){return new Fp({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Os(t)}})}var Kp=A("ZodPrefault",(e,t)=>{gf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Lh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function qp(e,t){return new Kp({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Os(t)}})}var so=A("ZodNonOptional",(e,t)=>{yf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Mh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Zp(e,t){return new so({type:"nonoptional",innerType:e,...R(t)})}var Wp=A("ZodCatch",(e,t)=>{wf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Jp(e,t){return new Wp({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var Hp=A("ZodPipe",(e,t)=>{vf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Dh(e,n,r,i),e.in=t.in,e.out=t.out});function Bi(e,t){return new Hp({type:"pipe",in:e,out:t})}var Vp=A("ZodReadonly",(e,t)=>{bf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Gp(e){return new Vp({type:"readonly",innerType:e})}var Yp=A("ZodLazy",(e,t)=>{_f.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Uh(e,n,r,i),e.unwrap=()=>e._zod.def.getter()});function Xp(e){return new Yp({type:"lazy",getter:e})}var Qp=A("ZodCustom",(e,t)=>{kf.init(e,t),J.init(e,t),e._zod.processJSONSchema=(n,r,i)=>$h(e,n,r,i)});function em(e,t={}){return hh(Qp,e,t)}function tm(e,t){return ph(e,t)}var nm=vs(),rm=en(),im=ps(),ur=tn(),sm=Ht(),je=B(),om=Ze(),am=oe(),cm=We(),lm=Je(),pk=Qn(),um=bs(),dm=_s(),fm=ks(),an=Gl(),oo=Jt(),mk=nm.Composer,gk=rm.Document,yk=im.Schema,{YAMLError:wk,YAMLParseError:vk,YAMLWarning:bk}=ur,_k=sm.Alias,{isAlias:kk,isCollection:Sk,isDocument:Tk,isMap:$k,isNode:Ek,isPair:Ak,isScalar:Ok,isSeq:Nk}=je,Ik=om.Pair,Ck=am.Scalar,Pk=cm.YAMLMap,Mk=lm.YAMLSeq,Rk=um.Lexer,Lk=dm.LineCounter,xk=fm.Parser,{parse:Dk,parseAllDocuments:jk,parseDocument:Uk,stringify:zk}=an,{visit:Fk,visitAsync:Bk}=oo,Jk=`${er.slug}_`,Hk=new RegExp("[\\u0000-\\u001f\\u007f]");function vm(e,t=""){let n="",r=0;for(;;){let i=e.indexOf("<!--",r);if(i===-1)break;let o=e.indexOf("-->",i+4);if(o===-1)break;n+=e.slice(r,i)+t,r=o+3}return n+e.slice(r)}var bm=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,_m=/\n{3,}/g;function km(e){let t=bm.exec(e);return t===null||t===void 0?e:e.slice(t[0].length)}function Sm(e){return vm(e).replace(_m,`
|
|
233
233
|
|
|
234
|
-
`).trim()}var Pt={static:2000,volatile:3500,reminder:500,total:6000},we=P().min(1),Sm=j({delimiters:Q(["xml","markdown","plain"]).optional(),intensity:Q(["emphatic","neutral","soft"]).optional(),examplesIn:Q(["system","user"]).optional(),skillsIn:Q(["system","user"]).optional()}).strict(),Tm=j({nativeTools:pe().optional(),strictSchema:pe().optional(),thinking:Q(["none","anthropic","openai","deepseek"]).optional(),promptCache:Q(["none","anthropic","openai","bedrock"]).optional(),parallelToolCalls:pe().optional(),contextWindow:x().int().positive().optional(),maxOutput:x().int().positive().optional(),vision:pe().optional(),promptStyle:Sm.optional()}).strict(),Zi="chat-completions",uo=j({id:P().min(1),api:P().min(1).optional(),options:ke(P(),Fe()).optional(),baseUrl:P().min(1).optional(),apiKeyEnv:P().min(1).optional(),temperature:x().min(0).max(2).optional(),topP:x().min(0).max(1).optional(),maxTokens:x().int().positive().optional(),reasoningEffort:Q(["none","minimal","low","medium","high","xhigh","max"]).optional(),headers:ke(P(),P()).optional(),streamUsage:pe().optional(),capabilities:Tm.optional()}).strict();function fo(e,t){if((e.api??Zi)===Zi&&e.baseUrl===void 0)t.addIssue({code:"custom",path:["baseUrl"],message:"baseUrl is required for the chat-completions transport"})}var $m=uo.superRefine(fo),Mt=uo.extend({fallbacks:K($m).min(1).optional()}).superRefine(fo),Em=j({main:Mt,selector:Mt.optional(),compactor:Mt.optional()}).catchall(Mt),Am=j({snip:x().default(0.6),micro:x().default(0.7),collapse:x().default(0.8),reset:x().default(0.88),trim:x().default(0.95)}).strict(),Om=j({static:x().int().positive().default(Pt.static),volatile:x().int().positive().default(Pt.volatile),reminder:x().int().positive().default(Pt.reminder),total:x().int().positive().default(Pt.total)}).strict(),Nm=j({perRuleSuccess:x().gt(0).lte(1).default(0.9),reliabilityTarget:x().gt(0).lt(1).default(0.8),onExceed:Q(["fail","warn"]).default("fail")}).strict(),Im=j({file:P().min(1),requires:j({contextWindow:P().min(1).optional(),class:Q(["frontier","small"]).optional()}).strict().optional(),onUnmet:Q(["distill","omit","fail"]).default("distill"),distilled:P().min(1).optional()}).strict(),Cm=j({dir:P().min(1),maxActive:x().int().nonnegative().default(2),budget:x().int().positive().default(600)}).strict(),Pm=j({window:x().int().positive().optional(),reserveOutput:x().int().positive().default(4096),observationMaxTokens:x().int().positive().optional(),modelIdentity:Q(["shown","hidden"]).default("shown"),files:K(P().min(1)).default([]),workspace:P().min(1).default("./workspace"),static:K(P().min(1)).default([]),volatile:K(P().min(1)).default([]),reminder:P().min(1).optional(),budgets:Om.prefault({}),rules:Nm.prefault({}),soul:Im.optional(),compactionNotice:pe().optional(),thresholds:Am.prefault({})}).strict(),Mm=j({max:x().int().positive().default(24),reserveWrite:x().int().nonnegative().default(6)}).strict(),Rm=j({onMutate:Q(["refuse","confirm","allow"]).default("refuse")}).strict(),Lm=j({mode:Q(["ask","allow","deny"]).default("allow"),allow:K(P().min(1)).default([]),deny:K(P().min(1)).default([]),onNoApprover:Q(["deny","allow"]).default("deny")}).strict(),xm=j({dialect:Q(["nlt","native"]).default("nlt"),providers:ke(we,ke(P(),Fe())).default({}),provider:we.optional(),providerConfig:ke(P(),Fe()).default({}),budget:Mm.prefault({}),pinned:K(P().min(1)).default([]),search:j({enabled:pe().default(!1)}).strict().prefault({}),local:K(P().min(1)).default([]),untrusted:Rm.prefault({}),policy:Lm.prefault({}),eventDetail:Q(["none","redacted"]).default("none")}).strict(),Dm=j({allow:K(P().min(1)),entry:pe().optional()}).strict(),jm=j({dir:P().min(1).default("./skills"),maxActive:x().int().nonnegative().default(1),threshold:x().default(0.35),trusted:K(P().min(1)).optional()}).strict(),Um=j({retriever:P().min(1).default("fts5"),dir:P().min(1).default("./memory"),maxActive:x().int().nonnegative().default(5),threshold:x().default(0.2),budget:x().int().positive().default(2000),includeHistory:pe().default(!0)}).strict(),zm=j({type:we,id:we,allowFrom:K(P().min(1)).optional(),enabled:pe().default(!0),role:we.optional()}).passthrough(),ho=j({channel:we,to:P().min(1)}).strict(),Fm=j({default:we.optional(),reply:Q(["all","final"]).default("all"),targets:ke(P(),ho).default({})}).strict(),Kt=Yp(()=>j({type:Q(["string","number","integer","boolean","array","object"]),description:P().optional(),enum:K(wt([P(),x(),pe()])).optional(),items:Kt.optional(),properties:ke(P(),Kt).optional(),required:K(P()).optional()})),po=j({id:we,manifest:P().min(1),task:P().min(1),artifact:j({type:Bt("object"),properties:ke(P(),Kt),required:K(P()).optional()}).strict()}).strict(),Bm=j({members:K(po).min(1)}).strict(),Km=j({name:we,task:P().min(1),tools:K(P().min(1)).min(1),route:j({tools:K(P().min(1)).min(1)}).strict(),artifact:po.shape.artifact.optional(),model:P().min(1).optional(),maxSteps:x().int().positive().optional(),timeoutMs:x().int().positive().optional()}).strict(),xn={provider:P().min(1),model:P().min(1).optional(),baseUrl:P().min(1).optional(),apiKeyEnv:P().min(1).optional(),options:ke(P(),Fe()).optional()},qm=j({transcription:j({...xn,timeoutMs:x().int().positive().default(60000),maxBytes:x().int().positive().default(26214400)}).strict().optional(),speech:j({...xn,timeoutMs:x().int().positive().default(60000),maxCharacters:x().int().positive().default(3000)}).strict().optional(),image:j({...xn,timeoutMs:x().int().positive().default(120000),size:P().regex(/^[0-9]+x[0-9]+$/).default("1024x1024")}).strict().optional()}).strict(),Zm=j({enabled:pe().default(!1),escalateAfterMs:x().int().nonnegative().default(0)}).strict(),Wm=j({offer:j({task:P().min(1),artifact:j({type:Bt("object"),properties:ke(P(),Kt),required:K(P()).optional()}).strict()}).strict().optional(),to:wt([Bt("*"),K(we).min(1)]).optional()}).strict(),Jm=j({id:we,kind:Q(["cron","every","at"]),expr:P().min(1),task:P().min(1),deliver:wt([Bt("none"),ho]),session:P().min(1).default("isolated"),role:we.optional(),tools:j({allow:K(P().min(1)).min(1)}).strict().optional(),timeoutMs:x().int().positive().optional(),maxSteps:x().int().positive().optional(),enabled:pe().default(!0),timezone:P().min(1).optional()}).strict(),Hm=wt([P().min(1),j({spec:P().min(1),config:ke(P(),Fe()).default({})}).strict()]),Vm=j({identicalCalls:x().int().min(2).default(3),sameTool:x().int().min(2).optional()}).strict(),Gm=j({maxSteps:x().int().positive().default(40),noProgress:Vm.prefault({}),turnTimeoutMs:x().int().positive().default(1800000),toolTimeoutMs:x().int().positive().default(120000),maxParallelTools:x().int().positive().default(4),maxConcurrentTurns:x().int().positive().optional(),reloadHoldMs:x().int().nonnegative().default(30000),maxHops:x().int().nonnegative().default(4),tokens:j({max:x().int().positive(),windowMs:x().int().positive()}).strict().optional()}).strict(),Ym=j({enabled:pe().default(!1),port:x().int().min(1).max(65535).default(7420),host:P().min(1).default("127.0.0.1"),tokenEnv:P().min(1).default(`${er.envPrefix}API_TOKEN`),allowedOrigins:K(P().min(1)).default([]),allowedHosts:K(P().min(1)).default([])}).strict(),Zk=j({apiVersion:P().min(1),id:we.refine((e)=>!e.startsWith("~"),{message:"An agent id may not start with `~`; that prefix is reserved for shared memory scopes."}),name:P().min(1).optional(),extends:P().min(1).optional(),model:Em,context:Pm.prefault({}),tools:xm.prefault({}),phases:ke(P(),Dm).optional(),skills:jm.optional(),knowledge:Cm.optional(),memory:Um.optional(),channels:K(zm).default([]),delivery:Fm.optional(),schedules:K(Jm).default([]),team:Bm.optional(),subagents:K(Km).optional(),media:qm.optional(),standIn:Zm.optional(),delegation:Wm.optional(),plugins:K(Hm).default([]),limits:Gm.prefault({}),server:Ym.prefault({})}).strict(),Xm={nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096},Dn={nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,maxOutput:5000},jn={vision:!0,nativeTools:!0,strictSchema:!1,thinking:"anthropic",promptCache:"none",parallelToolCalls:!0},Un="Thinking blocks must be replayed with tool results or multi-step reasoning degrades silently. Prompt caching is unavailable on Anthropic's OpenAI-compatible endpoint; through OpenRouter the chat-completions transport sends cache_control itself (`sendsCacheControl`).",Wk=[{pattern:"gpt-4o*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:128000,maxOutput:16384}},{pattern:"gpt-4.1*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:1e6,maxOutput:32768}},{pattern:"gpt-4-turbo*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:128000,maxOutput:4096}},{pattern:"gpt-3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:16385,maxOutput:4096}},{pattern:"gpt-6*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!0,contextWindow:1050000,maxOutput:128000},note:"Window and output are reported figures, unverified here. Run `model probe` or override if your endpoint says otherwise."},{pattern:"gpt-5*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!0,contextWindow:200000,maxOutput:32768},note:"Deliberately conservative on window and output. Override if your endpoint serves more."},{pattern:"o1*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o3*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o4*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},...["claude-fable-5*","claude-opus-5*","claude-opus-4-8*","claude-opus-4-7*","claude-opus-4-6*","claude-sonnet-5*","claude-sonnet-4-6*","claude-haiku-5*"].map((e)=>({pattern:e,capabilities:{...jn,contextWindow:1e6,maxOutput:128000},note:Un})),{pattern:"claude-haiku-*",family:!0,capabilities:{...jn,contextWindow:200000,maxOutput:64000},note:Un},{pattern:"claude-*",family:!0,capabilities:{...jn,contextWindow:200000,maxOutput:8192},note:Un},{pattern:"nova-micro*",capabilities:{...Dn,contextWindow:128000}},{pattern:"nova-lite*",capabilities:{...Dn,contextWindow:300000,vision:!0}},{pattern:"nova-pro*",capabilities:{...Dn,contextWindow:300000,vision:!0}},{pattern:"gemini*",family:!0,capabilities:{vision:!0,nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:1e6,maxOutput:8192}},{pattern:"glm-5.3*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:1048576,maxOutput:131072},note:"Reasoning is billed to the output budget, like the deepseek rows.",verified:"2026-10-21 via OpenRouter, provider z-ai/fp8"},{pattern:"qwen/qwen3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:262144,maxOutput:8192},note:"Reasoning is billed to the output budget, so context.reserveOutput must cover reasoning plus the reply.",verified:"2026-10-23 via OpenRouter, provider deepinfra/bf16 (published context_length 262,144)"},{pattern:"qwen3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192},note:"Served locally by Ollama, which reports no token usage unless model.<role>.streamUsage is set — token figures come from the estimator until it is. Reasoning is billed to the output budget, so context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-13 against qwen3.5:9b on localhost:11434/v1"},{pattern:"qwen*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"llama*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:128000,maxOutput:4096}},{pattern:"mistral*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"mixtral*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"deepseek-v4-pro*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Reasoning tokens are billed to the output budget. With max_tokens=16 this model returned empty content and finish_reason=length; context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-12 against api.deepseek.com/v1"},{pattern:"deepseek-v4-flash*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:1048576,maxOutput:393216},verified:"2026-08-12 against api.deepseek.com/v1 (reasoning confirmed). Measured 2026-08-25 by `model probe --window`: contextWindow 1048576 as a ceiling — the endpoint refused a 1048576-token prompt and named that number; maxOutput 393216 from a refusal naming the range [1, 393216]; automatic prompt caching confirmed at 1024 of 1115 prompt tokens with no breakpoints sent, which is why promptCache stays `none` (it describes the runtime's job, not the provider's behaviour)."},{pattern:"deepseek-v4*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Family fallback for v4 ids this registry has not seen. Assumes reasoning, because both measured v4 models emit it."},{pattern:"deepseek-reasoner*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"Not served by the account this registry was tested against. Numbers are from provider documentation and are deliberately low — override them if your endpoint serves this id."},{pattern:"deepseek-chat*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:65536,maxOutput:8192},note:"Unverified, from provider documentation."},{pattern:"deepseek-r1*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"The open-weight name for the reasoner, used by self-hosted and Ollama deployments."},{pattern:"deepseek*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192}},{pattern:"gemma*",family:!0,capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096}},{pattern:"phi*",family:!0,capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:16384,maxOutput:4096}},{pattern:"*",capabilities:Xm}];var Qm=/^(?:[-*+]|\d+[.)])[ \t]+\S/,eg=/\*\*(\d{4})-(\d{2})-\d{2}T/;function tg(e){let t=[],n=-1,r=(i)=>{if(n===-1)return;t.push({start:n,end:i,text:e.slice(n,i).join(`
|
|
235
|
-
`).trimEnd()}),n=-1};for(let i=0;i<e.length;i+=1){let o=e[i]??"";if(
|
|
234
|
+
`).trim()}var Pt={static:2000,volatile:3500,reminder:500,total:6000},ve=M().min(1),Tm=j({delimiters:X(["xml","markdown","plain"]).optional(),intensity:X(["emphatic","neutral","soft"]).optional(),examplesIn:X(["system","user"]).optional(),skillsIn:X(["system","user"]).optional()}).strict(),$m=j({nativeTools:ae().optional(),strictSchema:ae().optional(),thinking:X(["none","anthropic","openai","deepseek"]).optional(),promptCache:X(["none","anthropic","openai","bedrock"]).optional(),parallelToolCalls:ae().optional(),contextWindow:x().int().positive().optional(),maxOutput:x().int().positive().optional(),vision:ae().optional(),promptStyle:Tm.optional()}).strict(),Zi="chat-completions",lo=j({id:M().min(1),api:M().min(1).optional(),options:Te(M(),Ke()).optional(),baseUrl:M().min(1).optional(),apiKeyEnv:M().min(1).optional(),temperature:x().min(0).max(2).optional(),topP:x().min(0).max(1).optional(),maxTokens:x().int().positive().optional(),reasoningEffort:X(["none","minimal","low","medium","high","xhigh","max"]).optional(),headers:Te(M(),M()).optional(),streamUsage:ae().optional(),capabilities:$m.optional()}).strict();function uo(e,t){if((e.api??Zi)===Zi&&e.baseUrl===void 0)t.addIssue({code:"custom",path:["baseUrl"],message:"baseUrl is required for the chat-completions transport"})}var Em=lo.superRefine(uo),Mt=lo.extend({fallbacks:q(Em).min(1).optional()}).superRefine(uo),Am=j({main:Mt,selector:Mt.optional(),compactor:Mt.optional()}).catchall(Mt),Om=j({snip:x().default(0.6),micro:x().default(0.7),collapse:x().default(0.8),reset:x().default(0.88),trim:x().default(0.95)}).strict(),Nm=j({static:x().int().positive().default(Pt.static),volatile:x().int().positive().default(Pt.volatile),reminder:x().int().positive().default(Pt.reminder),total:x().int().positive().default(Pt.total)}).strict(),Im=j({perRuleSuccess:x().gt(0).lte(1).default(0.9),reliabilityTarget:x().gt(0).lt(1).default(0.8),onExceed:X(["fail","warn"]).default("fail")}).strict(),Cm=j({file:M().min(1),requires:j({contextWindow:M().min(1).optional(),class:X(["frontier","small"]).optional()}).strict().optional(),onUnmet:X(["distill","omit","fail"]).default("distill"),distilled:M().min(1).optional()}).strict(),Pm=j({dir:M().min(1),maxActive:x().int().nonnegative().default(2),budget:x().int().positive().default(600)}).strict(),Mm=j({window:x().int().positive().optional(),reserveOutput:x().int().positive().default(4096),observationMaxTokens:x().int().positive().optional(),modelIdentity:X(["shown","hidden"]).default("shown"),files:q(M().min(1)).default([]),workspace:M().min(1).default("./workspace"),static:q(M().min(1)).default([]),volatile:q(M().min(1)).default([]),reminder:M().min(1).optional(),budgets:Nm.prefault({}),rules:Im.prefault({}),soul:Cm.optional(),compactionNotice:ae().optional(),thresholds:Om.prefault({})}).strict(),Rm=j({max:x().int().positive().default(24),reserveWrite:x().int().nonnegative().default(6)}).strict(),Lm=j({onMutate:X(["refuse","confirm","allow"]).default("refuse")}).strict(),xm=j({mode:X(["ask","allow","deny"]).default("allow"),allow:q(M().min(1)).default([]),deny:q(M().min(1)).default([]),onNoApprover:X(["deny","allow"]).default("deny")}).strict(),Dm=j({dialect:X(["nlt","native"]).default("nlt"),providers:Te(ve,Te(M(),Ke())).default({}),provider:ve.optional(),providerConfig:Te(M(),Ke()).default({}),budget:Rm.prefault({}),pinned:q(M().min(1)).default([]),search:j({enabled:ae().default(!1)}).strict().prefault({}),local:q(M().min(1)).default([]),untrusted:Lm.prefault({}),policy:xm.prefault({}),eventDetail:X(["none","redacted"]).default("none")}).strict(),jm=j({allow:q(M().min(1)),entry:ae().optional()}).strict(),Um=j({dir:M().min(1).default("./skills"),maxActive:x().int().nonnegative().default(1),threshold:x().default(0.35),trusted:q(M().min(1)).optional()}).strict(),zm=j({retriever:M().min(1).default("fts5"),dir:M().min(1).default("./memory"),maxActive:x().int().nonnegative().default(5),threshold:x().default(0.2),budget:x().int().positive().default(2000),includeHistory:ae().default(!0),shared:ae().default(!0)}).strict(),Fm=["owner","peer","channel-peer"],Bm=j({scope:X(Fm).default("channel-peer")}).strict(),Km=j({type:ve,id:ve,allowFrom:q(M().min(1)).optional(),enabled:ae().default(!0),role:ve.optional()}).passthrough(),fo=j({channel:ve,to:M().min(1)}).strict(),qm=j({default:ve.optional(),reply:X(["all","final"]).default("all"),targets:Te(M(),fo).default({})}).strict(),Kt=Xp(()=>j({type:X(["string","number","integer","boolean","array","object"]),description:M().optional(),enum:q(wt([M(),x(),ae()])).optional(),items:Kt.optional(),properties:Te(M(),Kt).optional(),required:q(M()).optional()})),ho=j({id:ve,manifest:M().min(1),task:M().min(1),artifact:j({type:Bt("object"),properties:Te(M(),Kt),required:q(M()).optional()}).strict()}).strict(),Zm=j({members:q(ho).min(1)}).strict(),Wm=j({name:ve,task:M().min(1),tools:q(M().min(1)).min(1),route:j({tools:q(M().min(1)).min(1)}).strict().optional(),spawn:ae().default(!1),artifact:ho.shape.artifact.optional(),model:M().min(1).optional(),maxSteps:x().int().positive().optional(),timeoutMs:x().int().positive().optional()}).strict(),xn={provider:M().min(1),model:M().min(1).optional(),baseUrl:M().min(1).optional(),apiKeyEnv:M().min(1).optional(),options:Te(M(),Ke()).optional()},Jm=j({transcription:j({...xn,timeoutMs:x().int().positive().default(60000),maxBytes:x().int().positive().default(26214400)}).strict().optional(),speech:j({...xn,timeoutMs:x().int().positive().default(60000),maxCharacters:x().int().positive().default(3000)}).strict().optional(),image:j({...xn,timeoutMs:x().int().positive().default(120000),size:M().regex(/^[0-9]+x[0-9]+$/).default("1024x1024")}).strict().optional()}).strict(),Hm=j({enabled:ae().default(!1),escalateAfterMs:x().int().nonnegative().default(0)}).strict(),Vm=j({offer:j({task:M().min(1),artifact:j({type:Bt("object"),properties:Te(M(),Kt),required:q(M()).optional()}).strict()}).strict().optional(),to:wt([Bt("*"),q(ve).min(1)]).optional(),ask:ae().default(!1)}).strict(),Gm=j({id:ve,kind:X(["cron","every","at"]),expr:M().min(1),task:M().min(1),deliver:wt([Bt("none"),fo]),session:M().min(1).default("isolated"),role:ve.optional(),tools:j({allow:q(M().min(1)).min(1)}).strict().optional(),timeoutMs:x().int().positive().optional(),maxSteps:x().int().positive().optional(),enabled:ae().default(!0),timezone:M().min(1).optional()}).strict(),Ym=wt([M().min(1),j({spec:M().min(1),config:Te(M(),Ke()).default({})}).strict()]),Xm=j({identicalCalls:x().int().min(2).default(3),sameTool:x().int().min(2).optional()}).strict(),Qm=j({maxSteps:x().int().positive().default(40),noProgress:Xm.prefault({}),turnTimeoutMs:x().int().positive().default(1800000),toolTimeoutMs:x().int().positive().default(120000),maxParallelTools:x().int().positive().default(4),maxConcurrentTurns:x().int().positive().optional(),reloadHoldMs:x().int().nonnegative().default(30000),maxHops:x().int().nonnegative().default(4),tokens:j({max:x().int().positive(),windowMs:x().int().positive()}).strict().optional()}).strict(),eg=j({enabled:ae().default(!1),port:x().int().min(1).max(65535).default(7420),host:M().min(1).default("127.0.0.1"),tokenEnv:M().min(1).default(`${er.envPrefix}API_TOKEN`),allowedOrigins:q(M().min(1)).default([]),allowedHosts:q(M().min(1)).default([])}).strict(),Vk=j({apiVersion:M().min(1),id:ve.refine((e)=>!e.startsWith("~"),{message:"An agent id may not start with `~`; that prefix is reserved for shared memory scopes."}),name:M().min(1).optional(),description:M().min(1).max(200,{message:"A description is one line of at most 200 characters; it is rendered into every peer's ask_agent description."}).refine((e)=>!/[\r\n]/.test(e),{message:"A description is one line; put the detail in AGENTS.md."}).optional(),extends:M().min(1).optional(),model:Am,context:Mm.prefault({}),tools:Dm.prefault({}),phases:Te(M(),jm).optional(),skills:Um.optional(),knowledge:Pm.optional(),memory:zm.optional(),sessions:Bm.optional(),channels:q(Km).default([]),delivery:qm.optional(),schedules:q(Gm).default([]),team:Zm.optional(),subagents:q(Wm).optional(),media:Jm.optional(),standIn:Hm.optional(),delegation:Vm.optional(),plugins:q(Ym).default([]),limits:Qm.prefault({}),server:eg.prefault({})}).strict(),tg={nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096},Dn={nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,maxOutput:5000},jn={vision:!0,nativeTools:!0,strictSchema:!1,thinking:"anthropic",promptCache:"none",parallelToolCalls:!0},Un="Thinking blocks must be replayed with tool results or multi-step reasoning degrades silently. Prompt caching is unavailable on Anthropic's OpenAI-compatible endpoint; through OpenRouter the chat-completions transport sends cache_control itself (`sendsCacheControl`).",Gk=[{pattern:"gpt-4o*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:128000,maxOutput:16384}},{pattern:"gpt-4.1*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:1e6,maxOutput:32768}},{pattern:"gpt-4-turbo*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:128000,maxOutput:4096}},{pattern:"gpt-3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:16385,maxOutput:4096}},{pattern:"gpt-6*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!0,contextWindow:1050000,maxOutput:128000},note:"Window and output are reported figures, unverified here. Run `model probe` or override if your endpoint says otherwise."},{pattern:"gpt-5*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!0,contextWindow:200000,maxOutput:32768},note:"Deliberately conservative on window and output. Override if your endpoint serves more."},{pattern:"o1*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o3*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o4*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},...["claude-fable-5*","claude-opus-5*","claude-opus-4-8*","claude-opus-4-7*","claude-opus-4-6*","claude-sonnet-5*","claude-sonnet-4-6*","claude-haiku-5*"].map((e)=>({pattern:e,capabilities:{...jn,contextWindow:1e6,maxOutput:128000},note:Un})),{pattern:"claude-haiku-*",family:!0,capabilities:{...jn,contextWindow:200000,maxOutput:64000},note:Un},{pattern:"claude-*",family:!0,capabilities:{...jn,contextWindow:200000,maxOutput:8192},note:Un},{pattern:"nova-micro*",capabilities:{...Dn,contextWindow:128000}},{pattern:"nova-lite*",capabilities:{...Dn,contextWindow:300000,vision:!0}},{pattern:"nova-pro*",capabilities:{...Dn,contextWindow:300000,vision:!0}},{pattern:"gemini*",family:!0,capabilities:{vision:!0,nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:1e6,maxOutput:8192}},{pattern:"glm-5.3*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:1048576,maxOutput:131072},note:"Reasoning is billed to the output budget, like the deepseek rows.",verified:"2026-10-21 via OpenRouter, provider z-ai/fp8"},{pattern:"qwen/qwen3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:262144,maxOutput:8192},note:"Reasoning is billed to the output budget, so context.reserveOutput must cover reasoning plus the reply.",verified:"2026-10-23 via OpenRouter, provider deepinfra/bf16 (published context_length 262,144)"},{pattern:"qwen3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192},note:"Served locally by Ollama, which reports no token usage unless model.<role>.streamUsage is set — token figures come from the estimator until it is. Reasoning is billed to the output budget, so context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-13 against qwen3.5:9b on localhost:11434/v1"},{pattern:"qwen*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"llama*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:128000,maxOutput:4096}},{pattern:"mistral*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"mixtral*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"deepseek-v4-pro*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Reasoning tokens are billed to the output budget. With max_tokens=16 this model returned empty content and finish_reason=length; context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-12 against api.deepseek.com/v1"},{pattern:"deepseek-v4-flash*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:1048576,maxOutput:393216},verified:"2026-08-12 against api.deepseek.com/v1 (reasoning confirmed). Measured 2026-08-25 by `model probe --window`: contextWindow 1048576 as a ceiling — the endpoint refused a 1048576-token prompt and named that number; maxOutput 393216 from a refusal naming the range [1, 393216]; automatic prompt caching confirmed at 1024 of 1115 prompt tokens with no breakpoints sent, which is why promptCache stays `none` (it describes the runtime's job, not the provider's behaviour)."},{pattern:"deepseek-v4*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Family fallback for v4 ids this registry has not seen. Assumes reasoning, because both measured v4 models emit it."},{pattern:"deepseek-reasoner*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"Not served by the account this registry was tested against. Numbers are from provider documentation and are deliberately low — override them if your endpoint serves this id."},{pattern:"deepseek-chat*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:65536,maxOutput:8192},note:"Unverified, from provider documentation."},{pattern:"deepseek-r1*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"The open-weight name for the reasoner, used by self-hosted and Ollama deployments."},{pattern:"deepseek*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192}},{pattern:"gemma*",family:!0,capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096}},{pattern:"phi*",family:!0,capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:16384,maxOutput:4096}},{pattern:"*",capabilities:tg}];var ng=/^(?:[-*+]|\d+[.)])[ \t]+\S/,rg=/\*\*(\d{4})-(\d{2})-\d{2}T/;function ig(e){let t=[],n=-1,r=(i)=>{if(n===-1)return;t.push({start:n,end:i,text:e.slice(n,i).join(`
|
|
235
|
+
`).trimEnd()}),n=-1};for(let i=0;i<e.length;i+=1){let o=e[i]??"";if(ng.test(o)){r(i),n=i;continue}if(n===-1)continue;if(o.trim()===""||/^[ \t]/.test(o))continue;r(i)}return r(e.length),t}function Zn(e){return pu(Sm(km(e)))}function sg(e,t){let n=rg.exec(e);if(n!==null)return`${n[1]}-${n[2]}.md`;let r=t.getUTCFullYear(),i=`${t.getUTCMonth()+1}`.padStart(2,"0");return`${r}-${i}.md`}function og(e,t){let n=e.split(/\r?\n/),r=ig(n),i=[],o=r,s=e,c=Zn(s);while(c>t&&o.length>1){let l=o[0];if(l===void 0)break;i.push(l),o=o.slice(1),s=ag(n,i),c=Zn(s)}if(c<=t)return{evict:i,remaining:s,tokens:c};return{evict:i,remaining:s,tokens:c,shortfall:o.length<=1?`${c} tokens remain against a ${t}-token budget with one note left, so eviction cannot help`:`${c} tokens remain against a ${t}-token budget`}}function ag(e,t){let n=new Set;for(let r of t)for(let i=r.start;i<r.end;i+=1)n.add(i);return e.filter((r,i)=>!n.has(i)).join(`
|
|
236
236
|
`).replace(/\n{3,}/g,`
|
|
237
237
|
|
|
238
|
-
`)}async function
|
|
238
|
+
`)}async function cg(e){let t=e.tags.length===0?"":` _(${e.tags.join(", ")})_`,n=`
|
|
239
239
|
- **${e.now.toISOString()}**${t} ${e.text}
|
|
240
|
-
`;return await
|
|
240
|
+
`;return await co(e.path,n,"utf8"),await lg(e)}async function lg(e){let t=await gm(e.path,"utf8"),n=og(t,e.budget);if(n.evict.length===0)return{file:e.name,evicted:0,archives:[],...n.shortfall===void 0?{}:{shortfall:n.shortfall}};let r=new Map;for(let i of n.evict){let o=sg(i.text,e.now);r.set(o,[...r.get(o)??[],i.text])}await mm(e.archiveDir,{recursive:!0});for(let[i,o]of r)await co(wm(e.archiveDir,i),`${o.join(`
|
|
241
241
|
`)}
|
|
242
|
-
`,"utf8");return await
|
|
242
|
+
`,"utf8");return await ym(e.path,n.remaining,"utf8"),{file:e.name,evicted:n.evict.length,archives:[...r.keys()].sort(),...n.shortfall===void 0?{}:{shortfall:n.shortfall}}}var cn="local",Wi="memory",Ji="notes.md",ug={spec:{slug:"now",provider:cn,summary:"Reports the current date and time.",whenToUse:"you need today's date or the current time — including to work out what 'tomorrow' or 'in three hours' means",whenNotToUse:"the person already told you the date or time; use theirs rather than replacing it with the clock",mutating:!1,tags:["read","time"],parameters:{type:"object",properties:{timezone:{type:"string",description:"IANA name such as Europe/London. Defaults to UTC."},format:{type:"string",description:"iso for a machine-readable timestamp, human for a readable one",enum:["iso","human"],default:"iso"}}}},handler(e,t){let n=t.now(),r=typeof e.timezone==="string"&&e.timezone!==""?e.timezone:"UTC";if(e.format==="human")return`${new Intl.DateTimeFormat("en-GB",{dateStyle:"full",timeStyle:"short",timeZone:r}).format(n)} (${r})`;if(r==="UTC")return n.toISOString();return`${dg(n,r)} (${r})`}};function dg(e,t){let n=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"longOffset"}).formatToParts(e),r=(o)=>n.find((s)=>s.type===o)?.value??"",i=r("timeZoneName").replace("GMT","");return`${r("year")}-${r("month")}-${r("day")}T${r("hour")}:${r("minute")}:${r("second")}${i===""?"Z":i}`}var fg={spec:{slug:"memory_write",provider:cn,summary:"Saves a short note for later recall.",whenToUse:"the person tells you something durable about themselves or their work that later conversations should know",whenNotToUse:"for anything already in this conversation, for secrets or credentials, or to store your own reasoning",mutating:!0,tags:["write","memory"],parameters:{type:"object",properties:{text:{type:"string",description:"The note, in one or two sentences."},tags:{type:"array",items:{type:"string"},description:"Optional labels."}},required:["text"]}},async handler(e,t){let n=typeof e.text==="string"?e.text.trim():"",r=Array.isArray(e.tags)?e.tags.map((l)=>String(l)):[],i=t.now().toISOString(),o=r.length===0?"":` _(${r.join(", ")})_`,s=`
|
|
243
243
|
- **${i}**${o} ${n}
|
|
244
|
-
`;if(t.writeNote!==void 0)return await t.writeNote(r.length===0?n:`${n} (${r.join(", ")})`);let c=t.writeTarget;if(
|
|
244
|
+
`;if(t.writeNote!==void 0)return await t.writeNote(r.length===0?n:`${n} (${r.join(", ")})`);let c=await hg(n,r,s,t);if(t.shareNote===void 0)return c;return`${c} ${await t.shareNote(r.length===0?n:`${n} (${r.join(", ")})`)}`}};async function hg(e,t,n,r){let i=r.writeTarget;if(i?.mode==="refused")throw ou(i.name,i.reason??"none");if(i?.path!==void 0){if(i.budget!==void 0&&r.memoryDir!==void 0&&i.eviction==="oldest"){let s=await cg({path:i.path,name:i.name,budget:i.budget,archiveDir:r.memoryDir,text:e,tags:t,now:r.now()});if(s.shortfall!==void 0)return`Saved to ${s.file}, but it is still over budget: ${s.shortfall}. Ask the person to raise the budget or shorten the file — the agent will not load until they do.`;if(s.evicted===0)return`Saved to ${s.file}.`;return`Saved to ${s.file}. Moved ${s.evicted} older ${s.evicted===1?"note":"notes"} into ${s.archives.join(", ")}, still searchable.`}if(await Ki(i.path,n,"utf8"),i.budget!==void 0){let s=Zn(await pm(i.path,"utf8"))-i.budget;if(s>0)return`Saved to ${i.name}, which is now ${s} tokens over its ${i.budget}-token budget. The agent will not load until that is fixed: add \`eviction: oldest\` to its frontmatter so older notes move to the memory directory, or raise the budget.`}return`Saved to ${i.name}.`}let o=qi(r.dir,Wi);return await hm(o,{recursive:!0}),await Ki(qi(o,Ji),n,"utf8"),`Saved to ${Wi}/${Ji}.`}var pg=1200,mg=pg*3,gg={spec:{slug:"artifact_read",provider:cn,summary:"Reads back a tool result that compaction replaced with a pointer.",whenToUse:"a compaction marker in this conversation names an id, and you need the tool result it replaced",whenNotToUse:"for anything still written out in the conversation, or to explore — every id comes from a marker, so there is nothing to browse",mutating:!1,tags:["read","context"],parameters:{type:"object",properties:{id:{type:"string",description:"The id printed inside the compaction marker, copied character for character."},from:{type:"integer",description:"Character offset to continue from. Omit for the beginning; a truncated reply says the number to pass."}},required:["id"]}},async handler(e,t){let n=typeof e.id==="string"?e.id.trim():"",r=typeof e.from==="number"&&e.from>0?Math.floor(e.from):0;if(t.readArtifact===void 0)throw lu();let i=await t.readArtifact(n);if(i===void 0)throw uu(n);let o=i.slug===void 0?"observation":`${i.slug} observation`,s=i.content.slice(r,r+mg),c=r+s.length,l=`Compacted ${o}, ${i.tokens} tokens${r===0?"":`, from character ${r}`}:`;if(c>=i.content.length)return`${l}
|
|
245
245
|
${s}`;return`${l}
|
|
246
246
|
${s}
|
|
247
247
|
|
|
248
|
-
[cut here — ${i.content.length-c} characters remain; continue with artifact_read(id, from: ${c})]`},trustOf:(e)=>
|
|
248
|
+
[cut here — ${i.content.length-c} characters remain; continue with artifact_read(id, from: ${c})]`},trustOf:(e)=>fu(typeof e.id==="string"?e.id.trim():"")},yg=30,wg={spec:{slug:"memory_forget",provider:cn,summary:"Finds and deletes saved notes, and what was said in past conversations.",whenToUse:"the person asks you to forget something you noted. Call it with `query` first, show the person what matched, then call it with the `ids` they confirm",whenNotToUse:"to tidy notes nobody asked you to remove, or with `ids` you have not shown the person",mutating:!0,tags:["write","memory"],parameters:{type:"object",properties:{query:{type:"string",description:"Words every matching note or past message contains, case-insensitive. Lists matches; deletes nothing."},ids:{type:"array",items:{type:"string"},description:"Ids from a previous listing (notes and conversation messages). Deletes exactly these."}}}},async handler(e,t){let n=typeof e.query==="string"?e.query.trim():"",r=Array.isArray(e.ids)?e.ids.map((l)=>String(l).trim()).filter((l)=>l!==""):[];if(n===""===(r.length===0))throw au();if(t.forgetMemory===void 0)throw cu();let i=(l)=>l==="space"?"the team's shared memory":"your notes";if(n!==""){let l=await t.forgetMemory({query:n});if(l.notes.length===0)return`No note in ${i(l.scope)} contains "${n}".`;let a=l.notes.slice(0,yg),p=l.notes.length>a.length?`
|
|
249
249
|
${l.notes.length-a.length} more match; use more words to narrow it down.`:"";return[`${l.notes.length} ${l.notes.length===1?"note":"notes"} in ${i(l.scope)} ${l.notes.length===1?"matches":"match"}. Nothing is deleted yet: show these to the person, then call memory_forget with the ids they confirm.`,...a.map((f)=>`- ${f.id} (${f.source}): ${f.text}`)].join(`
|
|
250
|
-
`)+p}let o=await t.forgetMemory({ids:r}),s=o.notes.length===0?`Nothing was deleted from ${i(o.scope)}.`:`Deleted ${o.notes.length} ${o.notes.length===1?"note":"notes"} from ${i(o.scope)}; they will not be recalled again.`,c=o.missing.length===0?"":` No note has ${o.missing.length===1?"the id":"the ids"} ${o.missing.join(", ")}: already gone, or not yours to delete here.`;return s+c}},
|
|
251
|
-
`);var Yk=(()=>{let e=Symbol.for(`${er.slug}.liveRuntimes`),t=globalThis;return t[e]??=new Set,t[e]})();var gg="id, session_key, turn_id, role, content, tool_calls, tool_call_id, origin, tainted, created_at",Xk=gg.split(", ").map((e)=>`m.${e}`).join(", ");var Qk=new Set("a an and are as at be but by do does for from had has have he her his i if in is it its me my not of on or our she that the their them then there they this to was we were what when which who will with you your would could should im ive dont its ill".split(" ")),_g=65536,kg=1000,Gi=[1000,2000,5000,15000,30000,60000],Sg=3,Tg=512,Yi=60000,$g=180000,Eg=3000,Ag=401,Og=515,Ng={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 Xi(e){let t=e.authState?.creds;if(t===void 0)return!0;return t.registered===!0||t.account!==void 0&&t.account!==null}function Qi(){return typeof globalThis.Bun<"u"}class go{id;type="whatsapp";limits={maxMessageChars:_g,idempotentSend:!1,attachments:!0,voiceNotes:!0,minSendIntervalMs:kg};alwaysAllow;#e;#n;#t;#r;#o;#i;#a;#s;#c=!1;#l=0;#u=!1;#d=!0;#f=0;#p=!1;#h=new Set;#m=[];#w;#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??Eg,this.#o=e.api}async start(e){if(this.#c)return;if(this.#c=!0,this.#a=e,Qi())e.error(Ng);this.#w=this.#v(e)}async stop(){if(!this.#c)return;this.#c=!1;try{this.#s?.end()}catch{}this.#s=void 0,this.#y?.(),this.#y=void 0,await this.#w?.catch(()=>{}),this.#w=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(es(e.recipient),n===void 0?{text:e.text}:n.mimeType.startsWith("audio/")?{audio:await Vi(n.path),mimetype:"audio/ogg; codecs=opus",ptt:!0}:{image:await Vi(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>Tg)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.#_();try{this.#s?.end()}catch{}this.#s=void 0,this.#l=0,this.#a?.status("disconnected","unpaired — scan the next QR to link a device"),this.#y?.(),this.#y=void 0}async typing(e){await this.#s?.sendPresenceUpdate("composing",es(e))}async#v(e){while(this.#c&&!this.#p){try{let n=this.#o??await Rg();this.#i=n,yg(this.#e,{recursive:!0,mode:448}),this.#u=this.#n!==void 0&&this.#n!=="";let r=await n.connect({authDir:this.#e,...this.#t===void 0?{}:{deviceName:this.#t},onUpdate:(i)=>this.#T(e,i),onCreds:()=>this.#A(),onMessages:(i)=>this.#$(e,i)});this.#s=r,this.#d=Xi(r),await this.#k(e,r),await this.#S()}catch(n){if(!this.#c)return;this.#b(e,n)}if(!this.#c)return;let t=this.#g;if(this.#g=!1,!t)await ts(this.#E())}}async#k(e,t){let n=this.#n;if(n===void 0||n==="")return;if(Xi(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()+Yi).toISOString()});return}try{if(await ts(this.#r),!this.#c)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()+$g).toISOString()})}catch(r){this.#u=!1,this.#b(e,r)}}#S(){if(!this.#c)return Promise.resolve();return new Promise((e)=>{this.#y=e})}#y;#T(e,t){if(t.qr!==void 0&&t.qr!==""&&!this.#u){e.status("needs_input",`scan to pair channel "${this.id}"`,{kind:"qr",payload:t.qr,expiresAt:new Date(Date.now()+Yi).toISOString()});return}if(t.connection==="open"){this.#f=0,this.#l=0;let n=this.#s?.user;if(this.#h.clear(),n?.id!==void 0)this.#h.add(Zt(n.id));if(n?.lid!==void 0)this.#h.add(Zt(n.lid));e.status("connected","paired");return}if(t.connection==="close"){let n=t.lastDisconnect?.error?.output?.statusCode;if(n===Ag)if(this.#_(),this.#d)this.#f=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.#f+=1,this.#l+=1,this.#f>=Sg)this.#p=!0,e.status("error",`pairing refused ${this.#f} times — not asking again`),e.error({code:"whatsapp_pairing_refused",message:`WhatsApp refused ${this.#f} pairing attempts for channel "${this.id}" and none completed.`,hint:Qi()?"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===Og)this.#g=!0;else if(this.#l+=1,this.#l===1||this.#l%8===0)e.status("disconnected",t.lastDisconnect?.error?.message??"connection closed");this.#s=void 0,this.#y?.(),this.#y=void 0}}#$(e,t){if(t.type!=="notify")return;for(let n of t.messages){let r=Cg(n,{ownJids:this.#h,sentIds:this.#m});if(r===void 0)continue;let i=Pg(n),o=yo(n),s=this.#i,c=async()=>{if(s?.download===void 0)throw Error("this Baileys build cannot download media");return s.download(n)};e.receive({...r,...i===void 0?{}:{audio:{...i,fetch:c}},...o===void 0?{}:{images:[{...o,fetch:c}]}})}}#b(e,t){if(this.#l+=1,this.#l!==1&&this.#l%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.#l,Gi.length-1);return Gi[e]??1000}#_(){vg(this.#e,{recursive:!0,force:!0})}#A(){try{Hi(this.#e,448);for(let e of wg(this.#e))Hi(bg(this.#e,e),384)}catch{}}}var Ig={ownJids:new Set,sentIds:[]};function Cg(e,t=Ig){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 p=Zt(n),f=e.key?.remoteJidAlt,d=f===null||f===void 0?void 0:Zt(f);if(!(t.ownJids.has(p)||d!==void 0&&t.ownJids.has(d)))return}if(n.endsWith("@g.us")||n==="status@broadcast")return;let i=e.message,o=i?.conversation??i?.extendedTextMessage?.text??i?.imageMessage?.caption??i?.videoMessage?.caption??i?.documentMessage?.caption??"";if(o.trim()===""&&(i?.audioMessage??void 0)===void 0&&yo(e)===void 0)return;let s=e.messageTimestamp,c=typeof s==="number"?s:typeof s?.toNumber==="function"?s.toNumber():void 0,l=Mg(n,e.key?.remoteJidAlt),a=e.pushName;return{...r===null||r===void 0?{}:{providerMessageId:r},peerId:l,senderHandle:vo(l),...a===null||a===void 0||a===""?{}:{senderName:a},text:o,receivedAt:new Date(c===void 0?Date.now():c*1000).toISOString()}}function Pg(e){let t=e.message?.audioMessage;if(t===null||t===void 0)return;let n=wo(t.fileLength);return{mimeType:t.mimetype??"audio/ogg",...typeof t.seconds==="number"?{durationS:t.seconds}:{},...n===void 0?{}:{sizeBytes:n}}}function yo(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=wo(r.fileLength);return i===void 0?{}:{sizeBytes:i}}function wo(e){return typeof e==="number"?e:typeof e?.toNumber==="function"?e.toNumber():void 0}function Mg(e,t){if(e.endsWith("@s.whatsapp.net"))return e;if(t?.endsWith("@s.whatsapp.net")===!0)return t;return e}function Zt(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 vo(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 es(e){return e.includes("@")?e:`${vo(e)}@s.whatsapp.net`}async function Rg(){let e=await import("./index-ye2yb3xf.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),o=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{...o===void 0?{}:{download:(s)=>o(s,"buffer",{})},connect:async({authDir:s,deviceName:c,onUpdate:l,onCreds:a,onMessages:p})=>{let{state:f,saveCreds:d}=await i(s),u=r({auth:f,printQRInTerminal:!1,browser:[c??"Ubuntu","Chrome","22.04.4"],logger:Lg(),markOnlineOnConnect:!1});return u.ev.on("connection.update",l),u.ev.on("creds.update",async()=>{await d(),await a()}),u.ev.on("messages.upsert",p),u}}}function Lg(){let e=()=>{},t={level:"silent",trace:e,debug:e,info:e,warn:e,error:e,fatal:e};return t.child=()=>t,t}function ts(e){return new Promise((t)=>setTimeout(t,e))}var xg="./.whatsapp",dr=(e)=>{let t=zn(e.config,"authDir")??xg,n=Gl(t)?t:Yl(e.dir,t),r=e.config.api,i=zn(e.config,"pairWith"),o=i===void 0?void 0:i.replace(/[^0-9]/g,"");if(i!==void 0&&!/^[0-9]{6,20}$/.test(o??""))throw new Fn({code:"whatsapp_pair_with_invalid",message:`Channel "${e.id}" has a pairWith that is not a WhatsApp number: "${i}".`,hint:"Write the digits with the country code, with or without a + (for example +8801711223344 or 8801711223344); spaces and dashes are normalised away. The agent still starts — a channel is optional, so this one is reported broken rather than blocking the load.",field:`channels[${e.id}].pairWith`});let s=zn(e.config,"deviceName");if(s!==void 0&&!/^[\x20-\x7e]{1,32}$/.test(s))throw new Fn({code:"whatsapp_device_name_invalid",message:`Channel "${e.id}" has a deviceName outside 1-32 printable ASCII characters: "${s}".`,hint:"The deviceName is the bracket of the phone's Linked-devices label, so WhatsApp validates it: keep it 1-32 printable ASCII characters (letters, digits, spaces, punctuation). The agent still starts — a channel is optional, so this one is reported broken rather than blocking the load.",field:`channels[${e.id}].deviceName`});let c=e.config.pairingDelayMs;return new go({id:e.id,authDir:n,...o===void 0?{}:{pairWith:o},...s===void 0?{}:{deviceName:s},...typeof c==="number"?{pairingDelayMs:c}:{},...r===void 0?{}:{api:r}})};var Dg="0.1.0",bo={name:"whatsapp",version:Dg,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["web.whatsapp.com","*.whatsapp.net"]},{kind:"fs",paths:["<agent>/.whatsapp"],mode:"write"}],setup(e){e.defineChannel("whatsapp",dr)}};function zn(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}import{spawn as py}from"node:child_process";import{readFile as jg}from"node:fs/promises";class ln 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 Ug=new Set(["127.0.0.1","localhost","[::1]","169.254.170.2","169.254.170.23","[fd00:ec2::23]"]),zg=300000;function pr(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:"&&Ug.has(r.hostname)))return;let i;return async()=>{if(i?.expiration!==void 0&&i.expiration.getTime()-Date.now()>zg)return i;let o=e.AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE,s=o!==void 0&&o!==""?(await jg(o,"utf8")).trim():e.AWS_CONTAINER_AUTHORIZATION_TOKEN,c=await t(r,{headers:s===void 0||s===""?{}:{authorization:s},signal:AbortSignal.timeout(5000)}),l=await c.text(),a={};try{let g=JSON.parse(l);if(typeof g==="object"&&g!==null)a=g}catch{}let p=(...g)=>{for(let y of g)if(typeof a[y]==="string")return a[y];return};if(c.status>=400)throw new ln(c.status,p("code","Code"),p("message","Message"));let f=p("AccessKeyId"),d=p("SecretAccessKey");if(!c.ok||f===void 0||d===void 0)throw Error(`The credentials endpoint answered ${c.status} without AccessKeyId and SecretAccessKey.`);let u=p("Token"),m=p("Expiration");return i={accessKeyId:f,secretAccessKey:d,...u===void 0?{}:{sessionToken:u},...m===void 0?{}:{expiration:new Date(m)}},i}}var Fg={ThrottlingException:429,ServiceUnavailableException:503,InternalServerException:500,ModelNotReadyException:503,ModelStreamErrorException:500,ModelTimeoutException:408},Bg=/ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|socket hang up|TimeoutError/;function Kg(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 qg(e,t,n,r){let{name:i,message:o,status:s}=Kg(e),c=Fg[i];if(c!==void 0){let p=s??c;return{retryable:!0,status:p,error:new rt({code:"model_http_error",message:`Bedrock ${i} for ${t} in ${n}.`,detail:o,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:p,cause:e})}}if(i==="CredentialsRefusedError"){let p=e,f=typeof p.status==="number"?p.status:403,d=typeof p.code==="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(p.code)?p.code:void 0;if(f>=500)return{retryable:!0,status:f,error:new rt({code:d??"bedrock_credentials_unavailable",message:`The AWS credentials endpoint could not issue credentials for Bedrock (${t} in ${n}): status ${f}${d===void 0?"":`, ${d}`}${typeof p.detail==="string"?` — ${p.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:f,cause:e})};return{retryable:!1,status:f,error:new rt({code:d??"bedrock_credentials_refused",message:`The AWS credentials endpoint refused to issue credentials for Bedrock (${t} in ${n}): status ${f}${d===void 0?"":`, ${d}`}${typeof p.detail==="string"?` — ${p.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:f,cause:e})}}let l=/responded with status: (\d{3})/.exec(o);if(i==="CredentialsProviderError"&&l!==null)return{retryable:!1,status:Number(l[1]),error:new rt({code:"bedrock_credentials_refused",message:`The AWS credentials endpoint refused to issue credentials for Bedrock (${t} in ${n}): status ${l[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(l[1]),cause:e})};if(i==="CredentialsProviderError"||/Could not load credentials/i.test(o))return{retryable:!1,status:void 0,error:new rt({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"||s===403)return{retryable:!1,status:403,error:new rt({code:"model_access_denied",message:`Bedrock refused ${t} in ${n}: these credentials may not invoke it.`,detail:o,hint:/being verified/i.test(o)?"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"||s===404)return{retryable:!1,status:404,error:new rt({code:"model_not_found",message:`Bedrock has no model ${t} in ${n}.`,detail:o,hint:/use case details/i.test(o)?"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(Bg.test(`${i} ${o}`))return{retryable:!0,status:void 0,error:new rt({code:"model_unreachable",message:`Cannot reach Bedrock in ${n}.`,detail:o,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 a=s??400;return{retryable:!1,status:a,error:new rt({code:"model_http_error",message:`Bedrock ${i} for ${t}.`,detail:o,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:a,cause:e})}}var fr={cachePoint:{type:"default"}},Zg={"image/png":"png","image/jpeg":"jpeg","image/gif":"gif","image/webp":"webp"};function _o(e){return/(^|[./])anthropic\.claude|(^|[./])amazon\.nova/.test(e)}function ko(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 un(e){if(/(^|[./])openai\./.test(e))return"openai";let t=ko(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 So(e){let t=ko(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 To(e){return un(e)==="adaptive"||/(^|[./])openai\.gpt-6/.test(e)}function Wg(e,t){let n=[];if(un(e.id)==="adaptive"&&e.reasoningEffort==="none"&&So(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(To(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 Jg=32768,Hg=16384,Vg={minimal:1024,low:2048,medium:8192,high:16384};function Gg(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 Yg(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:Gg(n.arguments)}});return t}function Xg(e){if(e.role==="assistant")return{role:"assistant",content:Yg(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>
|
|
250
|
+
`)+p}let o=await t.forgetMemory({ids:r}),s=o.notes.length===0?`Nothing was deleted from ${i(o.scope)}.`:`Deleted ${o.notes.length} ${o.notes.length===1?"note":"notes"} from ${i(o.scope)}; they will not be recalled again.`,c=o.missing.length===0?"":` No note has ${o.missing.length===1?"the id":"the ids"} ${o.missing.join(", ")}: already gone, or not yours to delete here.`;return s+c}},vg=[ug,fg,wg,gg],Yk=vg.map((e)=>e.spec.slug);var po=[{path:"tools.local",means:"built-in tools: now, memory_write, memory_forget, artifact_read",agentListed:!0},{path:"tools.providers",means:"where tools come from, as a map — {system: {}} for shell and files, {web: {backend: tavily, apiKeyEnv: TAVILY_API_KEY}} for the internet. Several at once",toAgent:"A writeRoots key inside is refused",agentListed:!0},{path:"tools.pinned",means:"the tools from those providers this agent may call",agentListed:!0},{path:"tools.policy.allow",means:'rules permitting a call: "exec", or narrower like "exec(git *)". Also what lets a mutating tool run in a turn that has read untrusted content',agentListed:!0},{path:"tools.policy.deny",means:"rules refusing a call. Beats any allow rule",toAgent:"Replacing these is refused: it is the one edit whose only purpose is to remove a restriction someone set",agentListed:!0,confirm:"Deny rules are the restrictions that beat every allow rule. Replacing them removes whatever was deliberately put out of reach."},{path:"tools.policy.mode",means:"allow | ask | deny — for calls no rule mentions",agentListed:!0},{path:"tools.untrusted.onMutate",means:"refuse | confirm | allow — what happens when a tool that changes something is asked for in a turn that has read outside content",toAgent:'Cannot be set to "allow"',agentListed:!0,confirm:'Setting this to "allow" turns off the check that stops text from outside the conversation driving a tool that changes things. A fetched page that says "now delete the backups" would be acted on.'},{path:"tools.dialect",means:"nlt | native — how tool calls are written",agentListed:!0},{path:"description",means:"what this agent is for, in one line of at most 200 characters. The person's other agents see it beside this one in ask_agent",agentListed:!0},{path:"model.main.id",means:"the model this agent runs on",agentListed:!0},{path:"model.main.temperature",means:"0 to 2",agentListed:!0},{path:"model.main.maxTokens",means:"the most one reply may generate; unset lets the endpoint decide",agentListed:!1},{path:"tools.budget.max",means:"how many tools the model is shown at once, built-ins included",agentListed:!1},{path:"model.main.reasoningEffort",means:"none | minimal | low | medium | high | xhigh | max — how hard a reasoning model thinks",agentListed:!1},{path:"model.main",means:"the main model as a whole role, {api, id, baseUrl or options, apiKeyEnv, capabilities, ...}; replaces it in one write",agentListed:!1},{path:"model.<role>",means:"a named model role, {id, api or baseUrl, apiKeyEnv, ...}; a schedule or message runs on it with role: <name>",agentListed:!1},{path:"limits.maxSteps",means:"tool calls allowed in one turn",agentListed:!0},{path:"limits.toolTimeoutMs",means:"how long any single tool may take",agentListed:!0},...["static","volatile","reminder","total"].map((e)=>({path:`context.budgets.${e}`,means:`token budget for the ${e==="total"?"whole workspace":`${e} tier`}; a file over it stops the agent loading`,agentListed:!1})),{path:"limits.noProgress",means:"when a turn is stopped for going nowhere, as a map: {identicalCalls: <n, default 3>, sameTool: <n, off when absent>}",agentListed:!1},{path:"limits.noProgress.sameTool",means:"stop a turn after this many calls in a row to one tool, whatever the arguments. Absent, off",agentListed:!1},{path:"context.modelIdentity",means:"shown or hidden: whether the agent can see which model it runs on (hidden keeps tuning settable)",agentListed:!1},{path:"context.window",means:"the token budget for a whole request; unset uses the model's known window",agentListed:!1},{path:"context.observationMaxTokens",means:"how much of a tool's output reaches the model",agentListed:!0},{path:"tools.eventDetail",means:"none | redacted — whether tool events carry the call's arguments and output",agentListed:!1},{path:"context.rules.onExceed",means:"fail | warn — whether too many counted rules in the workspace refuses the load",agentListed:!1},{path:"channels",means:"how people reach this agent, as a list — [{type: telegram, id: tg, tokenEnv: TELEGRAM_BOT_TOKEN, mode: longpoll}]. The token goes in the .env",toAgent:"The token itself goes in the .env, which only a person can write. allowFrom is refused here: who may talk to you is not yours to decide",agentListed:!0},{path:"delivery",means:"where a reply goes when a turn has no origin — {default: tg}. Names a channel id, not a channel type",agentListed:!0},{path:"delivery.reply",means:"channel replies: all (every step's text, default) or final (the last step's only)",agentListed:!0},{path:"schedules",means:'what runs unattended, as a list — [{id, kind: cron|every|at, expr, task, deliver}]. expr is a 5- or 6-field cron, a duration like 15m, or an ISO instant; deliver is {channel, to} or the literal "none"',toAgent:"Only `serve` fires these; under `run` they are validated and listed and no timer starts. deliver.to is the address a reply is *sent* to — on Telegram the numeric chat id, never an @handle, which addresses a channel and not a person. It is the id inbound messages arrive on, so read it off your own session keys (tg:<id>); allowFrom holds handles and confers nothing here. Set role to name a model other than main. The whole list is replaced, so read it first",agentListed:!0},{path:"media",means:"voice notes, spoken replies and images: {transcription, speech, image}, each {provider: openai|aws, model, apiKeyEnv, options}",toAgent:"image adds image_generate after a restart; filling in the key variable is the person's",agentListed:!0},{path:"server.enabled",means:"true | false — serve the HTTP API on 127.0.0.1",toAgent:"host and tokenEnv are refused: binding anywhere reachable is not yours to decide",agentListed:!0},{path:"server.port",means:"port for the HTTP API",agentListed:!0},{path:"channels[].allowFrom",means:"who may talk to this agent through a channel. Empty or absent refuses everyone — a bot that is connected, healthy and answering nobody is almost always this",agentListed:!1,via:"config allow"},{path:"server.host",means:"the address the HTTP API binds. 127.0.0.1 is local only; anything else is reachable from the network",agentListed:!1},{path:"server.tokenEnv",means:"the env var holding the bearer token the API requires. Without it the API is unauthenticated",agentListed:!1},{path:"delegation.offer",means:`what this agent takes on when another member's agent asks it, as a map: {task: "<one line>", artifact: {type: object, properties: {...}, required: [...]}}. The agents whose delegation.to names this one are reloaded so their roster shows it`,agentListed:!1},{path:"delegation.to",means:`the other members' agents this one may ask, by id, or "*" for every agent that offers. A peer ask is one hop: the asked agent answers, and cannot ask onward`,agentListed:!1},{path:"delegation.ask",means:"true or false: this agent asks the person's other agents (ask_agent) and they may ask it. Both have to say yes; an agent assigned to nobody that says yes is a shared agent anyone's agent may ask",agentListed:!1},{path:"sessions.scope",means:"how a turn's conversation is chosen: channel-peer (one per surface, the default), owner (the owner's turns from every surface share one), or peer (owner, and every registered participant gets one too)",agentListed:!1},{path:"memory.shared",means:"read and write the memory this agent's owner's agents share (agents:<owner>). Default true; false keeps memory_write private",agentListed:!1},{path:"subagents",means:"children that run work in their own context, as a list of {name, task, tools, route?: {tools}, spawn?, model?, maxSteps?, timeoutMs?}. route runs a child for those tool calls; spawn: true lets the model start it with delegate. Each tool must be pinned, and each routed slug belongs to one child",agentListed:!1},{path:"skills.trusted",means:"the skills whose scripts may run, by name. A skill not listed is still used for its steps, and its scripts are documentation only. Absent, every skill's scripts run",agentListed:!1},{path:"tools.providers.<id>.writeRoots",means:"the directories a file tool may write to, for that provider. Nothing outside them is writable — and this binds file tools only, never exec, which carries its target inside a shell string",agentListed:!1}],Xk=po.filter((e)=>e.agentListed).map((e)=>e.path),Qk=po.filter((e)=>e.via===void 0&&!e.path.includes("<")&&!e.path.includes("[")).map((e)=>e.path);var e0=["Summarise the conversation above for your own future reference. You are writing notes to yourself, not a report for a person.","","The person's own requests are preserved verbatim below your summary, so do not restate them.","Keep: decisions taken and why, facts established by tool results, and anything still outstanding.","Drop: pleasantries, your own reasoning, and anything already superseded.","Write plain prose under 300 words. No headings, no preamble, no closing summary.","End with one line naming what this summary does not cover, so a later step knows to ask rather than assume."].join(`
|
|
251
|
+
`);var t0=(()=>{let e=Symbol.for(`${er.slug}.liveRuntimes`),t=globalThis;return t[e]??=new Set,t[e]})();var bg="id, session_key, turn_id, role, content, tool_calls, tool_call_id, origin, tainted, created_at",n0=bg.split(", ").map((e)=>`m.${e}`).join(", ");var r0=new Set("a an and are as at be but by do does for from had has have he her his i if in is it its me my not of on or our she that the their them then there they this to was we were what when which who will with you your would could should im ive dont its ill".split(" ")),$g=65536,Eg=1000,Gi=[1000,2000,5000,15000,30000,60000],Ag=3,Og=512,Yi=60000,Ng=180000,Ig=3000,Cg=401,Pg=515,Mg={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 Xi(e){let t=e.authState?.creds;if(t===void 0)return!0;return t.registered===!0||t.account!==void 0&&t.account!==null}function Qi(){return typeof globalThis.Bun<"u"}class mo{id;type="whatsapp";limits={maxMessageChars:$g,idempotentSend:!1,attachments:!0,voiceNotes:!0,minSendIntervalMs:Eg};alwaysAllow;#e;#n;#t;#r;#o;#i;#a;#s;#c=!1;#l=0;#u=!1;#d=!0;#f=0;#p=!1;#h=new Set;#m=[];#w;#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??Ig,this.#o=e.api}async start(e){if(this.#c)return;if(this.#c=!0,this.#a=e,Qi())e.error(Mg);this.#w=this.#v(e)}async stop(){if(!this.#c)return;this.#c=!1;try{this.#s?.end()}catch{}this.#s=void 0,this.#y?.(),this.#y=void 0,await this.#w?.catch(()=>{}),this.#w=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(es(e.recipient),n===void 0?{text:e.text}:n.mimeType.startsWith("audio/")?{audio:await Vi(n.path),mimetype:"audio/ogg; codecs=opus",ptt:!0}:{image:await Vi(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>Og)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.#_();try{this.#s?.end()}catch{}this.#s=void 0,this.#l=0,this.#a?.status("disconnected","unpaired — scan the next QR to link a device"),this.#y?.(),this.#y=void 0}async typing(e){await this.#s?.sendPresenceUpdate("composing",es(e))}async#v(e){while(this.#c&&!this.#p){try{let n=this.#o??await jg();this.#i=n,_g(this.#e,{recursive:!0,mode:448}),this.#u=this.#n!==void 0&&this.#n!=="";let r=await n.connect({authDir:this.#e,...this.#t===void 0?{}:{deviceName:this.#t},onUpdate:(i)=>this.#T(e,i),onCreds:()=>this.#A(),onMessages:(i)=>this.#$(e,i)});this.#s=r,this.#d=Xi(r),await this.#k(e,r),await this.#S()}catch(n){if(!this.#c)return;this.#b(e,n)}if(!this.#c)return;let t=this.#g;if(this.#g=!1,!t)await ts(this.#E())}}async#k(e,t){let n=this.#n;if(n===void 0||n==="")return;if(Xi(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()+Yi).toISOString()});return}try{if(await ts(this.#r),!this.#c)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()+Ng).toISOString()})}catch(r){this.#u=!1,this.#b(e,r)}}#S(){if(!this.#c)return Promise.resolve();return new Promise((e)=>{this.#y=e})}#y;#T(e,t){if(t.qr!==void 0&&t.qr!==""&&!this.#u){e.status("needs_input",`scan to pair channel "${this.id}"`,{kind:"qr",payload:t.qr,expiresAt:new Date(Date.now()+Yi).toISOString()});return}if(t.connection==="open"){this.#f=0,this.#l=0;let n=this.#s?.user;if(this.#h.clear(),n?.id!==void 0)this.#h.add(Zt(n.id));if(n?.lid!==void 0)this.#h.add(Zt(n.lid));e.status("connected","paired");return}if(t.connection==="close"){let n=t.lastDisconnect?.error?.output?.statusCode;if(n===Cg)if(this.#_(),this.#d)this.#f=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.#f+=1,this.#l+=1,this.#f>=Ag)this.#p=!0,e.status("error",`pairing refused ${this.#f} times — not asking again`),e.error({code:"whatsapp_pairing_refused",message:`WhatsApp refused ${this.#f} pairing attempts for channel "${this.id}" and none completed.`,hint:Qi()?"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===Pg)this.#g=!0;else if(this.#l+=1,this.#l===1||this.#l%8===0)e.status("disconnected",t.lastDisconnect?.error?.message??"connection closed");this.#s=void 0,this.#y?.(),this.#y=void 0}}#$(e,t){if(t.type!=="notify")return;for(let n of t.messages){let r=Lg(n,{ownJids:this.#h,sentIds:this.#m});if(r===void 0)continue;let i=xg(n),o=yo(n),s=this.#i,c=async()=>{if(s?.download===void 0)throw Error("this Baileys build cannot download media");return s.download(n)};e.receive({...r,...i===void 0?{}:{audio:{...i,fetch:c}},...o===void 0?{}:{images:[{...o,fetch:c}]}})}}#b(e,t){if(this.#l+=1,this.#l!==1&&this.#l%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.#l,Gi.length-1);return Gi[e]??1000}#_(){Sg(this.#e,{recursive:!0,force:!0})}#A(){try{Hi(this.#e,448);for(let e of kg(this.#e))Hi(Tg(this.#e,e),384)}catch{}}}var Rg={ownJids:new Set,sentIds:[]};function Lg(e,t=Rg){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 p=Zt(n),f=e.key?.remoteJidAlt,d=f===null||f===void 0?void 0:Zt(f);if(!(t.ownJids.has(p)||d!==void 0&&t.ownJids.has(d)))return}if(n.endsWith("@g.us")||n==="status@broadcast")return;let i=e.message,o=i?.conversation??i?.extendedTextMessage?.text??i?.imageMessage?.caption??i?.videoMessage?.caption??i?.documentMessage?.caption??"";if(o.trim()===""&&(i?.audioMessage??void 0)===void 0&&yo(e)===void 0)return;let s=e.messageTimestamp,c=typeof s==="number"?s:typeof s?.toNumber==="function"?s.toNumber():void 0,l=Dg(n,e.key?.remoteJidAlt),a=e.pushName;return{...r===null||r===void 0?{}:{providerMessageId:r},peerId:l,senderHandle:vo(l),...a===null||a===void 0||a===""?{}:{senderName:a},text:o,receivedAt:new Date(c===void 0?Date.now():c*1000).toISOString()}}function xg(e){let t=e.message?.audioMessage;if(t===null||t===void 0)return;let n=wo(t.fileLength);return{mimeType:t.mimetype??"audio/ogg",...typeof t.seconds==="number"?{durationS:t.seconds}:{},...n===void 0?{}:{sizeBytes:n}}}function yo(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=wo(r.fileLength);return i===void 0?{}:{sizeBytes:i}}function wo(e){return typeof e==="number"?e:typeof e?.toNumber==="function"?e.toNumber():void 0}function Dg(e,t){if(e.endsWith("@s.whatsapp.net"))return e;if(t?.endsWith("@s.whatsapp.net")===!0)return t;return e}function Zt(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 vo(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 es(e){return e.includes("@")?e:`${vo(e)}@s.whatsapp.net`}async function jg(){let e=await import("./index-hgm2gchq.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),o=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{...o===void 0?{}:{download:(s)=>o(s,"buffer",{})},connect:async({authDir:s,deviceName:c,onUpdate:l,onCreds:a,onMessages:p})=>{let{state:f,saveCreds:d}=await i(s),u=r({auth:f,printQRInTerminal:!1,browser:[c??"Ubuntu","Chrome","22.04.4"],logger:Ug(),markOnlineOnConnect:!1});return u.ev.on("connection.update",l),u.ev.on("creds.update",async()=>{await d(),await a()}),u.ev.on("messages.upsert",p),u}}}function Ug(){let e=()=>{},t={level:"silent",trace:e,debug:e,info:e,warn:e,error:e,fatal:e};return t.child=()=>t,t}function ts(e){return new Promise((t)=>setTimeout(t,e))}var zg="./.whatsapp",dr=(e)=>{let t=zn(e.config,"authDir")??zg,n=Yl(t)?t:Xl(e.dir,t),r=e.config.api,i=zn(e.config,"pairWith"),o=i===void 0?void 0:i.replace(/[^0-9]/g,"");if(i!==void 0&&!/^[0-9]{6,20}$/.test(o??""))throw new Fn({code:"whatsapp_pair_with_invalid",message:`Channel "${e.id}" has a pairWith that is not a WhatsApp number: "${i}".`,hint:"Write the digits with the country code, with or without a + (for example +8801711223344 or 8801711223344); spaces and dashes are normalised away. The agent still starts — a channel is optional, so this one is reported broken rather than blocking the load.",field:`channels[${e.id}].pairWith`});let s=zn(e.config,"deviceName");if(s!==void 0&&!/^[\x20-\x7e]{1,32}$/.test(s))throw new Fn({code:"whatsapp_device_name_invalid",message:`Channel "${e.id}" has a deviceName outside 1-32 printable ASCII characters: "${s}".`,hint:"The deviceName is the bracket of the phone's Linked-devices label, so WhatsApp validates it: keep it 1-32 printable ASCII characters (letters, digits, spaces, punctuation). The agent still starts — a channel is optional, so this one is reported broken rather than blocking the load.",field:`channels[${e.id}].deviceName`});let c=e.config.pairingDelayMs;return new mo({id:e.id,authDir:n,...o===void 0?{}:{pairWith:o},...s===void 0?{}:{deviceName:s},...typeof c==="number"?{pairingDelayMs:c}:{},...r===void 0?{}:{api:r}})};var Fg="0.1.0",bo={name:"whatsapp",version:Fg,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["web.whatsapp.com","*.whatsapp.net"]},{kind:"fs",paths:["<agent>/.whatsapp"],mode:"write"}],setup(e){e.defineChannel("whatsapp",dr)}};function zn(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}import{spawn as wy}from"node:child_process";import{readFile as Bg}from"node:fs/promises";class ln 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 Kg=new Set(["127.0.0.1","localhost","[::1]","169.254.170.2","169.254.170.23","[fd00:ec2::23]"]),qg=300000;function hr(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:"&&Kg.has(r.hostname)))return;let i;return async()=>{if(i?.expiration!==void 0&&i.expiration.getTime()-Date.now()>qg)return i;let o=e.AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE,s=o!==void 0&&o!==""?(await Bg(o,"utf8")).trim():e.AWS_CONTAINER_AUTHORIZATION_TOKEN,c=await t(r,{headers:s===void 0||s===""?{}:{authorization:s},signal:AbortSignal.timeout(5000)}),l=await c.text(),a={};try{let g=JSON.parse(l);if(typeof g==="object"&&g!==null)a=g}catch{}let p=(...g)=>{for(let y of g)if(typeof a[y]==="string")return a[y];return};if(c.status>=400)throw new ln(c.status,p("code","Code"),p("message","Message"));let f=p("AccessKeyId"),d=p("SecretAccessKey");if(!c.ok||f===void 0||d===void 0)throw Error(`The credentials endpoint answered ${c.status} without AccessKeyId and SecretAccessKey.`);let u=p("Token"),m=p("Expiration");return i={accessKeyId:f,secretAccessKey:d,...u===void 0?{}:{sessionToken:u},...m===void 0?{}:{expiration:new Date(m)}},i}}var Zg={ThrottlingException:429,ServiceUnavailableException:503,InternalServerException:500,ModelNotReadyException:503,ModelStreamErrorException:500,ModelTimeoutException:408},Wg=/ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|socket hang up|TimeoutError/;function Jg(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 Hg(e,t,n,r){let{name:i,message:o,status:s}=Jg(e),c=Zg[i];if(c!==void 0){let p=s??c;return{retryable:!0,status:p,error:new st({code:"model_http_error",message:`Bedrock ${i} for ${t} in ${n}.`,detail:o,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:p,cause:e})}}if(i==="CredentialsRefusedError"){let p=e,f=typeof p.status==="number"?p.status:403,d=typeof p.code==="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(p.code)?p.code:void 0;if(f>=500)return{retryable:!0,status:f,error:new st({code:d??"bedrock_credentials_unavailable",message:`The AWS credentials endpoint could not issue credentials for Bedrock (${t} in ${n}): status ${f}${d===void 0?"":`, ${d}`}${typeof p.detail==="string"?` — ${p.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:f,cause:e})};return{retryable:!1,status:f,error:new st({code:d??"bedrock_credentials_refused",message:`The AWS credentials endpoint refused to issue credentials for Bedrock (${t} in ${n}): status ${f}${d===void 0?"":`, ${d}`}${typeof p.detail==="string"?` — ${p.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:f,cause:e})}}let l=/responded with status: (\d{3})/.exec(o);if(i==="CredentialsProviderError"&&l!==null)return{retryable:!1,status:Number(l[1]),error:new st({code:"bedrock_credentials_refused",message:`The AWS credentials endpoint refused to issue credentials for Bedrock (${t} in ${n}): status ${l[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(l[1]),cause:e})};if(i==="CredentialsProviderError"||/Could not load credentials/i.test(o))return{retryable:!1,status:void 0,error:new st({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"||s===403)return{retryable:!1,status:403,error:new st({code:"model_access_denied",message:`Bedrock refused ${t} in ${n}: these credentials may not invoke it.`,detail:o,hint:/being verified/i.test(o)?"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"||s===404)return{retryable:!1,status:404,error:new st({code:"model_not_found",message:`Bedrock has no model ${t} in ${n}.`,detail:o,hint:/use case details/i.test(o)?"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(Wg.test(`${i} ${o}`))return{retryable:!0,status:void 0,error:new st({code:"model_unreachable",message:`Cannot reach Bedrock in ${n}.`,detail:o,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 a=s??400;return{retryable:!1,status:a,error:new st({code:"model_http_error",message:`Bedrock ${i} for ${t}.`,detail:o,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:a,cause:e})}}var fr={cachePoint:{type:"default"}},Vg={"image/png":"png","image/jpeg":"jpeg","image/gif":"gif","image/webp":"webp"};function _o(e){return/(^|[./])anthropic\.claude|(^|[./])amazon\.nova/.test(e)}function ko(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 un(e){if(/(^|[./])openai\./.test(e))return"openai";let t=ko(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 So(e){let t=ko(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 To(e){return un(e)==="adaptive"||/(^|[./])openai\.gpt-6/.test(e)}function Gg(e,t){let n=[];if(un(e.id)==="adaptive"&&e.reasoningEffort==="none"&&So(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(To(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 Yg=32768,Xg=16384,Qg={minimal:1024,low:2048,medium:8192,high:16384};function ey(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 ty(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:ey(n.arguments)}});return t}function ny(e){if(e.role==="assistant")return{role:"assistant",content:ty(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>
|
|
252
252
|
${e.content}
|
|
253
|
-
</system>`:e.content,n=t===""?[]:[{text:t}];for(let r of e.images??[])n.push({image:{format:Zg[r.mediaType],source:{bytes:Uint8Array.from(Buffer.from(r.data,"base64"))}}});return{role:"user",content:n}}function Qg(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 ey(e,t){let n=_o(e.model)&&t.capabilities?.promptCache!=="none",r=[],i=[],o=!0;for(let y of Qg(e.messages)){if(o&&y.role==="system"){if(y.content!=="")r.push({text:y.content});if(n&&y.cacheBreakpoint===!0)r.push(fr);continue}o=!1;let{role:w,content:v}=Xg(y);if(n&&y.cacheBreakpoint===!0&&v.length>0)v.push(fr);if(v.length===0)continue;let b=i.at(-1);if(b!==void 0&&b.role===w)b.content=[...b.content??[],...v];else i.push({role:w,content:v})}let s=i.at(-1),c=/(^|[./])amazon\.nova/.test(e.model)&&(s?.content??[]).some((y)=>y.toolResult!==void 0);if(n&&s!==void 0&&!c&&s.content?.at(-1)?.cachePoint===void 0)s.content=[...s.content??[],fr];let l=un(e.model),a=e.reasoningEffort,p=l==="budget"&&a!==void 0?Vg[a==="xhigh"||a==="max"?"high":a]:void 0,f=l==="adaptive"?ty(e.model,a):void 0,d=p===void 0&&!To(e.model),u=p!==void 0?Math.max(e.maxTokens??0,p+Hg):f?.thinking===!0?e.maxTokens??Jg:e.maxTokens,m={...u===void 0?{}:{maxTokens:u},...!d||e.temperature===void 0?{}:{temperature:e.temperature},...!d||e.topP===void 0?{}:{topP:e.topP}},g=p!==void 0?{thinking:{type:"enabled",budget_tokens:p}}:f!==void 0?f.fields:l==="openai"&&a!==void 0&&a!=="none"?{reasoning:{effort:a==="minimal"?"low":a}}:void 0;return{modelId:e.model,messages:i,...r.length===0?{}:{system:r},...Object.keys(m).length===0?{}:{inferenceConfig:m},...e.tools===void 0||e.tools.length===0?{}:{toolConfig:{tools:e.tools.map((y)=>({toolSpec:{name:y.name,description:y.description,inputSchema:{json:y.parameters}}}))}},...g===void 0?{}:{additionalModelRequestFields:g}}}function ty(e,t){if(t===void 0)return;if(t==="none"){let n=So(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 ny={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"},ry="<thinking>",iy="</thinking>";function sy(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 $o{#e="";#n=!1;#t=!1;push(e){let t=[],n=this.#e+e;this.#e="";for(;;){let r=this.#n?iy:ry,i=n.indexOf(r);if(i===-1){let o=sy(n,r);return this.#e=n.slice(n.length-o),t.push(...this.#r(n.slice(0,n.length-o))),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*oy(e,t={}){let n=new Map,r=t.thinkingTags===!0?new $o:void 0;for await(let i of e){if(i.contentBlockStart!==void 0){let c=i.contentBlockStart.start?.toolUse;if(c!==void 0)n.set(i.contentBlockStart.contentBlockIndex??0,{kind:"tool",id:c.toolUseId??"",name:c.name??"",input:""});continue}if(i.contentBlockDelta!==void 0){let c=i.contentBlockDelta.contentBlockIndex??0,l=i.contentBlockDelta.delta;if(l?.text!==void 0){if(r!==void 0)yield*r.push(l.text);else if(l.text!=="")yield{type:"text",delta:l.text}}else if(l?.toolUse!==void 0){let a=n.get(c);if(a?.kind==="tool")a.input+=l.toolUse.input??""}else if(l?.reasoningContent!==void 0){let a=n.get(c);if(a?.kind!=="reasoning")a={kind:"reasoning",text:""},n.set(c,a);let p=l.reasoningContent;if(p.text!==void 0&&p.text!=="")a.text+=p.text,yield{type:"reasoning",delta:p.text};if(p.signature!==void 0)a.signature=p.signature;if(p.redactedContent!==void 0)a.redacted=Buffer.from(p.redactedContent).toString("base64")}continue}if(i.contentBlockStop!==void 0){let c=i.contentBlockStop.contentBlockIndex??0,l=n.get(c);if(n.delete(c),l?.kind==="tool")yield{type:"tool_call",call:{id:l.id,name:l.name,arguments:l.input}};else if(l?.kind==="reasoning")yield{type:"thinking_block",block:{text:l.text,...l.signature===void 0?{}:{signature:l.signature},...l.redacted===void 0?{}:{redacted:l.redacted}}};continue}if(i.messageStop!==void 0){if(r!==void 0)yield*r.flush();let c=i.messageStop.stopReason??"end_turn";yield{type:"finish",reason:ny[c]??c};continue}let o=i.metadata?.usage;if(o!==void 0){let{cacheReadInputTokens:c,cacheWriteInputTokens:l}=o;yield{type:"usage",promptTokens:(o.inputTokens??0)+(c??0)+(l??0),completionTokens:o.outputTokens??0,...c===void 0?{}:{cachedPromptTokens:c,cacheSource:"metadata.usage.cacheReadInputTokens"},...l===void 0?{}:{cacheWriteTokens:l}};continue}let s=i.throttlingException??i.serviceUnavailableException??i.internalServerException??i.modelStreamErrorException??i.validationException;if(s!==void 0)throw s}}var ay=async(e)=>{let t=await import("./index-wk6andxq.js"),n=e.profile===void 0?pr(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,o)=>{let s=await r.send(new t.ConverseStreamCommand(i),{abortSignal:o});if(s.stream===void 0)throw Error("Bedrock returned a ConverseStream response with no stream.");return s.stream}};function cy(e){return e instanceof Error&&/bound to a different conversation/i.test(e.message)}function ly(e){let t=!1,n=(e.messages??[]).map((r)=>{let i=(r.content??[]).filter((o)=>{let s=o.reasoningContent!==void 0;return t||=s,!s});return{...r,content:i}}).filter((r)=>r.content.length>0);return t?{...e,messages:n}:void 0}var uy=/(^|[./])amazon\.nova/,dy={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 fy(e,t){let n=Math.min(e.baseDelayMs*2**(t-1),e.maxDelayMs);return Math.round(n*(0.5+Math.random()/2))}function hy(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 mr(e=ay){return{optionsSchema:dy,capabilities:(t,n)=>{let r=n.capabilities?.promptCache===void 0&&_o(n.id)?{...t,promptCache:"bedrock"}:t;return un(n.id)==="openai"?{...r,traceAfterInput:!0}:r},warnings:(t,n)=>Wg(t,n),create(t){let n=t.options;if(n===void 0)throw new h({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(o,s){i??=e(n);let c=await i,l=ey(o,t.config),a=!1;for(let p=1;;p+=1){let f=!1;try{for await(let d of oy(await c(l,s),{thinkingTags:uy.test(t.config.id)}))f=!0,yield d;return}catch(d){if(s.aborted)return;if(!f&&!a&&cy(d)){let g=ly(l);if(g!==void 0){l=g,a=!0,t.onRetry?.({status:400,attempt:p,delayMs:0});continue}}let u=qg(d,o.model,n.region,t.field);if(f||!u.retryable||p>=r.attempts)throw u.error;let m=fy(r,p);if(t.onRetry?.({status:u.status??0,attempt:p,delayMs:m}),await hy(m,s),s.aborted)return}}}}}}}var Eo={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",mr())}};var No=16000,my=(e,t)=>new Promise((n,r)=>{let i=py("ffmpeg",["-hide_banner","-loglevel","error","-i","pipe:0"].concat(["-f","s16le","-ac","1","-ar",String(No),"pipe:1"]),{stdio:["pipe","pipe","pipe"]}),o=[],s=[],c=()=>i.kill("SIGKILL");t.addEventListener("abort",c,{once:!0}),i.stdout.on("data",(l)=>o.push(l)),i.stderr.on("data",(l)=>s.push(l)),i.on("error",(l)=>{t.removeEventListener("abort",c),r(l)}),i.on("close",(l)=>{if(t.removeEventListener("abort",c),l===0)n(new Uint8Array(Buffer.concat(o)));else r(Error(Buffer.concat(s).toString("utf8").trim()||`ffmpeg exited ${l}`))}),i.stdin.on("error",()=>{}),i.stdin.end(Buffer.from(e))});function gr(e){if(e.profile!==void 0)return{profile:e.profile};let t=pr(process.env);return t===void 0?{}:{credentials:t}}var gy={async transcribe(e){let t=await import("./index-3b3h8kyh.js"),n=new t.TranscribeStreamingClient({region:e.region,...gr(e)});return async(r,i)=>{let o=await n.send(new t.StartStreamTranscriptionCommand(r),{abortSignal:i});if(o.TranscriptResultStream===void 0)throw Error("Transcribe returned no result stream.");return o.TranscriptResultStream}},async invoke(e){let t=await import("./index-wk6andxq.js"),n=new t.BedrockRuntimeClient({region:e.region,...gr(e)});return async(r,i)=>{let o=await n.send(new t.InvokeModelCommand({modelId:r.modelId,contentType:"application/json",accept:"application/json",body:r.body}),{abortSignal:i});return new TextDecoder().decode(o.body)}},async speak(e){let t=await import("./index-9dmgk6d3.js"),n=new t.PollyClient({region:e.region,...gr(e)});return async(r,i)=>{let o=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(o.AudioStream===void 0)throw Error("Polly returned no audio.");return{bytes:await o.AudioStream.transformToByteArray(),...o.RequestCharacters===void 0?{}:{characters:o.RequestCharacters}}}},decode:my},Ao=new Set(["region","profile","languageCode","sampleRate","voiceId","engine"]),yy={safeParse(e){let t=typeof e==="object"&&e!==null?e:{},n=(i)=>({success:!1,error:{issues:[{message:i}]}}),r=Object.keys(t).find((i)=>!Ao.has(i));if(r!==void 0)return n(`unknown option "${r}" (takes ${[...Ao].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 wy(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 Oo=8192;async function*vy(e){for(let t=0;t<e.byteLength;t+=Oo)yield{AudioEvent:{AudioChunk:e.subarray(t,t+Oo)}}}function by(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 yr(e,t){if(e instanceof ln){let i=e.code!==void 0&&/^[a-z][a-z0-9_]{1,63}$/.test(e.code)?e.code:void 0;return new qt({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 qt({code:"media_provider_refused",message:`AWS refused the request (${n||"error"}): ${r}`,hint:n==="AccessDeniedException"||n==="UnrecognizedClientException"?by(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 wr(e=gy){return{optionsSchema:yy,create(t){if(t.options===void 0)throw new h({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,o;return{async transcribe(c,l){let a=wy(c.mimeType),p=c.bytes;if(a===void 0)try{p=await e.decode(c.bytes,l)}catch(f){let d=f.code==="ENOENT";throw new qt({code:"media_audio_unsupported",message:d?`Amazon Transcribe streaming cannot read ${c.mimeType}, and ffmpeg, which would convert it, is not installed.`:`${c.mimeType} could not be converted for Amazon Transcribe: ${f instanceof Error?f.message:String(f)}`,hint:d?"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 d=await(await r)({LanguageCode:n.languageCode??"en-US",MediaEncoding:a??"pcm",MediaSampleRateHertz:a===void 0?No:n.sampleRate??48000,AudioStream:vy(p)},l),u=[],m;for await(let g of d)for(let y of g.TranscriptEvent?.Transcript?.Results??[]){if(y.IsPartial===!0)continue;let w=y.Alternatives?.[0]?.Transcript;if(w!==void 0&&w!=="")u.push(w);if(y.EndTime!==void 0)m=y.EndTime}return{text:u.join(" "),...m===void 0?{}:{durationS:m}}}catch(f){if(f instanceof qt)throw f;throw yr(f,t.field)}},async synthesize(c,l){o??=e.speak(n);try{let p=await(await o)({text:c.text,voiceId:n.voiceId??"Joanna",engine:n.engine??"neural",...n.languageCode===void 0?{}:{languageCode:n.languageCode}},l);return{bytes:p.bytes,mimeType:"audio/ogg; codecs=opus",...p.characters===void 0?{}:{characters:p.characters}}}catch(a){throw yr(a,t.field)}},async generateImage(c,l){let[a,p]=c.size.split("x").map(Number);i??=e.invoke(n);let f;try{f=await(await i)({modelId:t.config.model??"amazon.nova-canvas-v1:0",body:JSON.stringify({taskType:"TEXT_IMAGE",textToImageParams:{text:c.prompt},imageGenerationConfig:{numberOfImages:1,width:a,height:p}})},l)}catch(m){throw yr(m,t.field)}let d=JSON.parse(f),u=d.images?.[0];if(u===void 0)throw new qt({code:"media_provider_empty",message:`Nova Canvas returned no image${d.error===void 0?"":`: ${d.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(u,"base64"),mimeType:"image/png"}}}}}}var _y="0.1.0",Io={name:"media-aws",version:_y,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["transcribestreaming.*.amazonaws.com","bedrock-runtime.*.amazonaws.com","polly.*.amazonaws.com"]}],setup(e){e.defineMediaProvider("aws",wr())}};import{mkdirSync as ky,readFileSync as Sy,renameSync as Ty,writeFileSync as $y}from"node:fs";import{dirname as Ey,isAbsolute as Ay,join as Co,resolve as Oy}from"node:path";import{mkdirSync as ew,readFileSync as Jo,renameSync as tw,writeFileSync as nw}from"node:fs";import{dirname as rw,isAbsolute as iw,join as Uo,resolve as sw}from"node:path";var dn=1,Po="tools.cache.json";function fn(e){return Ay(e)?Co(e,re.stateDir,Po):Co(Oy(e),re.stateDir,Po)}function Ny(e){return typeof e==="object"&&e!==null&&typeof e.slug==="string"}function Mo(e){let t={version:dn,provider:"composio",fetchedAt:"",baseUrl:"",tools:{}},n;try{n=Sy(fn(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!==dn)return t;let o={};for(let[s,c]of Object.entries(i.tools??{}))if(Ny(c))o[s]=c;return{version:dn,provider:"composio",fetchedAt:typeof i.fetchedAt==="string"?i.fetchedAt:"",baseUrl:typeof i.baseUrl==="string"?i.baseUrl:"",tools:o}}catch{return t}}function Iy(e,t,n,r){let i=fn(e);ky(Ey(i),{recursive:!0});let o={version:dn,provider:"composio",fetchedAt:r().toISOString(),baseUrl:n,tools:t},s=`${i}.${process.pid}.tmp`;return $y(s,`${JSON.stringify(o,null,2)}
|
|
254
|
-
`,"utf8"),Ty(s,i),i}function Ro(e){return new h({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 Cy(e,t,n){return new h({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 Py(e,t){return new h({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 ot(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 My(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 Ry(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 Lo(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 xo(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 Ly="https://backend.composio.dev/api/v3";function Do(e){return/\/v3$/.test(e)?e.replace(/\/v3$/,"/v3.1"):e}var xy=100;function at(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}async function vt(e){let t;try{t=await e.json()}catch{return e.statusText===""?"no detail in the response body":e.statusText}let n=at(at(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 Bo{#e;#n;#t;constructor(e){this.#e=e.apiKey,this.#n=io(e.baseUrl??Ly),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 ot(n.status,await vt(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 ot(n.status,await vt(n));let r=at(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(xy)});if(n!==void 0)i.set("cursor",n);let o=await this.#o(`/tools?${i.toString()}`,e);for(let c of o.items??[])if(typeof c.slug==="string")t.push(c.slug);let s=o.next_cursor;if(s===null||s===void 0||s===""||s===n)break;n=s}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 ot(i.status,await vt(i));let o=at(await i.json())??{},s=o.successful!==!1,c=typeof o.error==="string"&&o.error!==""?o.error:void 0;return{ok:s,data:o.data??o,...c===void 0?{}:{error:c}}}#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(`${Do(this.#n)}/tool_router/session`,{user_id:e},t);if(!n.ok)throw ot(n.status,await vt(n));let r=at(await n.json())??{},i=r.session_id;if(typeof i!=="string"||i==="")throw ot(n.status,"no session_id in the response body");return r}async executeMeta(e,t,n,r){let i=await this.#i(`${Do(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 ot(i.status,await vt(i));let o=at(await i.json())??{},s=typeof o.error==="string"&&o.error!==""?o.error:void 0;return{ok:o.successful===void 0?s===void 0:o.successful!==!1,data:o.data??o,...s===void 0?{}:{error:s}}}}function Dy(e){return no(e.input_parameters,{unsupported:(t,n)=>Cy(e.slug,t,n),rootPath:"input_parameters"})}function br(e){let t=new Set(e.tags??[]);if(t.has("destructiveHint"))return!0;return!t.has("readOnlyHint")}function Ko(e){let t=new Set(e.tags??[]);return!t.has("readOnlyHint")&&!t.has("destructiveHint")}function jy(e){let t=e.replace(/\s+/g," ").trim(),n=t.search(/\.\s|\.$/);return n===-1?t:t.slice(0,n+1)}function qo(e){let t=(e.description??e.human_description??"").trim(),n=t===""?`The ${e.slug} tool.`:jy(t),r=e.toolkit?.slug;return{slug:e.slug,provider:"composio",summary:n,whenToUse:t===""?`the task needs ${e.slug}`:t,mutating:br(e),tags:[...r===void 0?[]:[r],...br(e)?["write"]:["read"]],parameters:Dy(e)}}var Uy=8,jo=100,hn="composio_search",pn="composio_connect",Sr="composio_workbench",zy=[hn,pn,Sr];function Ue(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function _r(e){return Array.isArray(e)?e:[]}function je(e){return typeof e==="string"&&e!==""?e:void 0}function Fy(e){let t=e.replace(/\s+/g," ").trim();return t.length<=jo?t:`${t.slice(0,jo-1)}…`}var Zo={slug:hn,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 By(e){let t=[];for(let n of _r(e.results)){let r=Ue(n);if(r===void 0)continue;for(let i of[r.primary_tool_slugs,r.related_tool_slugs])for(let o of _r(i))if(typeof o==="string"&&!t.includes(o))t.push(o)}return t.slice(0,Uy)}function Ky(e,t){let n=[];for(let r of e){let i=t[r];if(i===void 0)continue;let o=i.description??i.human_description??"",s;try{qo(i)}catch(c){if(!R(c))throw c;s=c.message}n.push({...s===void 0?{}:{unavailable:s},slug:r,summary:o===""?"no description supplied":Fy(o),toolkit:i.toolkit?.slug??"",mutating:br(i),assumed:Ko(i)})}return n}function qy(e){let t=[];for(let n of _r(e.toolkit_connection_statuses)){let r=Ue(n),i=je(r?.toolkit);if(i===void 0)continue;t.push({toolkit:i,connected:r?.has_active_connection===!0})}return t}function Zy(e,t,n){let r=[`Tools that can "${e}":`,""];for(let s of t){if(s.unavailable!==void 0){r.push(` n/a ${s.slug}`),r.push(` unavailable — do not pin it: ${s.unavailable}`);continue}r.push(` ${s.mutating?"write":"read "} ${s.slug}`),r.push(` ${s.summary}`)}if(t.some((s)=>s.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((s)=>!s.connected).map((s)=>s.toolkit),o=n.filter((s)=>s.connected).map((s)=>s.toolkit);if(r.push(""),o.length>0)r.push(`Already connected: ${o.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((s)=>s.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(`
|
|
255
|
-
`)}function
|
|
256
|
-
`)}function
|
|
253
|
+
</system>`:e.content,n=t===""?[]:[{text:t}];for(let r of e.images??[])n.push({image:{format:Vg[r.mediaType],source:{bytes:Uint8Array.from(Buffer.from(r.data,"base64"))}}});return{role:"user",content:n}}function ry(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 iy(e,t){let n=_o(e.model)&&t.capabilities?.promptCache!=="none",r=[],i=[],o=!0;for(let y of ry(e.messages)){if(o&&y.role==="system"){if(y.content!=="")r.push({text:y.content});if(n&&y.cacheBreakpoint===!0)r.push(fr);continue}o=!1;let{role:w,content:v}=ny(y);if(n&&y.cacheBreakpoint===!0&&v.length>0)v.push(fr);if(v.length===0)continue;let b=i.at(-1);if(b!==void 0&&b.role===w)b.content=[...b.content??[],...v];else i.push({role:w,content:v})}let s=i.at(-1),c=/(^|[./])amazon\.nova/.test(e.model)&&(s?.content??[]).some((y)=>y.toolResult!==void 0);if(n&&s!==void 0&&!c&&s.content?.at(-1)?.cachePoint===void 0)s.content=[...s.content??[],fr];let l=un(e.model),a=e.reasoningEffort,p=l==="budget"&&a!==void 0?Qg[a==="xhigh"||a==="max"?"high":a]:void 0,f=l==="adaptive"?sy(e.model,a):void 0,d=p===void 0&&!To(e.model),u=p!==void 0?Math.max(e.maxTokens??0,p+Xg):f?.thinking===!0?e.maxTokens??Yg:e.maxTokens,m={...u===void 0?{}:{maxTokens:u},...!d||e.temperature===void 0?{}:{temperature:e.temperature},...!d||e.topP===void 0?{}:{topP:e.topP}},g=p!==void 0?{thinking:{type:"enabled",budget_tokens:p}}:f!==void 0?f.fields:l==="openai"&&a!==void 0&&a!=="none"?{reasoning:{effort:a==="minimal"?"low":a}}:void 0;return{modelId:e.model,messages:i,...r.length===0?{}:{system:r},...Object.keys(m).length===0?{}:{inferenceConfig:m},...e.tools===void 0||e.tools.length===0?{}:{toolConfig:{tools:e.tools.map((y)=>({toolSpec:{name:y.name,description:y.description,inputSchema:{json:y.parameters}}}))}},...g===void 0?{}:{additionalModelRequestFields:g}}}function sy(e,t){if(t===void 0)return;if(t==="none"){let n=So(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 oy={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"},ay="<thinking>",cy="</thinking>";function ly(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 $o{#e="";#n=!1;#t=!1;push(e){let t=[],n=this.#e+e;this.#e="";for(;;){let r=this.#n?cy:ay,i=n.indexOf(r);if(i===-1){let o=ly(n,r);return this.#e=n.slice(n.length-o),t.push(...this.#r(n.slice(0,n.length-o))),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*uy(e,t={}){let n=new Map,r=t.thinkingTags===!0?new $o:void 0;for await(let i of e){if(i.contentBlockStart!==void 0){let c=i.contentBlockStart.start?.toolUse;if(c!==void 0)n.set(i.contentBlockStart.contentBlockIndex??0,{kind:"tool",id:c.toolUseId??"",name:c.name??"",input:""});continue}if(i.contentBlockDelta!==void 0){let c=i.contentBlockDelta.contentBlockIndex??0,l=i.contentBlockDelta.delta;if(l?.text!==void 0){if(r!==void 0)yield*r.push(l.text);else if(l.text!=="")yield{type:"text",delta:l.text}}else if(l?.toolUse!==void 0){let a=n.get(c);if(a?.kind==="tool")a.input+=l.toolUse.input??""}else if(l?.reasoningContent!==void 0){let a=n.get(c);if(a?.kind!=="reasoning")a={kind:"reasoning",text:""},n.set(c,a);let p=l.reasoningContent;if(p.text!==void 0&&p.text!=="")a.text+=p.text,yield{type:"reasoning",delta:p.text};if(p.signature!==void 0)a.signature=p.signature;if(p.redactedContent!==void 0)a.redacted=Buffer.from(p.redactedContent).toString("base64")}continue}if(i.contentBlockStop!==void 0){let c=i.contentBlockStop.contentBlockIndex??0,l=n.get(c);if(n.delete(c),l?.kind==="tool")yield{type:"tool_call",call:{id:l.id,name:l.name,arguments:l.input}};else if(l?.kind==="reasoning")yield{type:"thinking_block",block:{text:l.text,...l.signature===void 0?{}:{signature:l.signature},...l.redacted===void 0?{}:{redacted:l.redacted}}};continue}if(i.messageStop!==void 0){if(r!==void 0)yield*r.flush();let c=i.messageStop.stopReason??"end_turn";yield{type:"finish",reason:oy[c]??c};continue}let o=i.metadata?.usage;if(o!==void 0){let{cacheReadInputTokens:c,cacheWriteInputTokens:l}=o;yield{type:"usage",promptTokens:(o.inputTokens??0)+(c??0)+(l??0),completionTokens:o.outputTokens??0,...c===void 0?{}:{cachedPromptTokens:c,cacheSource:"metadata.usage.cacheReadInputTokens"},...l===void 0?{}:{cacheWriteTokens:l}};continue}let s=i.throttlingException??i.serviceUnavailableException??i.internalServerException??i.modelStreamErrorException??i.validationException;if(s!==void 0)throw s}}var dy=async(e)=>{let t=await import("./index-qgsdgbk8.js"),n=e.profile===void 0?hr(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,o)=>{let s=await r.send(new t.ConverseStreamCommand(i),{abortSignal:o});if(s.stream===void 0)throw Error("Bedrock returned a ConverseStream response with no stream.");return s.stream}};function fy(e){return e instanceof Error&&/bound to a different conversation/i.test(e.message)}function hy(e){let t=!1,n=(e.messages??[]).map((r)=>{let i=(r.content??[]).filter((o)=>{let s=o.reasoningContent!==void 0;return t||=s,!s});return{...r,content:i}}).filter((r)=>r.content.length>0);return t?{...e,messages:n}:void 0}var py=/(^|[./])amazon\.nova/,my={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 gy(e,t){let n=Math.min(e.baseDelayMs*2**(t-1),e.maxDelayMs);return Math.round(n*(0.5+Math.random()/2))}function yy(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 pr(e=dy){return{optionsSchema:my,capabilities:(t,n)=>{let r=n.capabilities?.promptCache===void 0&&_o(n.id)?{...t,promptCache:"bedrock"}:t;return un(n.id)==="openai"?{...r,traceAfterInput:!0}:r},warnings:(t,n)=>Gg(t,n),create(t){let n=t.options;if(n===void 0)throw new h({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??Ns,i;return{id:t.id,async*chat(o,s){i??=e(n);let c=await i,l=iy(o,t.config),a=!1;for(let p=1;;p+=1){let f=!1;try{for await(let d of uy(await c(l,s),{thinkingTags:py.test(t.config.id)}))f=!0,yield d;return}catch(d){if(s.aborted)return;if(!f&&!a&&fy(d)){let g=hy(l);if(g!==void 0){l=g,a=!0,t.onRetry?.({status:400,attempt:p,delayMs:0});continue}}let u=Hg(d,o.model,n.region,t.field);if(f||!u.retryable||p>=r.attempts)throw u.error;let m=gy(r,p);if(t.onRetry?.({status:u.status??0,attempt:p,delayMs:m}),await yy(m,s),s.aborted)return}}}}}}}var Eo={name:"model-bedrock",version:xe,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",pr())}};var No=16000,vy=(e,t)=>new Promise((n,r)=>{let i=wy("ffmpeg",["-hide_banner","-loglevel","error","-i","pipe:0"].concat(["-f","s16le","-ac","1","-ar",String(No),"pipe:1"]),{stdio:["pipe","pipe","pipe"]}),o=[],s=[],c=()=>i.kill("SIGKILL");t.addEventListener("abort",c,{once:!0}),i.stdout.on("data",(l)=>o.push(l)),i.stderr.on("data",(l)=>s.push(l)),i.on("error",(l)=>{t.removeEventListener("abort",c),r(l)}),i.on("close",(l)=>{if(t.removeEventListener("abort",c),l===0)n(new Uint8Array(Buffer.concat(o)));else r(Error(Buffer.concat(s).toString("utf8").trim()||`ffmpeg exited ${l}`))}),i.stdin.on("error",()=>{}),i.stdin.end(Buffer.from(e))});function mr(e){if(e.profile!==void 0)return{profile:e.profile};let t=hr(process.env);return t===void 0?{}:{credentials:t}}var by={async transcribe(e){let t=await import("./index-3c5jt6by.js"),n=new t.TranscribeStreamingClient({region:e.region,...mr(e)});return async(r,i)=>{let o=await n.send(new t.StartStreamTranscriptionCommand(r),{abortSignal:i});if(o.TranscriptResultStream===void 0)throw Error("Transcribe returned no result stream.");return o.TranscriptResultStream}},async invoke(e){let t=await import("./index-qgsdgbk8.js"),n=new t.BedrockRuntimeClient({region:e.region,...mr(e)});return async(r,i)=>{let o=await n.send(new t.InvokeModelCommand({modelId:r.modelId,contentType:"application/json",accept:"application/json",body:r.body}),{abortSignal:i});return new TextDecoder().decode(o.body)}},async speak(e){let t=await import("./index-2bsardvh.js"),n=new t.PollyClient({region:e.region,...mr(e)});return async(r,i)=>{let o=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(o.AudioStream===void 0)throw Error("Polly returned no audio.");return{bytes:await o.AudioStream.transformToByteArray(),...o.RequestCharacters===void 0?{}:{characters:o.RequestCharacters}}}},decode:vy},Ao=new Set(["region","profile","languageCode","sampleRate","voiceId","engine"]),_y={safeParse(e){let t=typeof e==="object"&&e!==null?e:{},n=(i)=>({success:!1,error:{issues:[{message:i}]}}),r=Object.keys(t).find((i)=>!Ao.has(i));if(r!==void 0)return n(`unknown option "${r}" (takes ${[...Ao].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 ky(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 Oo=8192;async function*Sy(e){for(let t=0;t<e.byteLength;t+=Oo)yield{AudioEvent:{AudioChunk:e.subarray(t,t+Oo)}}}function Ty(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 gr(e,t){if(e instanceof ln){let i=e.code!==void 0&&/^[a-z][a-z0-9_]{1,63}$/.test(e.code)?e.code:void 0;return new qt({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 qt({code:"media_provider_refused",message:`AWS refused the request (${n||"error"}): ${r}`,hint:n==="AccessDeniedException"||n==="UnrecognizedClientException"?Ty(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 yr(e=by){return{optionsSchema:_y,create(t){if(t.options===void 0)throw new h({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,o;return{async transcribe(c,l){let a=ky(c.mimeType),p=c.bytes;if(a===void 0)try{p=await e.decode(c.bytes,l)}catch(f){let d=f.code==="ENOENT";throw new qt({code:"media_audio_unsupported",message:d?`Amazon Transcribe streaming cannot read ${c.mimeType}, and ffmpeg, which would convert it, is not installed.`:`${c.mimeType} could not be converted for Amazon Transcribe: ${f instanceof Error?f.message:String(f)}`,hint:d?"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 d=await(await r)({LanguageCode:n.languageCode??"en-US",MediaEncoding:a??"pcm",MediaSampleRateHertz:a===void 0?No:n.sampleRate??48000,AudioStream:Sy(p)},l),u=[],m;for await(let g of d)for(let y of g.TranscriptEvent?.Transcript?.Results??[]){if(y.IsPartial===!0)continue;let w=y.Alternatives?.[0]?.Transcript;if(w!==void 0&&w!=="")u.push(w);if(y.EndTime!==void 0)m=y.EndTime}return{text:u.join(" "),...m===void 0?{}:{durationS:m}}}catch(f){if(f instanceof qt)throw f;throw gr(f,t.field)}},async synthesize(c,l){o??=e.speak(n);try{let p=await(await o)({text:c.text,voiceId:n.voiceId??"Joanna",engine:n.engine??"neural",...n.languageCode===void 0?{}:{languageCode:n.languageCode}},l);return{bytes:p.bytes,mimeType:"audio/ogg; codecs=opus",...p.characters===void 0?{}:{characters:p.characters}}}catch(a){throw gr(a,t.field)}},async generateImage(c,l){let[a,p]=c.size.split("x").map(Number);i??=e.invoke(n);let f;try{f=await(await i)({modelId:t.config.model??"amazon.nova-canvas-v1:0",body:JSON.stringify({taskType:"TEXT_IMAGE",textToImageParams:{text:c.prompt},imageGenerationConfig:{numberOfImages:1,width:a,height:p}})},l)}catch(m){throw gr(m,t.field)}let d=JSON.parse(f),u=d.images?.[0];if(u===void 0)throw new qt({code:"media_provider_empty",message:`Nova Canvas returned no image${d.error===void 0?"":`: ${d.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(u,"base64"),mimeType:"image/png"}}}}}}var $y="0.1.0",Io={name:"media-aws",version:$y,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["transcribestreaming.*.amazonaws.com","bedrock-runtime.*.amazonaws.com","polly.*.amazonaws.com"]}],setup(e){e.defineMediaProvider("aws",yr())}};import{mkdirSync as Ey,readFileSync as Ay,renameSync as Oy,writeFileSync as Ny}from"node:fs";import{dirname as Iy,isAbsolute as Cy,join as Co,resolve as Py}from"node:path";import{mkdirSync as iw,readFileSync as Jo,renameSync as sw,writeFileSync as ow}from"node:fs";import{dirname as aw,isAbsolute as cw,join as Uo,resolve as lw}from"node:path";var dn=1,Po="tools.cache.json";function fn(e){return Cy(e)?Co(e,se.stateDir,Po):Co(Py(e),se.stateDir,Po)}function My(e){return typeof e==="object"&&e!==null&&typeof e.slug==="string"}function Mo(e){let t={version:dn,provider:"composio",fetchedAt:"",baseUrl:"",tools:{}},n;try{n=Ay(fn(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!==dn)return t;let o={};for(let[s,c]of Object.entries(i.tools??{}))if(My(c))o[s]=c;return{version:dn,provider:"composio",fetchedAt:typeof i.fetchedAt==="string"?i.fetchedAt:"",baseUrl:typeof i.baseUrl==="string"?i.baseUrl:"",tools:o}}catch{return t}}function Ry(e,t,n,r){let i=fn(e);Ey(Iy(i),{recursive:!0});let o={version:dn,provider:"composio",fetchedAt:r().toISOString(),baseUrl:n,tools:t},s=`${i}.${process.pid}.tmp`;return Ny(s,`${JSON.stringify(o,null,2)}
|
|
254
|
+
`,"utf8"),Oy(s,i),i}function Ro(e){return new h({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 Ly(e,t,n){return new h({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 xy(e,t){return new h({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 \`${se.slug} tools <manifest> --warm\` once to populate it, then start again.`,field:"tools.pinned"})}function ot(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 Dy(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 jy(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 Lo(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 xo(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 Uy="https://backend.composio.dev/api/v3";function Do(e){return/\/v3$/.test(e)?e.replace(/\/v3$/,"/v3.1"):e}var zy=100;function at(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}async function vt(e){let t;try{t=await e.json()}catch{return e.statusText===""?"no detail in the response body":e.statusText}let n=at(at(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 Bo{#e;#n;#t;constructor(e){this.#e=e.apiKey,this.#n=ao(e.baseUrl??Uy),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 ot(n.status,await vt(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 ot(n.status,await vt(n));let r=at(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(zy)});if(n!==void 0)i.set("cursor",n);let o=await this.#o(`/tools?${i.toString()}`,e);for(let c of o.items??[])if(typeof c.slug==="string")t.push(c.slug);let s=o.next_cursor;if(s===null||s===void 0||s===""||s===n)break;n=s}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 ot(i.status,await vt(i));let o=at(await i.json())??{},s=o.successful!==!1,c=typeof o.error==="string"&&o.error!==""?o.error:void 0;return{ok:s,data:o.data??o,...c===void 0?{}:{error:c}}}#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(`${Do(this.#n)}/tool_router/session`,{user_id:e},t);if(!n.ok)throw ot(n.status,await vt(n));let r=at(await n.json())??{},i=r.session_id;if(typeof i!=="string"||i==="")throw ot(n.status,"no session_id in the response body");return r}async executeMeta(e,t,n,r){let i=await this.#i(`${Do(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 ot(i.status,await vt(i));let o=at(await i.json())??{},s=typeof o.error==="string"&&o.error!==""?o.error:void 0;return{ok:o.successful===void 0?s===void 0:o.successful!==!1,data:o.data??o,...s===void 0?{}:{error:s}}}}function Fy(e){return ro(e.input_parameters,{unsupported:(t,n)=>Ly(e.slug,t,n),rootPath:"input_parameters"})}function vr(e){let t=new Set(e.tags??[]);if(t.has("destructiveHint"))return!0;return!t.has("readOnlyHint")}function Ko(e){let t=new Set(e.tags??[]);return!t.has("readOnlyHint")&&!t.has("destructiveHint")}function By(e){let t=e.replace(/\s+/g," ").trim(),n=t.search(/\.\s|\.$/);return n===-1?t:t.slice(0,n+1)}function qo(e){let t=(e.description??e.human_description??"").trim(),n=t===""?`The ${e.slug} tool.`:By(t),r=e.toolkit?.slug;return{slug:e.slug,provider:"composio",summary:n,whenToUse:t===""?`the task needs ${e.slug}`:t,mutating:vr(e),tags:[...r===void 0?[]:[r],...vr(e)?["write"]:["read"]],parameters:Fy(e)}}var Ky=8,jo=100,pn="composio_search",mn="composio_connect",kr="composio_workbench",qy=[pn,mn,kr];function ze(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function br(e){return Array.isArray(e)?e:[]}function Ue(e){return typeof e==="string"&&e!==""?e:void 0}function Zy(e){let t=e.replace(/\s+/g," ").trim();return t.length<=jo?t:`${t.slice(0,jo-1)}…`}var Zo={slug:pn,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 Wy(e){let t=[];for(let n of br(e.results)){let r=ze(n);if(r===void 0)continue;for(let i of[r.primary_tool_slugs,r.related_tool_slugs])for(let o of br(i))if(typeof o==="string"&&!t.includes(o))t.push(o)}return t.slice(0,Ky)}function Jy(e,t){let n=[];for(let r of e){let i=t[r];if(i===void 0)continue;let o=i.description??i.human_description??"",s;try{qo(i)}catch(c){if(!T(c))throw c;s=c.message}n.push({...s===void 0?{}:{unavailable:s},slug:r,summary:o===""?"no description supplied":Zy(o),toolkit:i.toolkit?.slug??"",mutating:vr(i),assumed:Ko(i)})}return n}function Hy(e){let t=[];for(let n of br(e.toolkit_connection_statuses)){let r=ze(n),i=Ue(r?.toolkit);if(i===void 0)continue;t.push({toolkit:i,connected:r?.has_active_connection===!0})}return t}function Vy(e,t,n){let r=[`Tools that can "${e}":`,""];for(let s of t){if(s.unavailable!==void 0){r.push(` n/a ${s.slug}`),r.push(` unavailable — do not pin it: ${s.unavailable}`);continue}r.push(` ${s.mutating?"write":"read "} ${s.slug}`),r.push(` ${s.summary}`)}if(t.some((s)=>s.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((s)=>!s.connected).map((s)=>s.toolkit),o=n.filter((s)=>s.connected).map((s)=>s.toolkit);if(r.push(""),o.length>0)r.push(`Already connected: ${o.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((s)=>s.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(`
|
|
255
|
+
`)}function Gy(e){return{spec:Zo,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 o=ze(i.data)??{},s=Wy(o);if(s.length===0)throw xo(r);let c=await e.fetchSchemas(s,n.signal),l=Jy(s,c);if(l.length===0)throw xo(r);return Vy(r,l,Hy(o))}}}var Wo={slug:mn,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 _r(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(ze(e)??{})){let r=_r(n,t+1);if(r!==void 0)return r}return}function Yy(e,t){let n=ze(ze(t.results)?.[e]),r=Ue(n?.status)?.toLowerCase(),i=Ue(n?.redirect_url)??_r(t.results)??_r(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})`}. ${Ue(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(`
|
|
256
|
+
`)}function Xy(e){return{spec:Wo,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 Yy(r,ze(i.data)??{})}}}var Qy={slug:kr,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"]}},ew="code_to_execute";function tw(e){let t=ze(e);if(t===void 0)return typeof e==="string"?e:JSON.stringify(e,null,2);let n=[],r=Ue(t.stdout),i=Ue(t.stderr),o=Ue(t.error),s=Ue(t.results);if(r!==void 0)n.push(r.trimEnd());if(s!==void 0)n.push(s.trimEnd());if(i!==void 0)n.push(`stderr:
|
|
257
257
|
${i.trimEnd()}`);if(o!==void 0)n.push(`error:
|
|
258
258
|
${o.trimEnd()}`);return n.length===0?"The code ran and printed nothing.":n.join(`
|
|
259
|
-
`)}function
|
|
260
|
-
`,"utf8"),
|
|
261
|
-
`),
|
|
262
|
-
`))}return t}var
|
|
263
|
-
`);return e.structuredContent===void 0?"(no content)":JSON.stringify(e.structuredContent,null,2)}class aa{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=yw(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 o=_t(r.name,i.name);if(!e.includes(o))continue;try{t.push(this.#l(r,i))}catch(s){if(!R(s))throw s;n.push({slug:o,detail:s.toDetail()})}}return this.#s=n,t}refused(){return this.#s}#s=[];async list(){return[...this.#t.values()].flatMap((e)=>(this.#a(e)??[]).map((t)=>_t(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>=Ew)return e;e.push({slug:_t(t.name,n.name),summary:oa(t.name,n)})}return e}explainUnresolved(e){let t=new Set,n=[];for(let r of e){let i=this.#t.get(r.split(mn)[0]??"");if(i===void 0||!r.includes(mn))continue;if(this.#a(i)!==void 0)continue;t.add(i.name),n.push(r)}return n.length===0?void 0:vw([...t],n,Er(this.#e))}async refresh(e,t){let n={...this.#i},r=[],i=[],o=0;for(let l of this.#t.values())try{let a=await this.#c(l).listTools(t),p=new Map((this.#a(l)??[]).map((f)=>[f.name,JSON.stringify(f)]));for(let f of a){let d=_t(l.name,f.name);if(!e.includes(d))continue;if(o+=1,p.get(f.name)!==JSON.stringify(f))i.push(d)}n[l.name]={url:l.url,fetchedAt:new Date().toISOString(),tools:a}}catch(a){r.push({server:l,detail:a instanceof Error?a.message:String(a)})}if(this.#i=n,ww(this.#e,n),r.length>0)throw ia(r.map((l)=>l.server.name).join(", "),r.map((l)=>l.server.url).join(", "),r.map((l)=>l.detail).join("; "));let s=new Set(await this.list()),c=e.filter((l)=>this.#t.has(l.split(mn)[0]??"")&&!s.has(l));return{fetched:o,missing:c,changed:i}}#c(e){let t=this.#o.get(e.name);if(t===void 0)t=new sa({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 o=this.#n[i];if(o===void 0||o==="")throw bw(e.name,r,i);n[r]=o}return n}}),this.#o.set(e.name,t);return t}#l(e,t){return{spec:{...$w(e.name,t,e.policyArgs[t.name]),...e.personal===!0?{personal:!0}:{}},handler:async(n,r)=>{let i=r.actingParticipant,o={...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}}},s=await this.#c(e).callTool(t.name,n,o,r.signal);if(s.isError===!0)throw _w(e.name,t.name,ta(s));return ta(s)}}}}function Ar(e,t){return new aa({dir:e.dir,env:e.env,servers:Aw(e.config),...t===void 0?{}:{fetch:t}})}var Ow="0.1.0",ca={name:"mcp",version:Ow,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)=>Ar(t))}};import{readFile as Nw}from"node:fs/promises";import{join as Iw}from"node:path";import{tmpdir as Jw}from"node:os";import{join as Hw}from"node:path";import{mkdir as lv,realpath as uv,rm as pa,stat as dv}from"node:fs/promises";import{isAbsolute as fv,resolve as Pr}from"node:path";import{open as Ma}from"node:fs/promises";import{existsSync as wv,realpathSync as vv}from"node:fs";import{homedir as ga}from"node:os";import{isAbsolute as La,relative as bv,resolve as kt,sep as _v}from"node:path";import{spawn as Av}from"node:child_process";import{open as Ov,readFile as Nv}from"node:fs/promises";import{mkdir as Gv,readFile as Fa,realpath as Yv,stat as Ba,writeFile as Ka}from"node:fs/promises";import{dirname as Xv,isAbsolute as Qv,resolve as ba}from"node:path";import{isAbsolute as eb,relative as tb,resolve as nb,sep as qa}from"node:path";import{readFile as hb}from"node:fs/promises";import{readdir as pb}from"node:fs/promises";import{join as mb,relative as gb,sep as Sa}from"node:path";import{statSync as $b}from"node:fs";import{mkdir as Eb,rm as Oa}from"node:fs/promises";import{delimiter as Ab,join as Cr}from"node:path";function Cw(){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 Pw(e,t){return new h({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 Mw(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 la(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 Rw(){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 Na(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 Lw(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 xw(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 Dw(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 jw(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 Uw(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 zw(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 Fw(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 Bw(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 Kw(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 Ia(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 qw(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 Zw(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 ua(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 da(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 Ww(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 Ce="system";function Lr(){return Hw(Jw(),`${re.slug}-${Ce}`)}var Vw=rA.filter((e)=>e.agentListed),fa="(hidden by the operator)",Gw=new Set(["id","api","baseurl","options","apikeyenv"]),Yw=new Set(["model","provider","baseurl","options","apikeyenv"]);function Or(e){return e.getIn(["context","modelIdentity"])==="hidden"}function yn(e,t){let n=e.map((r)=>r.toLowerCase());if(n[0]==="model"&&n.slice(2).some((r)=>Gw.has(r)))return fa;if(n[0]==="media"&&n[2]!==void 0&&Yw.has(n[2]))return fa;if(Array.isArray(t))return t.map((r,i)=>yn([...e,String(i)],r));if(typeof t==="object"&&t!==null)return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,yn([...e,r],i)]));return t}function ha(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",o="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")&&be(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 s="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",c="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 c;if(n.startsWith("tools.providers")&&be(t,"baseurl"))return c;let l="which skills may run code is not yours to decide. A person lists them in skills.trusted";if(n==="skills.trusted"||n==="skills"&&be(t,"trusted"))return l;let a="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 a;if(n.startsWith("tools.providers")&&be(t,"confinereads"))return a;let p="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 p;if(n.startsWith("tools.providers")&&be(t,"personal"))return p;if(n.startsWith("tools.providers")&&n.split(".").includes("env"))return s;if(n.startsWith("tools.providers")&&be(t,"env"))return s;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"&&be(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"&&(be(t,"host")||be(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 be(e,t){if(Array.isArray(e))return e.some((n)=>be(n,t));if(typeof e!=="object"||e===null)return!1;return Object.entries(e).some(([n,r])=>n.toLowerCase()===t||be(r,t))}function Ca(e){return e.file??Iw(e.agentDir,"agent.yaml")}var Xw={slug:"config_read",provider:Ce,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."}}}},Qw={slug:"config_set",provider:Ce,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 ev(e){try{return so(e)}catch(t){throw Zw(e,t instanceof Error?t.message:String(t))}}function tv(e){return async(t)=>{let n=Ca(e),r;try{r=await Nw(n,"utf8")}catch(c){throw Ia(n,String(c))}let i=typeof t.path==="string"?t.path.trim():"";if(i!==""){let c=W(r),l=c.getIn(i.split("."),!1);if(l===void 0)return`${i} is not set in this configuration. It can be — see config_read with no path for the full list.`;let a=bt(l)||Ot(l)?l.toJS(c):l,p=Or(c)?yn(i.split("."),a):a;return`${i}:
|
|
264
|
-
${
|
|
259
|
+
`)}function nw(e){return{spec:Qy,handler:async(t,n)=>{let r=await e.call("COMPOSIO_REMOTE_WORKBENCH",{[ew]:String(t.code??"")},n.signal);if(!r.ok)return`The workbench failed: ${r.error??"no detail supplied"}`;return tw(r.data)}}}function rw(e){return{[pn]:Gy(e),[mn]:Xy(e),[kr]:nw(e)}}var zo="composio.session.json";function Ho(e){return cw(e)?Uo(e,se.stateDir,zo):Uo(lw(e),se.stateDir,zo)}function uw(e,t){let n;try{n=Jo(Ho(e),"utf8")}catch{return}try{let i=JSON.parse(n)?.sessions;if(typeof i!=="object"||i===null)return;let o=i[t];return typeof o==="string"&&o!==""?o:void 0}catch{return}}function dw(e,t,n){let r=Ho(e);iw(aw(r),{recursive:!0});let i={};try{let l=JSON.parse(Jo(r,"utf8"))?.sessions;if(typeof l==="object"&&l!==null){for(let[a,p]of Object.entries(l))if(typeof p==="string")i[a]=p}}catch{i={}}let o={sessions:{...i,[t]:n}},s=`${r}.${process.pid}.tmp`;return ow(s,`${JSON.stringify(o,null,2)}
|
|
260
|
+
`,"utf8"),sw(s,r),r}var fw="COMPOSIO_API_KEY";class Vo{id="composio";#e;#n;#t;#r;#o;#i;#a;#s;#c;#l=[];#u=[];#d;constructor(e){this.#e=e.dir,this.#n=e.userId??"default",this.#t=e.now??(()=>new Date),this.#i=e.apiKeyEnv??fw,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 Bo({apiKey:t,baseUrl:this.#r,...e.fetch===void 0?{}:{fetch:e.fetch}});let n=Mo(this.#e);this.#s=n.tools,this.#c=n.fetchedAt}async resolve(e){let t=[],n=[],r=[],i=rw(this.#p());for(let o of e){let s=i[o];if(s!==void 0){t.push(s);continue}let c=this.#s[o];if(c===void 0)continue;let l;try{l=qo(c)}catch(a){if(!T(a))throw a;r.push({slug:o,detail:a.toDetail()});continue}if(Ko(c))n.push(o);t.push(this.#h(l))}if(this.#l=n,this.#u=r,!this.#a)return t;return t.map((o)=>({...o,spec:{...o.spec,personal:!0}}))}refused(){return this.#u}async list(){return[...qy,...Object.keys(this.#s)]}async available(){return[{slug:pn,summary:Zo.summary},{slug:mn,summary:Wo.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 xy(e,fn(this.#e))}describe(){return{cached:Object.keys(this.#s).length,fetchedAt:this.#c,cachePath:fn(this.#e),assumedMutating:this.#l}}async refresh(e,t){let n=this.#o;if(n===void 0)throw Ro(this.#i);let r={},i=[],o=[];for(let c of e){let l=await n.tool(c,t);if(l===void 0){i.push(c);continue}r[c]=l;let a=this.#s[c];if(a===void 0||JSON.stringify(a)!==JSON.stringify(l))o.push(c)}this.#s={...this.#s,...r};let s=Ry(this.#e,this.#s,this.#r,this.#t);return this.#c=Mo(this.#e).fetchedAt,{fetched:Object.keys(r).length,missing:i,changed:o,cachePath:s}}async#f(e,t=!1){let n=this.#o;if(n===void 0)throw Lo(this.#i);if(!t){let i=this.#d??uw(this.#e,this.#n);if(i!==void 0)return this.#d=i,i}let r=await n.createSession(this.#n,e);return this.#d=r.session_id,dw(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 Lo(this.#i);let i=await this.#f(n),o=await r.executeMeta(i,e,t,n);if("notFound"in o){i=await this.#f(n,!0);let s=await r.executeMeta(i,e,t,n);if("notFound"in s)return{ok:!1,data:{},error:"the session could not be opened"};o=s}return o},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}}}#h(e){return{spec:e,handler:async(t,n)=>{let r=this.#o;if(r===void 0)throw Ro(this.#i);let i=await r.execute(e.slug,t,this.#n,n.signal);if(!i.ok){let o=i.error??"no detail supplied";if(/connected account|not connected|no connection/i.test(o)){let s=e.tags[0]??"the toolkit";throw jy(e.slug,s)}throw Dy(e.slug,200,o)}return typeof i.data==="string"?i.data:JSON.stringify(i.data,null,2)}}}}var Fo=["apiKeyEnv","userId","baseUrl","personal"];function wr(e,t){let n=e[t];if(n===void 0)return;if(typeof n!=="string"||n==="")throw new h({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 Sr(e){let t=Object.keys(e.config).filter((s)=>!Fo.includes(s));if(t.length>0)throw new h({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 ${Fo.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=wr(e.config,"apiKeyEnv"),r=wr(e.config,"userId"),i=wr(e.config,"baseUrl"),o=e.config.personal;if(o!==void 0&&typeof o!=="boolean")throw new h({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 Vo({dir:e.dir,env:e.env,...n===void 0?{}:{apiKeyEnv:n},...r===void 0?{}:{userId:r},...i===void 0?{}:{baseUrl:i},...o===void 0?{}:{personal:o}})}var hw="0.1.0",Go={name:"composio",version:hw,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",Sr)}};import{mkdirSync as pw,readFileSync as mw,renameSync as gw,writeFileSync as yw}from"node:fs";import{dirname as ww,join as vw,resolve as bw}from"node:path";var na=1;function $r(e){return vw(bw(e),se.stateDir,"mcp.cache.json")}function _w(e){try{let t=JSON.parse(mw($r(e),"utf8"));if(t.version!==na||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 kw(e,t){let n=$r(e);pw(ww(n),{recursive:!0});let r=`${n}.partial`;return yw(r,`${JSON.stringify({version:na,servers:t},null,2)}
|
|
261
|
+
`),gw(r,n),n}var ra="tools.providers.mcp";function be(e,t,n=ra){return new h({code:"mcp_config_invalid",message:e,hint:t,field:n})}function Sw(e,t,n){return new h({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 \`${se.slug} tools <manifest> --warm\` once with the server running to fill it, then start again.`,field:"tools.pinned"})}function Tw(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 (${ra}.servers.${e}.headersEnv), never the value.`})}function ia(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 $w(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 Yo="2025-06-18";class sa{#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 o of i.tools??[])if(typeof o?.name==="string")t.push(o);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.#c(e,t,n,r);if(i.status!==404||this.#t===void 0)return this.#u(i,e);return this.#t=void 0,await this.#a(r),this.#u(await this.#c(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.#c("initialize",{protocolVersion:Yo,capabilities:{},clientInfo:{name:se.slug,version:xe}},{},e);await this.#u(t,"initialize"),this.#t=t.headers.get("mcp-session-id")??"",await(await this.#l({jsonrpc:"2.0",method:"notifications/initialized"},{},e)).body?.cancel()}#c(e,t,n,r){let i=this.#o;return this.#o+=1,this.#l({jsonrpc:"2.0",id:i,method:e,params:t},n,r)}async#l(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":Yo,...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.#d(r.aborted?`no response within ${this.#e.timeoutMs} ms`:i instanceof Error?i.message:String(i))}}async#u(e,t){let n=await e.text();if(!e.ok)throw this.#d(`${t} answered ${e.status}: ${n.slice(0,300)}`);let i=(e.headers.get("content-type")??"").includes("text/event-stream")?Ew(n):[n];for(let o of i){let s;try{s=JSON.parse(o)}catch{continue}if(s.error!==void 0)throw this.#d(`${t} failed (${s.error.code??"?"}): ${s.error.message??"no message"}`);if(s.result!==void 0)return s.result}throw this.#d(`${t} returned no JSON-RPC result`)}#d(e){return ia(this.#e.server,this.#e.url,e)}}function Ew(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(`
|
|
262
|
+
`))}return t}var gn="__";function _t(e,t){return`${e}${gn}${t.replace(/[^A-Za-z0-9_-]/g,"_")}`}function Aw(e){let t=e.annotations;return t?.readOnlyHint!==!0||t.destructiveHint===!0}function Ow(e){let t=e.replace(/\s+/g," ").trim(),n=t.search(/\.\s|\.$/);return n===-1?t:t.slice(0,n+1)}function oa(e,t){let n=(t.description??t.title??"").trim();return n===""?`The ${t.name} tool on ${e}.`:Ow(n)}function Nw(e,t,n){let r=_t(e,t.name),i=(t.description??t.title??"").trim(),o=Aw(t);return{slug:r,provider:"mcp",summary:oa(e,t),whenToUse:i===""?`the task needs ${t.name} from ${e}`:i,mutating:o,tags:[e,o?"write":"read"],...n===void 0?{}:{policyArg:n},parameters:ro(t.inputSchema,{untyped:"object",rootPath:"inputSchema",unsupported:(s,c)=>be(`The MCP tool "${r}" declares "${c}" at ${s}, 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 Xo=["url","headersEnv","participantHeader","turnHeader","policyArgs","timeoutMs","personal"],Qo=30000,Iw=40;function Tr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ea(e,t,n){if(e===void 0)return{};let r=Tr(e),i=r===void 0?void 0:Object.entries(r),o=i?.every(([,s])=>typeof s==="string"&&(n===void 0||n.test(s)));if(i===void 0||o!==!0)throw be(`${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 Cw(e){let t=Object.keys(e).filter((r)=>r!=="servers");if(t.length>0)throw be(`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=Tr(e.servers);if(n===void 0||Object.keys(n).length===0)throw be("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 o=`tools.providers.mcp.servers.${r}`;if(!/^[a-z][a-z0-9-]{0,23}$/.test(r))throw be(`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.",o);let s=Tr(i)??{},c=Object.keys(s).filter((d)=>!Xo.includes(d));if(c.length>0)throw be(`${o} has keys the MCP provider does not read: ${c.join(", ")}.`,`Accepted keys are ${Xo.join(", ")}.`,o);let l;try{l=new URL(String(s.url))}catch{throw be(`${o}.url is not a URL.`,"Give the server's Streamable HTTP endpoint, e.g. http://127.0.0.1:3000/mcp.",`${o}.url`)}if(l.protocol!=="http:"&&l.protocol!=="https:")throw be(`${o}.url is ${l.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).",`${o}.url`);if(l.username!==""||l.password!=="")throw be(`${o}.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 }.",`${o}.url`);let a=s.timeoutMs===void 0?Qo:s.timeoutMs;if(typeof a!=="number"||!Number.isInteger(a)||a<=0)throw be(`${o}.timeoutMs must be a positive whole number of milliseconds.`,`Omit it for ${Qo} ms.`,`${o}.timeoutMs`);let p=s.participantHeader;if(p!==void 0&&typeof p!=="string")throw be(`${o}.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.",`${o}.participantHeader`);let f=s.turnHeader;if(f!==void 0&&(typeof f!=="string"||!/^[A-Za-z0-9-]+$/.test(f)))throw be(`${o}.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.",`${o}.turnHeader`);if(s.personal!==void 0&&typeof s.personal!=="boolean")throw be(`${o}.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.",`${o}.personal`);return{name:r,url:l.toString(),...s.personal===!0?{personal:!0}:{},...f===void 0?{}:{turnHeader:f},headersEnv:ea(s.headersEnv,`${o}.headersEnv`,/^[A-Za-z_][A-Za-z0-9_]*$/),...p===void 0?{}:{participantHeader:p},policyArgs:ea(s.policyArgs,`${o}.policyArgs`),timeoutMs:a}})}function ta(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(`
|
|
263
|
+
`);return e.structuredContent===void 0?"(no content)":JSON.stringify(e.structuredContent,null,2)}class aa{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=_w(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 o=_t(r.name,i.name);if(!e.includes(o))continue;try{t.push(this.#l(r,i))}catch(s){if(!T(s))throw s;n.push({slug:o,detail:s.toDetail()})}}return this.#s=n,t}refused(){return this.#s}#s=[];async list(){return[...this.#t.values()].flatMap((e)=>(this.#a(e)??[]).map((t)=>_t(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>=Iw)return e;e.push({slug:_t(t.name,n.name),summary:oa(t.name,n)})}return e}explainUnresolved(e){let t=new Set,n=[];for(let r of e){let i=this.#t.get(r.split(gn)[0]??"");if(i===void 0||!r.includes(gn))continue;if(this.#a(i)!==void 0)continue;t.add(i.name),n.push(r)}return n.length===0?void 0:Sw([...t],n,$r(this.#e))}async refresh(e,t){let n={...this.#i},r=[],i=[],o=0;for(let l of this.#t.values())try{let a=await this.#c(l).listTools(t),p=new Map((this.#a(l)??[]).map((f)=>[f.name,JSON.stringify(f)]));for(let f of a){let d=_t(l.name,f.name);if(!e.includes(d))continue;if(o+=1,p.get(f.name)!==JSON.stringify(f))i.push(d)}n[l.name]={url:l.url,fetchedAt:new Date().toISOString(),tools:a}}catch(a){r.push({server:l,detail:a instanceof Error?a.message:String(a)})}if(this.#i=n,kw(this.#e,n),r.length>0)throw ia(r.map((l)=>l.server.name).join(", "),r.map((l)=>l.server.url).join(", "),r.map((l)=>l.detail).join("; "));let s=new Set(await this.list()),c=e.filter((l)=>this.#t.has(l.split(gn)[0]??"")&&!s.has(l));return{fetched:o,missing:c,changed:i}}#c(e){let t=this.#o.get(e.name);if(t===void 0)t=new sa({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 o=this.#n[i];if(o===void 0||o==="")throw Tw(e.name,r,i);n[r]=o}return n}}),this.#o.set(e.name,t);return t}#l(e,t){return{spec:{...Nw(e.name,t,e.policyArgs[t.name]),...e.personal===!0?{personal:!0}:{}},handler:async(n,r)=>{let i=r.actingParticipant,o={...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}}},s=await this.#c(e).callTool(t.name,n,o,r.signal);if(s.isError===!0)throw $w(e.name,t.name,ta(s));return ta(s)}}}}function Er(e,t){return new aa({dir:e.dir,env:e.env,servers:Cw(e.config),...t===void 0?{}:{fetch:t}})}var Pw="0.1.0",ca={name:"mcp",version:Pw,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)=>Er(t))}};import{readFile as Mw}from"node:fs/promises";import{join as Rw}from"node:path";import{tmpdir as Yw}from"node:os";import{join as Xw}from"node:path";import{mkdir as hv,realpath as pv,rm as pa,stat as mv}from"node:fs/promises";import{isAbsolute as gv,resolve as Cr}from"node:path";import{open as Ma}from"node:fs/promises";import{existsSync as kv,realpathSync as Sv}from"node:fs";import{homedir as ga}from"node:os";import{isAbsolute as La,relative as Tv,resolve as kt,sep as $v}from"node:path";import{spawn as Cv}from"node:child_process";import{open as Pv,readFile as Mv}from"node:fs/promises";import{mkdir as eb,readFile as Fa,realpath as tb,stat as Ba,writeFile as Ka}from"node:fs/promises";import{dirname as nb,isAbsolute as rb,resolve as ba}from"node:path";import{isAbsolute as ib,relative as sb,resolve as ob,sep as qa}from"node:path";import{readFile as yb}from"node:fs/promises";import{readdir as wb}from"node:fs/promises";import{join as vb,relative as bb,sep as Sa}from"node:path";import{statSync as Nb}from"node:fs";import{mkdir as Ib,rm as Oa}from"node:fs/promises";import{delimiter as Cb,join as Ir}from"node:path";function Lw(){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 xw(e,t){return new h({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 Dw(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 la(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 jw(){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 Na(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 Uw(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 zw(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 Fw(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 Bw(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 Kw(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 qw(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 Zw(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 Ww(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 Jw(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 Ia(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 Hw(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 Vw(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 ua(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 da(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 Gw(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 Ce="system";function Rr(){return Xw(Yw(),`${se.slug}-${Ce}`)}var Qw=sA.filter((e)=>e.agentListed),fa="(hidden by the operator)",ev=new Set(["id","api","baseurl","options","apikeyenv"]),tv=new Set(["model","provider","baseurl","options","apikeyenv"]);function Ar(e){return e.getIn(["context","modelIdentity"])==="hidden"}function wn(e,t){let n=e.map((r)=>r.toLowerCase());if(n[0]==="model"&&n.slice(2).some((r)=>ev.has(r)))return fa;if(n[0]==="media"&&n[2]!==void 0&&tv.has(n[2]))return fa;if(Array.isArray(t))return t.map((r,i)=>wn([...e,String(i)],r));if(typeof t==="object"&&t!==null)return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,wn([...e,r],i)]));return t}function ha(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",o="widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(n.split(".").includes("writeroots"))return"widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(n.startsWith("tools.providers")&&_e(t,"writeroots"))return"widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";let s="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",c="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 c;if(n.startsWith("tools.providers")&&_e(t,"baseurl"))return c;let l="which skills may run code is not yours to decide. A person lists them in skills.trusted";if(n==="skills.trusted"||n==="skills"&&_e(t,"trusted"))return l;let a="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 a;if(n.startsWith("tools.providers")&&_e(t,"confinereads"))return a;let p="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 p;if(n.startsWith("tools.providers")&&_e(t,"personal"))return p;if(n.startsWith("tools.providers")&&n.split(".").includes("env"))return s;if(n.startsWith("tools.providers")&&_e(t,"env"))return s;if(n.split(".").includes("allowfrom"))return"who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line";if(n==="channels"&&_e(t,"allowfrom"))return"who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line";if(n==="server.host"||n==="server.tokenenv")return"where the API listens, and what authenticates it, is not yours to decide — the same reason writeRoots is refused. Enabling it on 127.0.0.1 is settable; binding anywhere reachable is a person's call";if(n==="server"&&(_e(t,"host")||_e(t,"tokenenv")))return"where the API listens, and what authenticates it, is not yours to decide — the same reason writeRoots is refused. Enabling it on 127.0.0.1 is settable; binding anywhere reachable is a person's call";if(n==="tools.policy.deny")return"removing or replacing the deny rules is the one edit whose only purpose is to remove a restriction someone deliberately set";if(t!==void 0&&n==="tools.untrusted.onmutate"&&String(t).toLowerCase()==="allow")return'setting the write gate to "allow" turns off the check that stops text from outside the conversation driving a tool that changes things';return}function _e(e,t){if(Array.isArray(e))return e.some((n)=>_e(n,t));if(typeof e!=="object"||e===null)return!1;return Object.entries(e).some(([n,r])=>n.toLowerCase()===t||_e(r,t))}function Ca(e){return e.file??Rw(e.agentDir,"agent.yaml")}var nv={slug:"config_read",provider:Ce,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."}}}},rv={slug:"config_set",provider:Ce,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 iv(e){try{return go(e)}catch(t){throw Vw(e,t instanceof Error?t.message:String(t))}}function sv(e){return async(t)=>{let n=Ca(e),r;try{r=await Mw(n,"utf8")}catch(c){throw Ia(n,String(c))}let i=typeof t.path==="string"?t.path.trim():"";if(i!==""){let c=z(r),l=c.getIn(i.split("."),!1);if(l===void 0)return`${i} is not set in this configuration. It can be — see config_read with no path for the full list.`;let a=bt(l)||Ot(l)?l.toJS(c):l,p=Ar(c)?wn(i.split("."),a):a;return`${i}:
|
|
264
|
+
${hn(p).trimEnd()}`}let o=z(r),s=Qw.map((c)=>{let l=o.getIn(c.path.split("."),!1),a=bt(l)||Ot(l)?l.toJS(o):l,p=Ar(o)?wn(c.path.split("."),a):a,f=p===void 0||p===null?"(not set)":Array.isArray(p)?`[${p.map((u)=>typeof u==="object"&&u!==null?JSON.stringify(u):String(u)).join(", ")}]`:hn(p).trim(),d=c.toAgent===void 0?c.means:`${c.means}. ${c.toAgent}`;return`- ${c.path} = ${f}
|
|
265
265
|
${d}`}).join(`
|
|
266
|
-
`);return[`This agent is ${o.get("name")??o.get("id")}, configured at ${n}.`,"","Settings config_set can change, with their current values:",s,"",...
|
|
267
|
-
`)}}function
|
|
268
|
-
`)}}function
|
|
269
|
-
`)}function
|
|
270
|
-
`),r=Number.parseInt(t??"",10),i=n?.trim();return{...Number.isNaN(r)?{}:{code:r},...i===void 0||i===""?{}:{cwd:i}}}catch{return{}}}async function Ua(e){if(
|
|
266
|
+
`);return[`This agent is ${o.get("name")??o.get("id")}, configured at ${n}.`,"","Settings config_set can change, with their current values:",s,"",...ov(o),"Anything not on this list is not settable from a conversation. A change takes effect when the agent next starts, not in the current conversation.","","Some edits are refused whatever the rules say. Removing a check: replacing tools.policy.deny, or setting tools.untrusted.onMutate to allow. Deciding reach: a writeRoots list anywhere, 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.","",...Ar(o)?[]:[`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(`
|
|
267
|
+
`)}}function ov(e){let t=(r)=>{let i=e.getIn(r,!1),o=bt(i)||Ot(i)?i.toJS(e):i;if(Array.isArray(o))return o.map(String);return typeof o==="string"&&o!==""?[o]:[]},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 av(e){return async(t,n)=>{let r=Ca(e),i=typeof t.path==="string"?t.path.trim():"",o=typeof t.value==="string"?t.value:String(t.value??""),s=ha(i);if(s!==void 0)throw da(i,s);if(!ti.includes(i))throw Hw(i,ti);let c=iv(o),l=ha(i,c);if(l!==void 0)throw da(i,l);let a;try{a=await Ts({file:r,path:i.split("."),value:c,...e.providers===void 0?{}:{providers:e.providers},...e.mediaProviders===void 0?{}:{mediaProviders:e.mediaProviders}})}catch(u){if(T(u)&&u.code==="manifest_edit_unreadable")throw Ia(r,String(u.cause??u.message));if(T(u)&&u.code==="manifest_edit_invalid"){let m=u.message.slice(u.message.indexOf(": ")+2);throw ua(i,o,m)}if(T(u))throw ua(i,o,`${u.message} ${u.hint??""}`.trim());throw u}let p=a.before!==void 0,f=i==="tools.pinned"&&Array.isArray(c)&&n.pinTools!==void 0?await n.pinTools(c.map(String)):void 0,d=f===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.":f.length>0?`The configuration still validates. Usable now, in this conversation: ${f.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}.`,p?`It was: ${hn(a.before).trim()}`:"It was not set before.",`It is now: ${hn(c).trim()}`,"",d,...cv(a.manifest,c)].join(`
|
|
268
|
+
`)}}function cv(e,t){if(!_e(t,"tokenenv")&&!_e(t,"apikeyenv"))return[];let n=new Set;for(let r of e.channels??[]){let i=r.tokenEnv;if(typeof i==="string"&&i!=="")n.add(i)}if(n.size===0)return[];return["",`This will NOT start until ${[...n].join(" and ")} ${n.size===1?"is":"are"} set in the .env beside the manifest — the value is read at boot, and a missing one fails the load rather than the first message. You cannot write that file; it is protected because it holds every secret here. Tell the person the variable name and where it goes.`]}function lv(e){return[{spec:nv,handler:sv(e)},{spec:rv,handler:av(e)}]}var uv=["PATH","HOME","USER","LOGNAME","SHELL","LANG","LANGUAGE","TZ","TERM","TMPDIR"],dv=/^[A-Za-z_][A-Za-z0-9_]*$/;function fv(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"&&dv.test(t)))return{scrub:!0,pass:e};throw new h({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 Pa(e,t){if(t==="inherit")return e;let n=new Set([...uv,...t.pass]);return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)||r.startsWith("LC_")))}var yv=6000,wv=3000,ma=1500,vv=new TextDecoder("utf-8");async function Or(e,t,n){let r=await Ma(e,"r");try{let i=new Uint8Array(n),{bytesRead:o}=await r.read(i,0,n,t);return vv.decode(i.subarray(0,o))}finally{await r.close()}}async function Ra(e){let t=await Ma(e,"r"),n;try{n=(await t.stat()).size}finally{await t.close()}if(n<=yv)return{head:jt(await Or(e,0,n)),tail:"",bytes:n,spilled:!1};return{head:jt(await Or(e,0,wv)),tail:jt(await Or(e,n-ma,ma)),bytes:n,spilled:!0}}function bv(e){return e.replace(/^(?:\^[A-Z?]\s*)+/,"")}function _v(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Ev(e){if(e==="~")return ga();return e.startsWith("~/")?kt(ga(),e.slice(2)):e}var Av="workspace";function Ov(e,t=[],n=!1){let r=kt(e),i=kt(r,Av);return{primary:kv(i)?i:r,extra:t.map((o)=>La(o)?kt(o):kt(r,o)),confineReads:n}}function ya(e){try{return Sv(e)}catch{return e}}function xa(e,t){if(!t.confineReads)return;let n=ya(e);if(St(t).some((r)=>Da(n,ya(r))))return;throw Jw(e,St(t))}function Da(e,t){if(e===t)return!0;let n=Tv(t,e);return n!==""&&!n.startsWith(`..${$v}`)&&n!==".."&&!La(n)}function St(e){return[e.primary,...e.extra]}function Nv(e,t){return St(t).some((n)=>Da(e,n))}function Iv(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 ${St(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 Lr(e,t,n,r=e.mutating?"write":"read"){let i={...e.parameters.properties};for(let o of n){let s=i[o];if(s===void 0)continue;i[o]={...s,description:`${s.description??""}${Iv(t,r)}`}}return{...e,parameters:{...e.parameters,properties:i}}}var Ve=new Map,Rv=8;function Lv(){return[...Ve.entries()].map(([e,t])=>({pid:e,...t})).sort((e,t)=>t.since-e.since)}function xv(){let e=[];for(let[t,n]of Ve)try{process.kill(-t,"SIGTERM"),e.push(`${t} (${n.command})`)}catch{}return Ve.clear(),e}function Dv(){for(let e of[...Ve.keys()])try{process.kill(e,0)}catch{Ve.delete(e)}}var jv=250,wa=2000,Uv=new Set(["sleep","git","ssh","scp","sudo","su","doas"]);function zv(e){for(let t of e.split(/\s+/)){if(/^[A-Za-z_]\w*=/.test(t))continue;return t.replace(/^.*\//,"").toLowerCase()}return""}function Fv(e){let t=Ms(e);if(t.length===0)return!1;return t.every((n)=>!Uv.has(zv(n)))}function ja(e){return`'${e.replaceAll("'","'\\''")}'`}function Bv(e,t){return[e,"__code=$?",`{ printf '%s\\n' "$__code"; pwd; } > ${ja(t)} 2>/dev/null`,"exit $__code"].join(`
|
|
269
|
+
`)}function Kv(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 ${ja(e)}`,"/dev/null"],env:{SHELL:"/bin/sh"}};return{file:"script",args:["-q","/dev/null","/bin/sh","-c",e],env:{SHELL:"/bin/sh"}}}function yn(e,t){let n=e.pid;if(n===void 0)return;try{process.kill(-n,t)}catch{}}async function qv(e){try{let[t,n]=(await Mv(e,"utf8")).split(`
|
|
270
|
+
`),r=Number.parseInt(t??"",10),i=n?.trim();return{...Number.isNaN(r)?{}:{code:r},...i===void 0||i===""?{}:{cwd:i}}}catch{return{}}}async function Ua(e){if(Dv(),Ve.size>=Rv)throw Gw(Lv().map((a)=>a.command));let t=Bv(e.command,e.statusPath),{file:n,args:r,env:i}=Kv(t,e.pty),o=await Pv(e.outPath,"w"),s;try{s=Cv(n,r,{cwd:e.cwd,env:{...e.env,...i},stdio:["ignore",o.fd,o.fd],detached:!0})}catch(a){throw await o.close(),la(e.command,String(a))}let c=await new Promise((a,p)=>{let f=!1,d=!1,u=setTimeout(g,e.background?jv:e.timeoutMs),m=(w)=>{if(f)return;f=!0,clearTimeout(u),e.signal.removeEventListener("abort",y),a(w)};function g(){if(e.background||Fv(e.command)){if(s.unref(),s.pid!==void 0)Ve.set(s.pid,{command:e.command,since:Date.now(),outPath:e.outPath});m({ending:"backgrounded",...s.pid===void 0?{}:{pid:s.pid}});return}d=!0,yn(s,"SIGTERM"),setTimeout(()=>yn(s,"SIGKILL"),wa).unref?.()}function y(){yn(s,"SIGTERM"),setTimeout(()=>yn(s,"SIGKILL"),wa).unref?.()}e.signal.addEventListener("abort",y,{once:!0}),s.on("error",(w)=>{if(f)return;f=!0,clearTimeout(u),e.signal.removeEventListener("abort",y),p(e.pty&&Zv(w)?Dw(process.platform,String(w)):la(e.command,String(w)))}),s.on("exit",(w,v)=>{m({ending:d?"killed":"finished",...w===null?{}:{code:w},...v===null?{}:{killedBy:v},...s.pid===void 0?{}:{pid:s.pid}})})}).finally(()=>o.close()),l=await qv(e.statusPath);return{...c,...l.code===void 0?{}:{code:l.code},...l.cwd===void 0?{}:{cwdAfter:l.cwd}}}function Zv(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}var vn=120000,za=600000,Wv=5000,Jv={slug:"exec",provider:Ce,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 ${vn}, maximum ${za}.`,default:vn},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 Hv(e,t){let n=e===void 0||e<=0?vn:e,r=Math.min(n,za),i=t-Wv;return Math.max(1,Math.min(r,i>0?i:Math.floor(t*0.8)))}function va(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function Vv(e,t){let n=Rr();return{out:Cr(n,`${e.turnId}-${t}.log`),status:Cr(n,`${e.turnId}-${t}.status`)}}function Gv(e){return async(t,n)=>{let r=typeof t.command==="string"?t.command.trim():"";if(r==="")throw Lw();let i=e.sessions.lastCwd(n.sessionKey),o=i??e.roots.primary,s=typeof t.workdir==="string"?t.workdir.trim():"",c=s===""?o:gv(s)?s:Cr(o,s),l;try{if(l=await pv(c),!(await mv(l)).isDirectory())throw Error("not a directory")}catch{let v=s===""&&i!==void 0;if(v)e.sessions.forget(n.sessionKey);throw xw(c,v)}let a=Hv(va(t.timeoutMs),n.deadlineMs),p=va(t.timeoutMs),f=p!==void 0&&p!==vn&&a<p,d=t.background===!0,u=Rr();await hv(u,{recursive:!0});let m=Vv(n,Yv(r,n.turnId)),g=await Ua({command:r,cwd:l,env:e.env,timeoutMs:a,pty:t.pty===!0,background:d,signal:n.signal,outPath:m.out,statusPath:m.status});if(g.cwdAfter!==void 0)e.sessions.remember(n.sessionKey,g.cwdAfter);let y=await Ra(m.out),w=t.pty===!0?{...y,head:bv(y.head)}:y;if(await pa(m.status,{force:!0}),!w.spilled&&g.ending!=="backgrounded")await pa(m.out,{force:!0});return Xv({command:r,cwd:l,run:g,observation:w,clamped:f,timeoutMs:a,path:m.out})}}function Yv(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 Xv(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,Nr("Output so far",e.observation.head)].join(`
|
|
271
271
|
|
|
272
|
-
`);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 ${
|
|
272
|
+
`);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 ${_v(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(Nr("First part of the output",e.observation.head)),n)r.push(Nr("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(`
|
|
273
273
|
|
|
274
|
-
`)}function
|
|
275
|
-
${t.trimEnd()}`}function
|
|
276
|
-
`),a=Math.max(1,ka(t.offset)??1),p=Math.max(1,ka(t.limit)??
|
|
274
|
+
`)}function Nr(e,t){return`${e}:
|
|
275
|
+
${t.trimEnd()}`}function Qv(e){return{spec:Lr(Jv,e.roots,["command","workdir"],"shell"),handler:Gv(e)}}var ab=["agent.yaml","agent.yml","SOUL.md","SOUL.compact.md","AGENTS.md","POLICY.md","REMINDER.md"],Za=[".ssh",".aws",".kube",".gnupg",".docker"],Wa=/^(?:\.env(\..+)?|\.netrc|\.npmrc|\.pypirc|id_[a-z0-9]+|.*\.pem|.*\.key)$/i;function Ja(e){return e.split(qa).filter((t)=>t!=="")}function Pr(e){let t=Ja(e),n=t[t.length-1]??"";for(let r of Za)if(t.includes(r))return`${r}/ holds credentials`;if(Wa.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 cb(e,t){let n=Ja(e),r=n[n.length-1]??"";for(let c of Za)if(n.includes(c))return`${c}/ holds credentials, and nothing under it is writable by an agent`;if(Wa.test(r))return`${r} holds secrets — the manifest names environment variables, and their values are not the agent's to edit`;let i=ob(t.agentDir),o=sb(i,e);if(o!==""&&!o.startsWith("..")&&!ib(o)){let c=o.split(qa),l=c[c.length-1]??"";if(ab.includes(l))return`${o} 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(c[0]?.startsWith(".")===!0)return`${o} is runtime state this agent depends on`}for(let c of t.extra??[])if(e.includes(c)||r===c)return`${r} is listed in tools.providerConfig.protect`;return}var _a=2000000,Mr=400;function lb(e){return e.subarray(0,8000).includes(0)}var ub={slug:"file_read",provider:Ce,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 ${Mr}.`,default:Mr}},required:["path"]}},db={slug:"file_write",provider:Ce,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"]}},fb={slug:"file_edit",provider:Ce,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 bn(e,t,n,r){let i=Ev(typeof e==="string"?e.trim():"");if(i==="")throw jw();let o=t.lastCwd(n)??r;return rb(i)?ba(i):ba(o,i)}function Ha(e,t){if(!Nv(e,t.roots))throw Ww(e,St(t.roots));let n=cb(e,{agentDir:t.agentDir,...t.protect===void 0?{}:{extra:t.protect}});if(n!==void 0)throw Bw(e,n)}function ka(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function hb(e){return async(t,n)=>{let r=bn(t.path,e.sessions,n.sessionKey,e.roots.primary);xa(r,e.roots);let i=Pr(await tb(r).catch(()=>r))??Pr(r);if(i!==void 0)throw Fw(r,i);let o;try{o=(await Ba(r)).size}catch{throw Na(r)}if(o>_a)throw Uw(r,o,_a);let s=await Fa(r);if(lb(s))throw zw(r,o);let l=jt(s.toString("utf8")).split(`
|
|
276
|
+
`),a=Math.max(1,ka(t.offset)??1),p=Math.max(1,ka(t.limit)??Mr),f=l.slice(a-1,a-1+p);if(f.length===0)return`${r} has ${l.length} lines, so there is nothing at line ${a}.`;let d=f.join(`
|
|
277
277
|
`),u=a-1+f.length;if(a===1&&u>=l.length)return d;return`Lines ${a}-${u} of ${l.length} in ${r}:
|
|
278
|
-
${d}`}}function
|
|
279
|
-
`).length;return`${o?"Replaced":"Created"} ${r} — ${s} line${s===1?"":"s"}, ${i.length} characters.`}}function
|
|
280
|
-
`).length} lines.`}}function
|
|
278
|
+
${d}`}}function pb(e){return async(t,n)=>{let r=bn(t.path,e.sessions,n.sessionKey,e.roots.primary);Ha(r,e);let i=typeof t.content==="string"?t.content:String(t.content??""),o=await Ba(r).then(()=>!0,()=>!1);await eb(nb(r),{recursive:!0}),await Ka(r,i,"utf8");let s=i===""?0:i.split(`
|
|
279
|
+
`).length;return`${o?"Replaced":"Created"} ${r} — ${s} line${s===1?"":"s"}, ${i.length} characters.`}}function mb(e){return async(t,n)=>{let r=bn(t.path,e.sessions,n.sessionKey,e.roots.primary);Ha(r,e);let i=typeof t.find==="string"?t.find:"",o=typeof t.replace==="string"?t.replace:"",s;try{s=await Fa(r,"utf8")}catch{throw Na(r)}let c=i===""?0:s.split(i).length-1;if(c===0)throw Kw(r,i);if(c>1&&t.all!==!0)throw qw(r,c);let l=t.all===!0?s.split(i).join(o):s.replace(i,o);await Ka(r,l,"utf8");let a=t.all===!0?c:1;return`Edited ${r} — replaced ${a} occurrence${a===1?"":"s"}. The file is now ${l.split(`
|
|
280
|
+
`).length} lines.`}}function gb(e){let t=(n)=>Lr(n,e.roots,["path"]);return[{spec:t(ub),handler:hb(e)},{spec:t(db),handler:pb(e)},{spec:t(fb),handler:mb(e)}]}var _b=new Set(["node_modules",".git",".hg",".svn","dist","build","out",".next",".turbo",".cache","coverage","__pycache__",".venv","venv","target","vendor"]);function Va(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 kb(e){return Sa==="/"?e:e.split(Sa).join("/")}async function Ga(e,t){let n=[],r=[e];while(r.length>0){let i=r.shift();if(i===void 0)break;let o;try{o=await wb(i,{withFileTypes:!0})}catch{continue}for(let s of o){let c=vb(i,s.name);if(s.isDirectory()){if(_b.has(s.name))continue;if(t.hidden!==!0&&s.name.startsWith("."))continue;r.push(c);continue}if(!s.isFile())continue;if(t.hidden!==!0&&s.name.startsWith("."))continue;let l=kb(bb(e,c));if(t.accept!==void 0&&!t.accept(l))continue;if(n.length>=t.limit)return{files:n,truncated:!0};n.push(l)}}return{files:n,truncated:!1}}var Ta=200,$a=100,Sb=1e6,Tb={slug:"glob",provider:Ce,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"]}},$b={slug:"grep",provider:Ce,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 Ya(e,t,n){let r=typeof e.path==="string"&&e.path.trim()!==""?e.path:".",i=bn(r,t.sessions,n,t.roots.primary);return xa(i,t.roots),i}function Eb(e){return async(t,n)=>{let r=typeof t.pattern==="string"?t.pattern.trim():"",i=Ya(t,e,n.sessionKey),o=Va(r),s=await Ga(i,{limit:Ta,...t.hidden===!0?{hidden:!0}:{},accept:(l)=>o.test(l)});if(s.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`${s.truncated?`The first ${s.files.length} of more than ${Ta} matches for ${r} under ${i} — narrow the pattern to see the rest:`:`${s.files.length} match${s.files.length===1?"":"es"} for ${r} under ${i}:`}
|
|
281
281
|
${s.files.join(`
|
|
282
|
-
`)}`}}function
|
|
282
|
+
`)}`}}function Ab(e){return async(t,n)=>{let r=typeof t.pattern==="string"?t.pattern:"",i=Ya(t,e,n.sessionKey),o;try{o=new RegExp(r,t.ignoreCase===!0?"i":"")}catch(d){throw Zw(r,String(d))}let s=typeof t.glob==="string"&&t.glob.trim()!==""?Va(t.glob.trim()):void 0,c=await Ga(i,{limit:5000,...s===void 0?{}:{accept:(d)=>s.test(d)}}),l=[],a=0,p=!1;for(let d of c.files){if(l.length>=$a){p=!0;break}if(Pr(`${i}/${d}`)!==void 0)continue;let u;try{let g=await yb(`${i}/${d}`);if(g.length>Sb||g.subarray(0,8000).includes(0))continue;u=g.toString("utf8")}catch{continue}a+=1;let m=u.split(`
|
|
283
283
|
`);for(let g=0;g<m.length;g+=1){let y=m[g]??"";if(!o.test(y))continue;if(l.length>=$a){p=!0;break}let w=y.length>300?`${y.slice(0,300)}…`:y;l.push(`${d}:${g+1}: ${jt(w).trim()}`)}}if(l.length===0)return`Nothing under ${i} matches ${r}${s===void 0?"":` in files matching ${String(t.glob)}`}. ${a} file${a===1?"":"s"} were searched; node_modules, .git, dist and dot-files are skipped.`;return`${p?`The first ${l.length} matches for ${r} under ${i} — there are more, so narrow the pattern or pass a glob:`:`${l.length} match${l.length===1?"":"es"} for ${r} under ${i}, across ${a} file${a===1?"":"s"} searched:`}
|
|
284
284
|
${l.join(`
|
|
285
|
-
`)}`}}function
|
|
285
|
+
`)}`}}function Ob(e){let t=(n)=>Lr(n,e.roots,["path"]);return[{spec:t(Tb),handler:Eb(e)},{spec:t($b),handler:Ab(e)}]}class Xa{#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 Ea(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}class Qa{id=Ce;#e=new Xa;#n;constructor(e){let t=Ov(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=[Qv({sessions:this.#e,env:e.env,roots:t}),...gb(n),...Ob({sessions:this.#e,roots:t}),...lv({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(Ea));return Promise.resolve(this.#n.filter((n)=>t.has(Ea(n.spec.slug))))}stop(){return Promise.resolve(xv())}list(){return Promise.resolve(this.#n.map((e)=>e.spec.slug))}}var Aa=["protect","writeRoots","env","confineReads"];function xr(e,t){let n=Object.keys(e.config).filter((c)=>!Aa.includes(c));if(n.length>0)throw new h({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 ${Aa.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,o=e.config.confineReads;if(o!==void 0&&typeof o!=="boolean")throw new h({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 s=fv(e.config.env);return t?.(s),new Qa({env:Pa(e.env,s),dir:e.dir,...e.providers===void 0?{}:{providers:e.providers},...e.mediaProviders===void 0?{}:{mediaProviders:e.mediaProviders},...Array.isArray(r)?{protect:r.map((c)=>String(c))}:{},...Array.isArray(i)?{writeRoots:i.map((c)=>String(c))}:{},...o===!0?{confineReads:!0}:{}})}function Pb(e){return`'${e.replaceAll("'","'\\''")}'`}class _n{#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(Cb)){if(n==="")continue;try{let r=Nb(Ir(n,e));if(r.isFile()&&(r.mode&73)!==0)return!0}catch{}}return!1}async run(e){let t=Rr();await Ib(t,{recursive:!0});let n=Mb([e.command,...e.args].join(" ")),r=Ir(t,`skill-${n}.out`),i=Ir(t,`skill-${n}.status`),o=[e.command,...e.args].map(Pb).join(" "),s=await Ua({command:o,cwd:e.cwd,env:Pa(this.#e,this.#n()),timeoutMs:e.timeoutMs,pty:!1,background:!1,signal:e.signal,outPath:r,statusPath:i}),c=await Ra(r);if(await Oa(i,{force:!0}),!c.spilled&&s.ending!=="backgrounded")await Oa(r,{force:!0});let l=s.ending==="killed"||s.ending==="backgrounded",a=c.spilled?`${c.head}
|
|
286
286
|
|
|
287
287
|
… ${c.bytes} bytes in total; the rest is at ${r}
|
|
288
288
|
|
|
289
289
|
${c.tail}`:c.head;return{ok:s.ending==="finished"&&s.code===0,output:s.ending==="backgrounded"?`${a}
|
|
290
290
|
|
|
291
|
-
Still running past ${e.timeoutMs} ms, left going rather than discarded. Output continues to accumulate at ${r}.`:a,...s.code===void 0?{}:{code:s.code},timedOut:l}}}function
|
|
291
|
+
Still running past ${e.timeoutMs} ms, left going rather than discarded. Output continues to accumulate at ${r}.`:a,...s.code===void 0?{}:{code:s.code},timedOut:l}}}function Mb(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 Rb="0.1.0",ec={name:"system",version:Rb,dispachApi:"^0.2",permissions:[{kind:"exec",commands:["*"]},{kind:"fs",paths:["<workspace>"],mode:"write"}],setup(e){let t="inherit";e.defineToolProvider("system",(n)=>xr(n,(r)=>{t=r})),e.defineScriptRunner(new _n({env:e.env,policy:()=>t}))}};import{lookup as t_}from"node:dns/promises";function tc(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 Lb(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 xb(){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 Dr(e,t,n,r,i){let o=t===e?t:`${e} → ${t}`;return new S({code:"web_address_refused",message:`${o} 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 kn(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 nc(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 rc(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 uc(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 ic(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 Db(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 jb(e,t){return new h({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 Ub(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 Ne(e,t){return new h({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 zb(e){return new h({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 Fb(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 sc=["tavily","brave","exa","firecrawl"];function ee(e,t){return typeof e==="object"&&e!==null?e[t]:void 0}function ke(e){return typeof e==="string"?e:""}function Tn(e){return Array.isArray(e)?e:[]}var Bb={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 Tn(ee(e,"results")).map((t)=>({title:ke(ee(t,"title")),url:ke(ee(t,"url")),snippet:ke(ee(t,"content"))}))}},Kb={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 Tn(ee(ee(e,"web"),"results")).map((t)=>({title:ke(ee(t,"title")),url:ke(ee(t,"url")),snippet:ke(ee(t,"description"))}))}},qb={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 Tn(ee(e,"results")).map((t)=>({title:ke(ee(t,"title")),url:ke(ee(t,"url")),snippet:ke(ee(t,"text"))||ke(ee(t,"snippet"))}))}},Zb={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 Tn(ee(ee(e,"data"),"web")).map((t)=>({title:ke(ee(t,"title")),url:ke(ee(t,"url")),snippet:ke(ee(t,"description"))}))},units(e){let t=ee(e,"creditsUsed");return typeof t==="number"&&Number.isFinite(t)?t:1}},Wb={tavily:Bb,brave:Kb,exa:qb,firecrawl:Zb};function dc(e){return Wb[e]}async function Jb(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 Ub(e,t.status,n)}var Hb=["script","style","noscript","template","svg","canvas","iframe","head"],Vb=/<\/?(?: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,Gb={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 fc(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 Gb[n.toLowerCase()]??t})}function Yb(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(e);if(t===null)return;let n=hc(fc(t[1]??""));return n===""?void 0:n}function Xb(e){let t=e;for(let n of Hb)t=t.replace(new RegExp(`<${n}\\b[^>]*>[\\s\\S]*?</${n}>`,"gi")," "),t=t.replace(new RegExp(`<${n}\\b[^>]*>[\\s\\S]*$`,"i")," ");return t=zr(t," "),t=t.replace(Vb,`
|
|
292
292
|
`),t=t.replace(/<[^>]*>/g," "),t=fc(t),t.split(`
|
|
293
293
|
`).map((n)=>hc(n)).filter((n,r,i)=>n!==""||(i[r-1]??"")!=="").join(`
|
|
294
|
-
`).trim()}function hc(e){return e.replace(/\s+/g," ").trim()}function
|
|
295
|
-
`)}var
|
|
296
|
-
`)}finally{l()}}}}var
|
|
294
|
+
`).trim()}function hc(e){return e.replace(/\s+/g," ").trim()}function Qb(e,t){let n=t.split(";")[0]?.trim().toLowerCase()??"";if(n.includes("html")||n.includes("xml")){let r=Yb(e);return{text:Xb(e),...r===void 0?{}:{title:r}}}return{text:e.trim()}}function e_(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 n_=new Set(["http:","https:"]),r_=[".local",".localhost",".internal",".intranet",".lan",".home.arpa"];function pc(e){let t=e.trim();if(t==="")throw tc(e,"the value is empty");try{return new URL(t)}catch(n){throw tc(e,n instanceof Error?n.message:String(n))}}function i_(e){if(!n_.has(e.protocol))throw Lb(e.protocol.replace(":",""));if(e.username!==""||e.password!=="")throw xb();let t=e.hostname.toLowerCase();if(t==="")throw kn(e.href,"there is no host in the URL");if(t==="localhost")throw kn(t,"it is this machine by definition");for(let r of r_)if(t.endsWith(r))throw kn(t,`${r} names are resolved on the local network, not the internet`);let n=t.startsWith("[")?"":t;if(n!==""&&!n.includes(".")&&Qr(t)===void 0)throw kn(t,"a name with no dot in it is completed by the local search domain")}async function mc(e,t,n=0){i_(e);let r=e.hostname.toLowerCase(),i=Qr(r);if(i!==void 0){if(i.kind!=="public")throw Dr(r,r,i.kind,i.range,n);return}let o;try{o=await t(r)}catch(s){throw nc(r,s instanceof Error?s.message:String(s))}if(o.length===0)throw nc(r,"it has no addresses");for(let{address:s}of o){let c=Qr(s);if(c===void 0)throw Dr(r,s,"an address this cannot classify",void 0,n);if(c.kind!=="public")throw Dr(r,s,c.kind,c.range,n)}}var s_=async(e)=>(await t_(e,{all:!0,verbatim:!0})).map((n)=>({address:n.address})),$t="web",gc=2000000,jr=6000,Sn=5,o_=3000,a_=20000,yc={slug:"web_fetch",provider:$t,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 c_(e){return{spec:yc,handler:u_(e)}}function l_(e){let t=Math.max(1000,e-o_);return Math.min(a_,t)}function u_(e){let t=e.maxBytes??gc;return async(n,r)=>{let i=String(n.url??""),o=pc(i),s=new AbortController,c=()=>{s.abort()};r.signal.addEventListener("abort",c,{once:!0});let l=setTimeout(c,l_(r.deadlineMs));try{for(let a=0;a<=Sn;a+=1){await mc(o,e.lookup,a);let p;try{p=await e.fetch(o.href,{method:"GET",redirect:"manual",signal:s.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 rc(o.href,v instanceof Error?v.message:String(v))}let f=p.headers.get("location");if(d_(p.status)&&f!==null){if(await p.body?.cancel().catch(()=>{return}),a===Sn)throw ic(i,Sn);try{o=new URL(f,o)}catch{throw rc(o.href,`it redirected to an unusable address: ${f}`)}continue}if(!p.ok)throw await p.body?.cancel().catch(()=>{return}),uc(o.href,p.status,p.statusText);let d=p.headers.get("content-type")??"";if(!e_(d))throw await p.body?.cancel().catch(()=>{return}),Db(o.href,d.split(";")[0]?.trim()??"binary");let{text:u,read:m,capped:g}=await f_(p,t),{title:y,text:w}=Qb(u,d);return wc({url:o.href,requested:i,...y===void 0?{}:{title:y},text:w,read:m,capped:g,hops:a})}throw ic(i,Sn)}finally{clearTimeout(l),r.signal.removeEventListener("abort",c)}}}function d_(e){return e===301||e===302||e===303||e===307||e===308}async function f_(e,t){let n=e.body;if(n===null)return{text:"",read:0,capped:!1};let r=n.getReader(),i=new TextDecoder("utf-8"),o=[],s=0,c=!1;try{for(;;){let{done:l,value:a}=await r.read();if(l)break;if(a===void 0)continue;if(s+=a.byteLength,s>=t){let p=a.byteLength-(s-t);o.push(i.decode(a.subarray(0,Math.max(0,p)),{stream:!0})),c=!0;break}o.push(i.decode(a,{stream:!0}))}}finally{await r.cancel().catch(()=>{return})}return o.push(i.decode()),{text:o.join(""),read:Math.min(s,t),capped:c}}function wc(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>jr)n=n.slice(0,jr),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 ${jr.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(`
|
|
295
|
+
`)}var h_="https://api.firecrawl.dev/v2",Ur=3000,vc=60000,p_=2000,m_=12000,g_=6000,bc=5,_c=20,kc=100,Sc=500;function H(e,t){return typeof e==="object"&&e!==null?e[t]:void 0}function ye(e){if(typeof e==="string")return e;if(Array.isArray(e)&&typeof e[0]==="string")return e[0];return""}function Fr(e,t){let n=H(e,"creditsUsed");return typeof n==="number"&&Number.isFinite(n)?n:t}async function Tt(e,t,n,r,i){let o=e.env[e.config.apiKeyEnv]??"";if(o==="")throw zb(e.config.apiKeyEnv);let s=await e.fetch(`${e.config.baseUrl??h_}${n}`,{method:r.method,headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},...r.body===void 0?{}:{body:JSON.stringify(r.body)},signal:i});if(!s.ok){let c=s.statusText;try{let l=await s.text(),a=ye(H(y_(l),"error"));c=a!==""?a:l.length>300?`${l.slice(0,300)}…`:l}catch{}throw Fb(t,s.status,c)}return await s.json()}function y_(e){try{return JSON.parse(e)}catch{return}}function Br(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-Ur)));return{signal:n.signal,done:()=>{clearTimeout(i),e.signal.removeEventListener("abort",r)}}}async function Kr(e,t){let n=pc(e);return await mc(n,t.lookup),n}function w_(e){return{spec:yc,handler:async(n,r)=>{let i=String(n.url??""),o=await Kr(i,e),s=Math.max(1000,Math.min(e.config.timeoutMs??vc,r.deadlineMs-2*Ur)),{signal:c,done:l}=Br(r,s+Ur);try{let a=await Tt(e,"scrape","/scrape",{method:"POST",body:{url:o.href,formats:["markdown"],onlyMainContent:e.config.onlyMainContent,timeout:s,...e.config.maxAgeMs===void 0?{}:{maxAge:e.config.maxAgeMs}}},c);r.meter?.({provider:"firecrawl",operation:"scrape",unit:"credits",units:Fr(a,1)});let p=H(a,"data"),f=H(p,"metadata"),d=H(f,"statusCode"),u=ye(H(f,"url"))||ye(H(f,"sourceURL"))||o.href;if(typeof d==="number"&&d>=400)throw uc(u,d,ye(H(f,"error")));let m=ye(H(f,"title")),g=ye(H(p,"markdown"));return wc({url:u,requested:i,...m===""?{}:{title:m},text:g,read:g.length,capped:!1,hops:u===o.href?0:1})}finally{l()}}}}var v_={slug:"web_map",provider:$t,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 ${Sc}.`,default:kc}},required:["url"]}};function b_(e){return{spec:v_,handler:async(n,r)=>{let i=await Kr(String(n.url??""),e),o=String(n.search??"").trim(),s=Tc(n.limit,kc,Sc),{signal:c,done:l}=Br(r,vc);try{let a=await Tt(e,"map","/map",{method:"POST",body:{url:i.href,limit:s,...o===""?{}:{search:o}}},c);r.meter?.({provider:"firecrawl",operation:"map",unit:"credits",units:Fr(a,1)});let p=(Array.isArray(H(a,"links"))?H(a,"links"):[]).map((g)=>typeof g==="string"?{url:g,title:""}:{url:ye(H(g,"url")),title:ye(H(g,"title"))}).filter((g)=>g.url!=="").slice(0,s);if(p.length===0)return`No addresses found on ${i.host}${o===""?"":` for ${JSON.stringify(o)}`}. The site may block crawlers or publish no sitemap; web_fetch on its home page is the other way in.`;let f=[],d=0;for(let g of p){let y=g.title===""?g.url:`${g.url} — ${g.title}`;if(d+y.length>g_)break;f.push(y),d+=y.length+1}let u=`${p.length} address${p.length===1?"":"es"} on ${i.host}${o===""?"":` for ${JSON.stringify(o)}`}:`,m=f.length<p.length?[`incomplete: only the first ${f.length} are shown; narrow it with search`]:[];return[u,...m,"",...f].join(`
|
|
296
|
+
`)}finally{l()}}}}var __={slug:"web_crawl",provider:$t,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 ${_c}.`,default:bc},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 k_(e){return{spec:__,handler:async(n,r)=>{let i=await Kr(String(n.url??""),e),o=Tc(n.limit,bc,_c),s=Array.isArray(n.includePaths)?n.includePaths.map((p)=>String(p)).filter((p)=>p!==""):[],{signal:c,done:l}=Br(r,Number.POSITIVE_INFINITY),a="";try{let p=await Tt(e,"crawl","/crawl",{method:"POST",body:{url:i.href,limit:o,...s.length===0?{}:{includePaths:s},scrapeOptions:{formats:["markdown"],onlyMainContent:e.config.onlyMainContent,...e.config.maxAgeMs===void 0?{}:{maxAge:e.config.maxAgeMs}}}},c);a=ye(H(p,"id"));let f={};while(!c.aborted){if(await S_(p_,c),c.aborted)break;try{f=await Tt(e,"crawl",`/crawl/${encodeURIComponent(a)}`,{method:"GET"},c)}catch(v){if(c.aborted)break;throw v}let w=ye(H(f,"status"));if(w==="completed"||w==="failed")break}let d=ye(H(f,"status")),u=(Array.isArray(H(f,"data"))?H(f,"data"):[]).map((w)=>({url:ye(H(H(w,"metadata"),"sourceURL"))||ye(H(H(w,"metadata"),"url")),markdown:ye(H(w,"markdown"))})).filter((w)=>w.markdown!=="");if(r.meter?.({provider:"firecrawl",operation:"crawl",unit:"credits",units:Fr(f,u.length)}),d!=="completed"&&a!=="")await Tt(e,"crawl",`/crawl/${encodeURIComponent(a)}`,{method:"DELETE"},AbortSignal.timeout(5000)).catch(()=>{return});if(u.length===0)return d==="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 m=Math.floor(m_/u.length),g=u.map((w)=>{let v=w.markdown.length>m?`${w.markdown.slice(0,m).trimEnd()}
|
|
297
297
|
…(cut)`:w.markdown;return`## ${w.url}
|
|
298
298
|
|
|
299
299
|
${v}`}),y=[];if(d!=="completed")y.push("the crawl did not finish in time, so some pages are missing");if(u.some((w)=>w.markdown.length>m))y.push(`each page is cut to ${m.toLocaleString("en-US")} characters`);return[`${u.length} page${u.length===1?"":"s"} from ${i.host}:`,...y.length===0?[]:[`incomplete: ${y.join("; ")}`],"",g.join(`
|
|
300
300
|
|
|
301
301
|
`)].join(`
|
|
302
|
-
`)}finally{l()}}}}function Tc(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
|
|
302
|
+
`)}finally{l()}}}}function Tc(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 S_(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 $c=5,Ec=10,oc=300,T_=3000,$_=15000,E_={slug:"web_search",provider:$t,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 ${Ec}.`,default:$c}},required:["query"]}};function A_(e){return{spec:E_,handler:O_(e)}}function O_(e){let t=dc(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 o=e.env[e.apiKeyEnv]??"";if(o==="")throw jb(t.id,e.apiKeyEnv);let s=N_(n.maxResults),{url:c,init:l}=t.request(i,s,o,e.baseUrl??t.defaultBase),a=new AbortController,p=()=>{a.abort()};r.signal.addEventListener("abort",p,{once:!0});let f=setTimeout(p,Math.min($_,Math.max(1000,r.deadlineMs-T_)));try{let d=await e.fetch(c,{...l,signal:a.signal});if(!d.ok)await Jb(t.id,d);let u=await d.json();return r.meter?.({provider:t.id,operation:"search",unit:t.unit,units:t.units?.(u)??1}),I_(i,t.read(u).slice(0,s))}finally{clearTimeout(f),r.signal.removeEventListener("abort",p)}}}function N_(e){let t=typeof e==="number"?e:Number(e);if(!Number.isFinite(t))return $c;return Math.min(Ec,Math.max(1,Math.trunc(t)))}function I_(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 o=r.snippet.length>oc?`${r.snippet.slice(0,oc).trimEnd()}…`:r.snippet;return[`${i+1}. ${r.title===""?"(untitled)":r.title}`,` ${r.url}`,...o===""?[]:[` ${o.replace(/\s+/g," ")}`]].join(`
|
|
303
303
|
`)});return[`${t.length} result${t.length===1?"":"s"} for ${JSON.stringify(e)}:`,"",...n].join(`
|
|
304
|
-
`)}var
|
|
305
|
-
export{
|
|
304
|
+
`)}var C_="dispach-agent/0.1 (+https://github.com/moeen-mahmud/dispach)";function ac(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}class Ac{id=$t;#e;constructor(e){let t=e.backend??"tavily",n=dc(t),r=e.fetch??((o,s)=>fetch(o,s)),i=e.lookup??s_;this.#e=[A_({backend:t,apiKeyEnv:e.apiKeyEnv??n.defaultKeyEnv,...e.baseUrl===void 0?{}:{baseUrl:e.baseUrl},env:e.env,fetch:r}),...e.firecrawl===void 0?[c_({lookup:i,fetch:r,maxBytes:e.maxBytes??gc,userAgent:C_})]:(()=>{let o={config:e.firecrawl,env:e.env,fetch:r,lookup:i};return[w_(o),k_(o),b_(o)]})()]}available(){return Promise.resolve(this.#e.map((e)=>({slug:e.spec.slug,summary:e.spec.summary})))}resolve(e){let t=new Set(e.map(ac));return Promise.resolve(this.#e.filter((n)=>t.has(ac(n.spec.slug))))}list(){return Promise.resolve(this.#e.map((e)=>e.spec.slug))}}var cc=["backend","apiKeyEnv","baseUrl","maxBytes","firecrawl"],lc=["apiKeyEnv","baseUrl","onlyMainContent","maxAge","timeoutMs"];function qr(e){let t=Object.keys(e.config).filter((c)=>!cc.includes(c));if(t.length>0)throw new h({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 ${cc.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&&!sc.includes(String(n)))throw Ne("backend",`must be one of ${sc.join(", ")} — got ${JSON.stringify(n)}.`);let r=e.config.apiKeyEnv;if(r!==void 0&&(typeof r!=="string"||r===""))throw Ne("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 Ne("maxBytes","must be a number of at least 1000.");let o=Oc(e.config.baseUrl,"baseUrl"),s=P_(e.config.firecrawl,n==="firecrawl",typeof r==="string"?r:void 0,o);return new Ac({env:e.env,...o===void 0?{}:{baseUrl:o},...s===void 0?{}:{firecrawl:s},...n===void 0?{}:{backend:String(n)},...typeof r==="string"?{apiKeyEnv:r}:{},...typeof i==="number"?{maxBytes:i}:{}})}function P_(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 Ne("firecrawl","must be a map, e.g. `firecrawl: {}` for the defaults.");let o=Object.keys(i).find((u)=>!lc.includes(u));if(o!==void 0)throw Ne(`firecrawl.${o}`,`is not a setting. Accepted: ${lc.join(", ")}.`);let s=i.apiKeyEnv;if(s!==void 0&&(typeof s!=="string"||s===""))throw Ne("firecrawl.apiKeyEnv","must be the non-empty name of an environment variable.");let c=i.onlyMainContent;if(c!==void 0&&typeof c!=="boolean")throw Ne("firecrawl.onlyMainContent","must be true or false.");let l=(u,m,g)=>{let y=i[u];if(y===void 0)return;if(typeof y!=="number"||!Number.isFinite(y)||y<m||y>g)throw Ne(`firecrawl.${u}`,`must be a number of milliseconds from ${m} to ${g}.`);return y},p=Oc(i.baseUrl,"firecrawl.baseUrl")??(t?r:void 0),f=l("maxAge",0,2592000000),d=l("timeoutMs",1000,300000);return{apiKeyEnv:typeof s==="string"?s:t&&n!==void 0?n:"FIRECRAWL_API_KEY",onlyMainContent:c??!0,...p===void 0?{}:{baseUrl:p},...f===void 0?{}:{maxAgeMs:f},...d===void 0?{}:{timeoutMs:d}}}function Oc(e,t){if(e===void 0)return;let n;try{n=new URL(String(e))}catch{throw Ne(t,`is not a URL: ${JSON.stringify(e)}.`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw Ne(t,"must be an http or https address.");if(n.username!==""||n.password!=="")throw Ne(t,"must not carry credentials. The key travels in the request's own header, from apiKeyEnv.");return n.href.replace(/\/+$/,"")}var M_="0.1.0",Nc={name:"web",version:M_,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["*"]}],setup(e){e.defineToolProvider("web",qr)}};var ie={composio:Sr,mcp:(e)=>Er(e),system:xr,web:qr},Se={"bedrock-converse":pr()},de={aws:yr()};function ue(){return new _n({env:process.env})}var xS=Object.keys(ie),le={teams:In,slack:An,telegram:Mn,whatsapp:dr},DS=Object.keys(le),Be={"@dispach/channel-a2a":Gr,"@dispach/channel-teams":fi,"@dispach/channel-slack":ri,"@dispach/channel-telegram":wi,"@dispach/channel-whatsapp":bo,"@dispach/media-aws":Io,"@dispach/model-bedrock":Eo,"@dispach/tools-composio":Go,"@dispach/tools-mcp":ca,"@dispach/tools-system":ec,"@dispach/tools-web":Nc},Jr=Object.keys(Be);
|
|
305
|
+
export{ie,Se,de,ue,le,Be,Jr};
|
|
306
306
|
|
|
307
|
-
//# debugId=
|
|
308
|
-
//# sourceMappingURL=index-
|
|
307
|
+
//# debugId=C634807E870FA7C564756E2164756E21
|
|
308
|
+
//# sourceMappingURL=index-fxpmx6cr.js.map
|