dispach 0.2.3 → 0.2.13
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 +46 -43
- package/dist/APEv2Parser-rt8hyadd.js +5 -0
- package/dist/{AiffParser-9hj6fpmy.js → AiffParser-gvpmtb2e.js} +3 -3
- package/dist/{AiffParser-9hj6fpmy.js.map → AiffParser-gvpmtb2e.js.map} +1 -1
- package/dist/App-18dvbyev.js +11 -0
- package/dist/{App-2f72vhjv.js.map → App-18dvbyev.js.map} +1 -1
- package/dist/AsfParser-h9zyh6cx.js +5 -0
- package/dist/{AsfParser-7emspn04.js.map → AsfParser-h9zyh6cx.js.map} +1 -1
- package/dist/ConfigEditor-444m13ta.js +6 -0
- package/dist/{ConfigEditor-vk7vxaa6.js.map → ConfigEditor-444m13ta.js.map} +1 -1
- package/dist/DsdiffParser-gxqv4gn1.js +5 -0
- package/dist/{DsdiffParser-dz88pnnr.js.map → DsdiffParser-gxqv4gn1.js.map} +1 -1
- package/dist/{DsfParser-qgh63tbs.js → DsfParser-sndt4jbk.js} +3 -3
- package/dist/{DsfParser-qgh63tbs.js.map → DsfParser-sndt4jbk.js.map} +1 -1
- package/dist/FlacParser-rmkpvf9e.js +5 -0
- package/dist/{KeyProbe-5anphmb7.js → KeyProbe-6t531sy6.js} +3 -3
- package/dist/{KeyProbe-5anphmb7.js.map → KeyProbe-6t531sy6.js.map} +1 -1
- package/dist/MP4Parser-87xfsck4.js +5 -0
- package/dist/{MP4Parser-yr7p3z12.js.map → MP4Parser-87xfsck4.js.map} +2 -2
- package/dist/{MatroskaParser-jkbsbsk3.js → MatroskaParser-7krspfgx.js} +3 -3
- package/dist/{MatroskaParser-jkbsbsk3.js.map → MatroskaParser-7krspfgx.js.map} +1 -1
- package/dist/{MpegParser-t93vwnew.js → MpegParser-jcs35q0h.js} +3 -3
- package/dist/{MpegParser-t93vwnew.js.map → MpegParser-jcs35q0h.js.map} +1 -1
- package/dist/MusepackParser-d4zfnzk3.js +5 -0
- package/dist/{MusepackParser-6e8kbh2d.js.map → MusepackParser-d4zfnzk3.js.map} +2 -2
- package/dist/OggParser-fbspjs7v.js +5 -0
- package/dist/{OggParser-ggcypmag.js.map → OggParser-fbspjs7v.js.map} +1 -1
- package/dist/Picker-x6aj42tc.js +5 -0
- package/dist/{Picker-j7txnm7w.js.map → Picker-x6aj42tc.js.map} +1 -1
- package/dist/SessionPicker-pngdv97x.js +5 -0
- package/dist/{SessionPicker-hpv2ncsb.js.map → SessionPicker-pngdv97x.js.map} +1 -1
- package/dist/SkillBrowser-3mnzkakr.js +5 -0
- package/dist/{SkillBrowser-qc542n71.js.map → SkillBrowser-3mnzkakr.js.map} +1 -1
- package/dist/WavPackParser-0x9z4466.js +5 -0
- package/dist/{WavPackParser-jw9stzqp.js.map → WavPackParser-0x9z4466.js.map} +1 -1
- package/dist/WaveParser-31b6qtef.js +5 -0
- package/dist/{WaveParser-epmncs9w.js.map → WaveParser-31b6qtef.js.map} +1 -1
- package/dist/WizardApp-c42wc116.js +5 -0
- package/dist/{WizardApp-pgzcz9zq.js.map → WizardApp-c42wc116.js.map} +1 -1
- package/dist/channels-nf6d8fvx.js +31 -0
- package/dist/{channels-m8nambmm.js.map → channels-nf6d8fvx.js.map} +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.js +11 -11
- package/dist/client.js.map +4 -4
- package/dist/config-sx40rg8m.js +24 -0
- package/dist/{config-hmgrqgf2.js.map → config-sx40rg8m.js.map} +2 -2
- package/dist/credential-vdbkfk65.js +19 -0
- package/dist/{credential-nkb2ya59.js.map → credential-vdbkfk65.js.map} +1 -1
- package/dist/daemon.d.ts.map +1 -1
- package/dist/{index-51x0n5z0.js → index-0dcpsfet.js} +4 -4
- package/dist/{index-51x0n5z0.js.map → index-0dcpsfet.js.map} +1 -1
- package/dist/{index-yw3fby4n.js → index-1h8s50d9.js} +3 -3
- package/dist/{index-yw3fby4n.js.map → index-1h8s50d9.js.map} +1 -1
- package/dist/index-1hbvhrsj.js +6 -0
- package/dist/{index-dzy19wtf.js.map → index-1hbvhrsj.js.map} +1 -1
- package/dist/index-1hfece7s.js +10 -0
- package/dist/{index-22fzzn7z.js.map → index-1hfece7s.js.map} +2 -2
- package/dist/index-2h566rtg.js +6 -0
- package/dist/{index-jc4kmfwa.js.map → index-2h566rtg.js.map} +1 -1
- package/dist/index-4g4smpkk.js +11 -0
- package/dist/{index-sh44ymqz.js.map → index-4g4smpkk.js.map} +1 -1
- package/dist/index-4gfsf9n8.js +6 -0
- package/dist/{index-8tmv33mr.js.map → index-4gfsf9n8.js.map} +1 -1
- package/dist/{index-dv9pdjy4.js → index-5ptbytze.js} +10 -10
- package/dist/{index-dv9pdjy4.js.map → index-5ptbytze.js.map} +1 -1
- package/dist/index-5s1cq8np.js +8 -0
- package/dist/{index-9t4dz145.js.map → index-5s1cq8np.js.map} +1 -1
- package/dist/{index-2zjh5zd5.js → index-659ggfbf.js} +2 -2
- package/dist/index-6ebppx3t.js +6 -0
- package/dist/{index-1x8mzvz7.js.map → index-6ebppx3t.js.map} +1 -1
- package/dist/index-6pym9p8h.js +9 -0
- package/dist/{index-38gs9anh.js.map → index-6pym9p8h.js.map} +1 -1
- package/dist/index-9ejax6hp.js +6 -0
- package/dist/{index-8edck2pr.js.map → index-9ejax6hp.js.map} +1 -1
- package/dist/{index-zw6wyas6.js → index-9hw9j1qg.js} +4 -4
- package/dist/{index-zw6wyas6.js.map → index-9hw9j1qg.js.map} +1 -1
- package/dist/{index-bqdkm3de.js → index-9xhresrg.js} +4 -4
- package/dist/{index-bqdkm3de.js.map → index-9xhresrg.js.map} +1 -1
- package/dist/{index-hgm2gchq.js → index-abm0zyc0.js} +12 -12
- package/dist/{index-hgm2gchq.js.map → index-abm0zyc0.js.map} +1 -1
- package/dist/index-ar5c9d2f.js +7 -0
- package/dist/{index-3826kf9t.js.map → index-ar5c9d2f.js.map} +1 -1
- package/dist/index-bhj4pmrx.js +74 -0
- package/dist/index-bhj4pmrx.js.map +13 -0
- package/dist/index-brt17yfr.js +6 -0
- package/dist/{index-hrwakb11.js.map → index-brt17yfr.js.map} +2 -2
- package/dist/index-bysnsdkd.js +6 -0
- package/dist/{index-nxhqf597.js.map → index-bysnsdkd.js.map} +1 -1
- package/dist/index-c74wx9pv.js +6 -0
- package/dist/{index-323jvr1g.js.map → index-c74wx9pv.js.map} +1 -1
- package/dist/index-cm3g4t3r.js +14 -0
- package/dist/{index-y7dxq4a4.js.map → index-cm3g4t3r.js.map} +2 -2
- package/dist/index-dzp6mc5h.js +6 -0
- package/dist/{index-42e29zs4.js.map → index-dzp6mc5h.js.map} +1 -1
- package/dist/index-fad09b8c.js +6 -0
- package/dist/{index-836hc2h1.js.map → index-fad09b8c.js.map} +2 -2
- package/dist/{index-0444sh6x.js → index-fvb2dxzn.js} +4 -4
- package/dist/{index-0444sh6x.js.map → index-fvb2dxzn.js.map} +1 -1
- package/dist/{index-2bsardvh.js → index-gpq4agva.js} +3 -3
- package/dist/{index-2bsardvh.js.map → index-gpq4agva.js.map} +1 -1
- package/dist/{index-qgsdgbk8.js → index-hcpvk5de.js} +3 -3
- package/dist/{index-qgsdgbk8.js.map → index-hcpvk5de.js.map} +1 -1
- package/dist/{index-pqw1n1pv.js → index-jv5t63tp.js} +4 -4
- package/dist/{index-pqw1n1pv.js.map → index-jv5t63tp.js.map} +1 -1
- package/dist/index-kyz4t0j0.js +126 -0
- package/dist/{index-ry6a4bqh.js.map → index-kyz4t0j0.js.map} +2 -2
- package/dist/{index-ytxbw8py.js → index-m6r2sxcw.js} +33 -33
- package/dist/{index-ytxbw8py.js.map → index-m6r2sxcw.js.map} +1 -1
- package/dist/{index-snz49ndn.js → index-mhw3d7af.js} +3 -3
- package/dist/{index-snz49ndn.js.map → index-mhw3d7af.js.map} +1 -1
- package/dist/{index-1mbdz3f7.js → index-mk7hrzq7.js} +9 -9
- package/dist/{index-1mbdz3f7.js.map → index-mk7hrzq7.js.map} +1 -1
- package/dist/index-n0hqgwad.js +6 -0
- package/dist/{index-xg7s813b.js.map → index-n0hqgwad.js.map} +2 -2
- package/dist/index-ncb840sk.js +6 -0
- package/dist/{index-mjfv7k5w.js.map → index-ncb840sk.js.map} +1 -1
- package/dist/{index-fbsrhcga.js → index-ntczmwnf.js} +4 -4
- package/dist/{index-fbsrhcga.js.map → index-ntczmwnf.js.map} +1 -1
- package/dist/{index-095hrkyr.js → index-p5gy5s7p.js} +4 -4
- package/dist/{index-095hrkyr.js.map → index-p5gy5s7p.js.map} +1 -1
- package/dist/{index-3c5jt6by.js → index-p86w0qjw.js} +3 -3
- package/dist/{index-3c5jt6by.js.map → index-p86w0qjw.js.map} +1 -1
- package/dist/index-qhh30m9p.js +6 -0
- package/dist/{index-nvc24414.js.map → index-qhh30m9p.js.map} +1 -1
- package/dist/{index-p6ya59m6.js → index-rerdsr3d.js} +4 -4
- package/dist/{index-p6ya59m6.js.map → index-rerdsr3d.js.map} +1 -1
- package/dist/{index-k8e9f466.js → index-s0mfq8t7.js} +19 -19
- package/dist/index-s0mfq8t7.js.map +11 -0
- package/dist/{index-3vzf253k.js → index-s9ybp2r1.js} +7 -7
- package/dist/{index-3vzf253k.js.map → index-s9ybp2r1.js.map} +1 -1
- package/dist/index-ss77hvwy.js +1246 -0
- package/dist/{index-hpvfqq6r.js.map → index-ss77hvwy.js.map} +32 -31
- package/dist/{index-jff5q27j.js → index-t9bnt6a1.js} +4 -4
- package/dist/{index-jff5q27j.js.map → index-t9bnt6a1.js.map} +1 -1
- package/dist/index-w2ss9hn5.js +9 -0
- package/dist/{index-eztfverw.js.map → index-w2ss9hn5.js.map} +1 -1
- package/dist/{index-pszmnhgq.js → index-w80shmpv.js} +9 -9
- package/dist/{index-pszmnhgq.js.map → index-w80shmpv.js.map} +1 -1
- package/dist/index-w8e8qxd4.js +337 -0
- package/dist/index-w8e8qxd4.js.map +21 -0
- package/dist/{index-308y9xt0.js → index-z9r4e0yq.js} +4 -4
- package/dist/{index-308y9xt0.js.map → index-z9r4e0yq.js.map} +1 -1
- package/dist/index-zj87j4j2.js +6 -0
- package/dist/index-zj87j4j2.js.map +10 -0
- package/dist/{index-m6fqx0ch.js → index-zmerx9rc.js} +6 -6
- package/dist/{index-m6fqx0ch.js.map → index-zmerx9rc.js.map} +1 -1
- package/dist/index-zqjtjs7c.js +153 -0
- package/dist/{index-dpcm1j62.js.map → index-zqjtjs7c.js.map} +2 -2
- package/dist/index.js +381 -368
- package/dist/index.js.map +7 -6
- package/dist/lib/launchd.d.ts.map +1 -1
- package/dist/lib/service-env.d.ts.map +1 -1
- package/dist/lib/templates.d.ts.map +1 -1
- package/dist/lib/theme.d.ts.map +1 -1
- package/dist/lib/watchdog.d.ts +20 -0
- package/dist/lib/watchdog.d.ts.map +1 -0
- package/dist/serve.d.ts.map +1 -1
- package/dist/skills.d.ts.map +1 -1
- package/dist/sources.d.ts.map +1 -1
- package/dist/web-zvf80ns1.js +14 -0
- package/dist/{web-gfv0mzgs.js.map → web-zvf80ns1.js.map} +1 -1
- package/dist/wire.js +11 -11
- package/dist/wire.js.map +4 -4
- package/dist/wrapper-5zhcdmnk.js +5 -0
- package/package.json +4 -4
- package/dist/APEv2Parser-ysjr6adv.js +0 -5
- package/dist/App-2f72vhjv.js +0 -11
- package/dist/AsfParser-7emspn04.js +0 -5
- package/dist/ConfigEditor-vk7vxaa6.js +0 -6
- package/dist/DsdiffParser-dz88pnnr.js +0 -5
- package/dist/FlacParser-drm5wq0p.js +0 -5
- package/dist/MP4Parser-yr7p3z12.js +0 -5
- package/dist/MusepackParser-6e8kbh2d.js +0 -5
- package/dist/OggParser-ggcypmag.js +0 -5
- package/dist/Picker-j7txnm7w.js +0 -5
- package/dist/SessionPicker-hpv2ncsb.js +0 -5
- package/dist/SkillBrowser-qc542n71.js +0 -5
- package/dist/WavPackParser-jw9stzqp.js +0 -5
- package/dist/WaveParser-epmncs9w.js +0 -5
- package/dist/WizardApp-pgzcz9zq.js +0 -5
- package/dist/channels-m8nambmm.js +0 -31
- package/dist/config-hmgrqgf2.js +0 -24
- package/dist/credential-nkb2ya59.js +0 -19
- package/dist/index-1x8mzvz7.js +0 -6
- package/dist/index-22fzzn7z.js +0 -10
- package/dist/index-323jvr1g.js +0 -6
- package/dist/index-3826kf9t.js +0 -7
- package/dist/index-38gs9anh.js +0 -9
- package/dist/index-42e29zs4.js +0 -6
- package/dist/index-836hc2h1.js +0 -6
- package/dist/index-8edck2pr.js +0 -6
- package/dist/index-8tmv33mr.js +0 -6
- package/dist/index-9t4dz145.js +0 -8
- package/dist/index-djeqvfms.js +0 -74
- package/dist/index-djeqvfms.js.map +0 -13
- package/dist/index-dpcm1j62.js +0 -153
- package/dist/index-dzy19wtf.js +0 -6
- package/dist/index-eztfverw.js +0 -9
- package/dist/index-fxpmx6cr.js +0 -308
- package/dist/index-fxpmx6cr.js.map +0 -21
- package/dist/index-hpvfqq6r.js +0 -1252
- package/dist/index-hrwakb11.js +0 -6
- package/dist/index-jc4kmfwa.js +0 -6
- package/dist/index-k8e9f466.js.map +0 -13
- package/dist/index-mjfv7k5w.js +0 -6
- package/dist/index-nvc24414.js +0 -6
- package/dist/index-nxhqf597.js +0 -6
- package/dist/index-qv6ktepc.js +0 -6
- package/dist/index-qv6ktepc.js.map +0 -10
- package/dist/index-ry6a4bqh.js +0 -126
- package/dist/index-sh44ymqz.js +0 -11
- package/dist/index-xg7s813b.js +0 -6
- package/dist/index-y7dxq4a4.js +0 -14
- package/dist/web-gfv0mzgs.js +0 -14
- package/dist/wrapper-f662ny3r.js +0 -5
- /package/dist/{APEv2Parser-ysjr6adv.js.map → APEv2Parser-rt8hyadd.js.map} +0 -0
- /package/dist/{FlacParser-drm5wq0p.js.map → FlacParser-rmkpvf9e.js.map} +0 -0
- /package/dist/{index-2zjh5zd5.js.map → index-659ggfbf.js.map} +0 -0
- /package/dist/{wrapper-f662ny3r.js.map → wrapper-5zhcdmnk.js.map} +0 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{V,_,ne,B,gt,S,Ye,jt,ro,io,zr,ao,Os,Ns,$r,Ms,Vt,Ts,go,sA,Ai,Qr}from"./index-bhj4pmrx.js";import{ht,Ot,X,hn}from"./index-ss77hvwy.js";import{randomUUID as Di}from"node:crypto";import{randomUUID as kt}from"node:crypto";var Kt="1.0",ye={parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,taskNotFound:-32001,taskNotCancelable:-32002,unsupportedOperation:-32004,contentTypeNotSupported:-32005,versionNotSupported:-32009},hu=["TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED"],pu=3600000,mu=3000;class de extends Error{code;status;constructor(e,t,n=200){super(t);this.code=e,this.status=n}}class Ui{#e;#n;#t=new Map;#r=new Map;#o=new Map;#s=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",wu(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 s=this.#m(t);if(s!==void 0)this.#g(s,"TASK_STATE_FAILED",`The turn ended: ${n??"unknown"}.`);return}let r=this.#m(t);if(r===void 0)return;setTimeout(()=>{if(r.endedAt===void 0&&this.#m(t)===r)this.#g(r,"TASK_STATE_COMPLETED",void 0)},mu).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:Kt,supportedInterfaces:[{url:t,protocolBinding:"JSONRPC",protocolVersion:Kt}],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 de(ye.versionNotSupported,`A2A-Version ${n} is not supported; this agent speaks ${Kt}.`);let r=this.#i(e.caller),i;try{i=await e.request.json()}catch{throw new de(ye.parse,"The body is not JSON.")}let s=typeof i==="object"&&i!==null?i:{};if(t=s.id??null,s.jsonrpc!=="2.0"||typeof s.method!=="string")throw new de(ye.invalidRequest,"Not a JSON-RPC 2.0 request.");this.#c(r);let o=typeof s.params==="object"&&s.params!==null?s.params:{};switch(s.method){case"SendMessage":return ji(t,await this.#l(r,o));case"SendStreamingMessage":return this.#d(t,await this.#u(r,o));case"GetTask":return ji(t,this.#p(r,o.id).task);case"CancelTask":{let c=this.#p(r,o.id);throw new de(ye.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 de(s.method.startsWith("SendMessage")||s.method.includes("PushNotification")?ye.unsupportedOperation:ye.methodNotFound,`${s.method} is not supported here.`)}}catch(n){if(n instanceof de)return yu(t,n.code,n.message,n.status);throw n}}#i(e){let t=e.kind==="key"?this.#e.peers.find((n)=>n.key===e.label):void 0;if(t===void 0)throw new de(ye.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.#s.get(e.name)??[]).filter((r)=>t-r<60000);if(n.length>=e.ratePerMinute)throw this.#s.set(e.name,n),new de(ye.invalidRequest,`Peer ${e.name} is over ${e.ratePerMinute} requests a minute.`,429);this.#s.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 de(ye.invalidParams,"The message has no parts.");if(r.some((h)=>typeof h.text!=="string"))throw new de(ye.contentTypeNotSupported,"Only text parts are accepted.");let i=r.map((h)=>String(h.text)).join(`
|
|
3
|
+
`);if(i.length>e.maxChars)throw new de(ye.invalidParams,`The message is ${i.length} characters; ${e.name} may send ${e.maxChars}.`);let s=typeof n.messageId==="string"&&n.messageId!==""?n.messageId:kt(),o=this.#o.get(`${e.name}\x1F${s}`),c=o===void 0?void 0:this.#t.get(o);if(c!==void 0)return c;let l=this.#a;if(l===void 0)throw new de(ye.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:kt(),d=`${e.name}:${a}`,f={task:{id:kt(),contextId:a,status:{state:"TASK_STATE_WORKING",timestamp:new Date().toISOString()},artifacts:[]},peer:e.name,recipient:d,messageId:s,text:"",waiters:[]};return this.#t.set(f.task.id,f),this.#o.set(`${e.name}\x1F${s}`,f.task.id),this.#r.set(d,[...this.#r.get(d)??[],f.task.id]),l.receive({peerId:d,senderHandle:e.name,senderName:e.name,senderKind:"agent",providerMessageId:s,receivedAt:new Date().toISOString(),text:i}),f}#d(e,t){let n=new TextEncoder,r=(s)=>n.encode(`data: ${JSON.stringify({jsonrpc:"2.0",id:e,result:s})}
|
|
4
|
+
|
|
5
|
+
`),i=new ReadableStream({start:async(s)=>{s.enqueue(r(this.#h(t)));let o=await this.#f(t,this.#e.waitMs);s.enqueue(r({statusUpdate:{taskId:o.id,contextId:o.contextId,status:o.status}})),s.close()}});return new Response(i,{headers:{"content-type":"text/event-stream","cache-control":"no-cache"}})}#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 de(ye.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:kt(),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:kt(),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()-pu;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 gu(e){return hu.includes(e)}function ji(e,t){return Response.json({jsonrpc:"2.0",id:e,result:t})}function yu(e,t,n,r){return Response.json({jsonrpc:"2.0",id:e,error:{code:t,message:n}},{status:r})}function wu(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 vu(e){let t=typeof e==="object"&&e!==null?e:{},n=(s)=>(s??[]).flatMap((o)=>typeof o.text==="string"?[o.text]:[]).join(`
|
|
6
|
+
`);if(t.message!==void 0)return n(t.message.parts);let r=t.task;if(r===void 0)return"The peer answered with nothing readable.";if(!gu(r.status.state))return`The peer is still working on it (task ${r.id}, ${r.status.state}). It has not answered yet.`;let i=n(r.status.message?.parts)||r.artifacts.map((s)=>n(s.parts)).join(`
|
|
7
|
+
`);if(r.status.state!=="TASK_STATE_COMPLETED")return`The peer's task ended ${r.status.state}${i===""?"":`: ${i}`}.`;return i===""?"The peer finished without saying anything.":i}function bu(e,t=fetch){let n=e.peers.filter((i)=>i.url!==void 0),r=new Map;return(i)=>{let s={spec:{slug:"a2a_send",provider:"a2a",summary:"Sends a message to another agent and returns its answer.",whenToUse:`a task needs another agent's help and that agent is one of: ${n.map((o)=>o.name).join(", ")||"(none configured)"}`,whenNotToUse:"for anything you can answer yourself, or to reach anyone not in the peer list",mutating:!0,trust:"untrusted",policyArg:"peer",tags:["a2a","agent"],parameters:{type:"object",properties:{peer:{type:"string",enum:n.map((o)=>o.name),description:"Which agent to ask, by the name the manifest gives it."},text:{type:"string",description:"The message, as you would write it to a colleague."}},required:["peer","text"]}},async handler(o,c){let l=n.find((m)=>m.name===o.peer);if(l?.url===void 0)throw new ne({code:"a2a_peer_unknown",message:`No peer "${String(o.peer)}" to send to.`,hint:`The peers this agent may call are: ${n.map((m)=>m.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 ne({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 d=`${c.sessionKey}\x1F${l.name}`,f=AbortSignal.timeout(Math.max(1000,Math.min(60000,c.deadlineMs-5000))),h;try{h=await t(l.url,{method:"POST",headers:{"content-type":"application/json","a2a-version":Kt,...a===void 0?{}:{authorization:`Bearer ${a}`}},body:JSON.stringify({jsonrpc:"2.0",id:Di(),method:"SendMessage",params:{message:{messageId:Di(),role:"ROLE_USER",parts:[{text:String(o.text??"")}],...r.has(d)?{contextId:r.get(d)}:{}}}}),signal:AbortSignal.any([c.signal,f])})}catch(m){throw new ne({code:"a2a_peer_unreachable",message:`Peer ${l.name} did not answer: ${m instanceof Error?m.message:String(m)}`,hint:`Check ${l.url} is reachable from this runtime; a timeout is 60 seconds at most.`})}let u=await h.json().catch(()=>({}));if(u.error!==void 0||!h.ok)throw new ne({code:"a2a_peer_refused",message:`Peer ${l.name} refused: ${u.error?.message??`HTTP ${h.status}`}`,hint:"A 401 or 403 means the token in the peer's tokenEnv is wrong; anything else is the peer's own error, quoted."});let p=u.result?.task?.contextId??u.result?.message?.contextId;if(typeof p==="string")r.set(d,p);return vu(u.result)}};return{id:"a2a",resolve:async(o)=>o.includes("a2a_send")?[s]:[]}}}var xe=(e)=>typeof e==="string"&&e.trim()!==""?e.trim():void 0,Gn=(e,t,n)=>{if(e===void 0)return t;if(typeof e==="number"&&Number.isInteger(e)&&e>0)return e;throw ct(`${n} must be a positive whole number.`,n)};function ct(e,t){return new B({code:"a2a_config_invalid",message:e,hint:"See @dispach/channel-a2a's config: `card` describes this agent, and `peers` maps each name to the key it calls with (`key`), the URL it is called at (`url` and `tokenEnv`), or both.",field:`plugins[channel-a2a].${t}`})}function _u(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 ct(`Peer "${l}" needs a lowercase slug name; it becomes part of a session key.`,`peers.${l}`);let d=typeof a==="object"&&a!==null?a:{},f=xe(d.key),h=xe(d.url),u=xe(d.tokenEnv);if(f===void 0&&h===void 0)throw ct(`Peer "${l}" names neither a key (inbound) nor a url (outbound).`,`peers.${l}`);if(h!==void 0&&!/^https?:\/\//.test(h))throw ct(`Peer "${l}"'s url must be absolute http(s).`,`peers.${l}.url`);return{name:l,...f===void 0?{}:{key:f},...h===void 0?{}:{url:h},...u===void 0?{}:{tokenEnv:u},ratePerMinute:Gn(d.ratePerMinute,30,`peers.${l}.ratePerMinute`),maxChars:Gn(d.maxChars,20000,`peers.${l}.maxChars`)}}),s=i.flatMap((l)=>l.key===void 0?[]:[l.key]);if(new Set(s).size!==s.length)throw ct("Two peers name the same key; a key identifies exactly one peer.","peers");let o=Array.isArray(n.skills)?n.skills:[],c=xe(t.publicUrl);return{card:{name:xe(n.name)??"Agent",description:xe(n.description)??"",skills:o.map((l,a)=>{let d=typeof l==="object"&&l!==null?l:{},f=xe(d.id);if(f===void 0)throw ct("A card skill needs an id.",`card.skills.${a}`);return{id:f,name:xe(d.name)??f,description:xe(d.description)??"",tags:Array.isArray(d.tags)?d.tags.map(String):[]}})},peers:i,...c===void 0?{}:{publicUrl:c},waitMs:Gn(t.waitMs,60000,"waitMs")}}var ku="0.1.0",zi={name:"a2a",version:ku,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["*"]}],setup(e){let t=_u(e.config),n=new Ui(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",bu(t)),e.events.on("turn.end",(r)=>n.observe(r))}};import{readFile as Su}from"node:fs/promises";import{basename as $u}from"node:path";function Bi(e){return e.files?.find((t)=>t.url_private_download!==void 0&&(t.subtype==="slack_audio"||t.mimetype?.startsWith("audio/")===!0))}function Ki(e){return(e.files??[]).filter((t)=>t.url_private_download!==void 0&&t.mimetype?.startsWith("image/")===!0)}var Tu={"&":"&","<":"<",">":">"};function Eu(e,t){return(t===void 0?e.replace(/^\s*<@[A-Z0-9]+>/,""):e.replaceAll(`<@${t}>`,"")).replace(/&(amp|lt|gt);/g,(r)=>Tu[r]??r).replace(/\s+/g," ").trim()}function Au(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=Eu(e.text??"",t);if(r===""&&Bi(e)===void 0&&Ki(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 Ou="https://slack.com/api/",Nu="https://files.slack.com/",Iu=[1000,2000,5000,15000,30000];class qt extends Error{detail;constructor(e){super(e.message);this.detail=e}}class qi{id;type="slack";limits={maxMessageChars:12000,idempotentSend:!1,minSendIntervalMs:1000,attachments:!0,voiceNotes:!0};#e;#n;#t;#r;#o;#s;#a;#i;#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??Iu,this.#s=e.apiBase??Ou}async start(e){if(this.#i!==void 0)return;this.#a=e,this.#i=new AbortController,this.#c=this.#l(e,this.#i.signal)}async stop(){this.#i?.abort(),await this.#c?.catch(()=>{}),this.#i=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),s=await this.#d(e,i,t,()=>{if(n=0,!r)e.status("connected","Socket Mode");r=!0});if(t.aborted)return;if(s)continue;throw new qt({code:"slack_socket_closed",message:"Slack closed the Socket Mode connection before it was established.",hint:"Usually transient and retried. If it persists, check that Socket Mode is enabled for the app (Settings → Socket Mode)."})}catch(i){if(t.aborted)return;if(n+=1,r=!1,n===1||n%8===0){let o=i instanceof qt?i.detail:{code:"slack_unreachable",message:`Cannot reach Slack: ${i instanceof Error?i.message:String(i)}`,hint:"Allow outbound HTTPS to slack.com and wss to *.slack.com. Retried with backoff."};e.status("error",o.message),e.error(o)}let s=this.#o[Math.min(n,this.#o.length)-1]??30000;await Mu(s,t)}}async#u(e){let t=await this.#t(`${this.#s}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 qt({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 s=this.#r(t),o=!1,c=()=>s.close();n.addEventListener("abort",c,{once:!0}),s.addEventListener("message",(l)=>{let a;try{a=JSON.parse(String(l.data))}catch{return}if(a.envelope_id!==void 0)s.send(JSON.stringify({envelope_id:a.envelope_id}));if(a.type==="hello")o=!0,r();else if(a.type==="disconnect")s.close();else if(a.type==="events_api"&&a.payload?.event){let d=a.payload.event,f=a.payload.authorizations?.[0]?.user_id,h=Au(d,f),u=Bi(d),p=u?.url_private_download;if(h===void 0)return;let m=Ki(d).map((g)=>({...g.size===void 0?{}:{sizeBytes:g.size},fetch:(y)=>this.#h(g.url_private_download??"",y)}));e.receive({...h,...m.length===0?{}:{images:m},...u===void 0||p===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:(g)=>this.#h(p,g)}}})}}),s.addEventListener("close",()=>{n.removeEventListener("abort",c),i(o)})})}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 St)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 Su(n.path),i=$u(n.path),s=await this.#p("files.getUploadURLExternal",new URLSearchParams({filename:i,length:String(r.byteLength)}),t),{upload_url:o,file_id:c}=s;if(typeof o!=="string"||typeof c!=="string")throw new St(200,"no_upload_url",void 0);let l=await this.#t(o,{method:"POST",headers:{"content-type":n.mimeType},body:r,...t===void 0?{}:{signal:t}});if(!l.ok)throw new St(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.#s}${e}`,{method:"POST",headers:{authorization:`Bearer ${this.#n}`,...t instanceof URLSearchParams?{}:{"content-type":"application/json; charset=utf-8"}},body:t instanceof URLSearchParams?t:JSON.stringify(t),...n===void 0?{}:{signal:n}}),i=await r.json().catch(()=>({}));if(i.ok===!0)return i;let s=Number(r.headers.get("retry-after"));throw new St(r.status,typeof i.error==="string"?i.error:`HTTP ${r.status}`,Number.isFinite(s)&&s>0?s*1000:void 0)}async#h(e,t){let n=Cu(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 Cu(e){try{let t=new URL(e);if(`${t.protocol}//${t.host}/`!==Nu)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 St 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||Pu.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:Ru[this.code]??"Slack's own error code is above. Rate limits and server errors are retried; anything else is not."}}}}var Pu=new Set(["ratelimited","internal_error","fatal_error","service_unavailable","request_timeout"]),Ru={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 Mu(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}function Fi(e,t,n,r,i){let s=e.config[t],o=typeof s==="string"&&s!==""?s:n,c=e.env[o],l=`channels[${e.id}].${t}`;if(c===void 0||c==="")throw new B({code:"slack_token_missing",message:`Channel "${e.id}" needs ${o}, which is not set.`,hint:`Put the ${i} in ${o}, in the environment or the .env beside the manifest. The agent starts either way, with this channel reported broken.`,field:l});if(!c.startsWith(r))throw new B({code:"slack_token_wrong_kind",message:`${o} does not hold a Slack ${i}; those start with ${r}.`,hint:"Slack issues two tokens and Socket Mode needs both: the app-level token (xapp-…, Basic Information → App-Level Tokens) opens the socket, the bot token (xoxb-…, OAuth & Permissions) sends replies. They are easy to swap.",field:l});return c}var Yn=(e)=>new qi({id:e.id,appToken:Fi(e,"appTokenEnv","SLACK_APP_TOKEN","xapp-","app-level token"),botToken:Fi(e,"botTokenEnv","SLACK_BOT_TOKEN","xoxb-","bot token")}),Lu="0.1.0",Wi={name:"channel-slack",version:Lu,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",Yn)}};import{createPublicKey as xu,verify as Du}from"node:crypto";import{mkdirSync as Fu,readFileSync as Bu,renameSync as Ku,writeFileSync as qu}from"node:fs";import{dirname as Wu,join as Zu}from"node:path";var ju="https://login.botframework.com/v1/.well-known/openidconfiguration",Uu="https://api.botframework.com",Zi=300,zu=86400000;class he extends Error{}function Ji(e){return JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}class Gi{#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,s]=n.split(".");if(r===void 0||i===void 0||s===void 0)throw new he("malformed token");let o,c;try{o=Ji(r),c=Ji(i)}catch{throw new he("unreadable token")}if(o.alg!=="RS256")throw new he(`unexpected algorithm ${String(o.alg)}`);let l=await this.#s(String(o.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(!Du("RSA-SHA256",Buffer.from(`${r}.${i}`),xu({key:{kty:l.kty??"RSA",n:l.n??"",e:l.e??""},format:"jwk"}),Buffer.from(s,"base64url")))throw new he("bad signature");let d=this.#t()/1000;if(c.iss!==Uu)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<d-Zi)throw new he("token expired");if(typeof c.nbf==="number"&&c.nbf>d+Zi)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 Qn(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#s(e){let n=this.#r!==void 0&&this.#t()-this.#r.at<zu?this.#r?.keys.find((s)=>s.kid===e):void 0;if(n!==void 0)return n;let r=await(await this.#n(ju)).json();if(typeof r.jwks_uri!=="string")return;let i=await(await this.#n(r.jwks_uri)).json();return this.#r={at:this.#t(),keys:i.keys??[]},this.#r.keys.find((s)=>s.kid===e)}}class Qn extends Error{status;constructor(e,t){super(t);this.status=e}}var Hi={m4a:"audio/mp4",mp4:"audio/mp4",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"audio/webm",aac:"audio/aac"};function Yi(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&&Hi[n]!==void 0)return{url:r,mimeType:Hi[n],signed:!0};if(t.contentType.startsWith("audio/")&&t.contentUrl!==void 0)return{url:t.contentUrl,mimeType:t.contentType,signed:!1}}return}var Ju=new Set(["png","jpg","jpeg","gif","webp"]);function Xi(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&&Ju.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 Hu={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"};function Vu(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)=>Hu[r]??r).replace(/\s+/g," ").trim()}function Gu(e){let t=e.recipient?.id;return(e.entities??[]).some((n)=>n.type==="mention"&&n.mentioned?.id===t)}function Yu(e){return e.channelData?.tenant?.id??e.conversation?.tenantId}function Xu(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"&&!Gu(e))return;let n=Vu(e);if(n===""&&Yi(e)===void 0&&Xi(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 Qi{id;type="teams";limits={maxMessageChars:4000,idempotentSend:!1};#e;#n;#t;#r;#o;#s;#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=Zu(e.dir,V.stateDir,`teams-${e.id}.json`),this.#a=Qu(this.#o)}async start(e){this.#s=e,e.status("connected",`webhook — POST /v1/channels/${this.id}/webhook/${this.#r??"<agent>"}`)}async stop(){this.#s?.status("disconnected"),this.#s=void 0}async webhook(e){let t=e.body;if(t===void 0||typeof t!=="object"||typeof t.type!=="string")return{status:400,detail:"not an activity"};try{await this.#e.verify(e.headers.authorization,t)}catch(o){if(o instanceof he)return{status:401,detail:o.message};return this.#s?.status("error",`cannot verify activities: ${String(o)}`),{status:503,detail:"cannot verify right now"}}let n=this.#s;if(n===void 0)return{status:503,detail:"channel not started"};if(this.#n!==void 0&&Yu(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=Xu(t);if(r===void 0)return{status:200};let i=Yi(t),s=Xi(t).map((o)=>({fetch:(c)=>this.#c(o.url,o.signed,c)}));return n.receive({...r,...s.length===0?{}:{images:s},...i===void 0?{}:{audio:{mimeType:i.mimeType,fetch:(o)=>this.#c(i.url,i.signed,o)}}}),{status:200}}async send(e,t){return this.#i(e.recipient,{type:"message",text:e.text,textFormat:"markdown"},t)}async typing(e){await this.#i(e,{type:"typing"})}async#i(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 d=a instanceof Qn?a.status:0;return{ok:!1,retryable:d===0||d>=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 s=`${r.replace(/\/?$/,"/")}v3/conversations/${encodeURIComponent(e)}/activities`,o;try{o=await this.#t(s,{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify(t),...n===void 0?{}:{signal:n}})}catch(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(o.ok){let a=await o.json().catch(()=>({}));return{ok:!0,...a.id===void 0?{}:{providerMessageId:a.id}}}let c=(await o.text().catch(()=>"")).slice(0,300),l=Number(o.headers.get("retry-after"));return{ok:!1,retryable:o.status===429||o.status>=500,...Number.isFinite(l)&&l>0?{retryAfterMs:l*1000}:{},error:{code:"teams_send_failed",message:`Teams refused the reply (${o.status}): ${c}`,hint:o.status===403?"The bot is not a member of that conversation any more (removed from the chat or team), or its registration does not allow this tenant.":"Teams' own words are above. 429 and 5xx are retried; anything else is not."}}}async#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},Fu(Wu(this.#o),{recursive:!0});let n=`${this.#o}.partial`;qu(n,`${JSON.stringify(this.#a,null,2)}
|
|
8
|
+
`),Ku(n,this.#o)}}function Qu(e){try{let t=JSON.parse(Bu(e,"utf8"));if(typeof t!=="object"||t===null)return{};return Object.fromEntries(Object.entries(t).filter((n)=>typeof n[1]==="string"))}catch{return{}}}var Vi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Xn(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var er=(e)=>{let t=(o)=>`channels[${e.id}].${o}`,n=Xn(e.config,"appId");if(n===void 0||!Vi.test(n))throw new B({code:"teams_app_id_invalid",message:`Channel "${e.id}" needs appId, the bot's Entra application id.`,hint:"It is the GUID on the Azure Bot resource (Configuration → Microsoft App ID). Not a secret, so it is written here; the password goes in an env var named by passwordEnv. The agent starts either way, with this channel reported broken.",field:t("appId")});let r=Xn(e.config,"passwordEnv")??"TEAMS_APP_PASSWORD",i=e.env[r];if(i===void 0||i==="")throw new B({code:"teams_password_missing",message:`Channel "${e.id}" needs ${r}, which is not set.`,hint:`Put the bot's client secret in ${r}, in the environment or the .env beside the manifest. It is refused here rather than at the first reply, because an unset variable needs no round trip to Microsoft to discover.`,field:t("passwordEnv")});let s=Xn(e.config,"tenantId");if(s!==void 0&&!Vi.test(s))throw new B({code:"teams_tenant_invalid",message:`Channel "${e.id}" declares tenantId "${s}", which is not a tenant id.`,hint:"The Entra tenant (directory) id, a GUID. Omit it only for a legacy multi-tenant bot registration.",field:t("tenantId")});return new Qi({id:e.id,agentId:e.agentId,dir:e.dir,auth:new Gi({appId:n,password:i,...s===void 0?{}:{tenantId:s}}),...s===void 0?{}:{tenantId:s}})},ed="0.1.0",es={name:"channel-teams",version:ed,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",er)}};import{readFile as ts}from"node:fs/promises";import{basename as ns}from"node:path";class Re 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 td="https://api.telegram.org";class nr{#e;#n;#t;constructor(e){this.#e=e.token,this.#n=e.fetch??((t,n)=>fetch(t,n)),this.#t=ao(e.baseUrl??td)}async call(e,t,n){let r;try{r=await this.#n(`${this.#t}/bot${this.#e}/${e}`,{method:"POST",...t instanceof FormData?{body:t}:{headers:{"content-type":"application/json"},body:JSON.stringify(t??{})},...n===void 0?{}:{signal:n}})}catch(s){throw new Re({message:`Telegram ${e} did not complete: ${s instanceof Error?s.message:String(s)}`,status:0,retryable:!0,detail:{code:"telegram_unreachable",message:`Could not reach the Telegram Bot API for ${e}.`,hint:"Check network access from this host. api.telegram.org is blocked in some networks and from some cloud regions; a webhook deployment behind a proxy still needs outbound access for sendMessage."}})}let i=await r.json().catch(()=>({}));if(r.ok&&i.ok&&i.result!==void 0)return i.result;throw nd(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 Re({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 nd(e,t,n){let r=n.description??`HTTP ${t}`,i=n.error_code??t,s=n.parameters?.retry_after;if(i===429)return new Re({message:`Telegram rate-limited ${e}: ${r}`,status:i,retryable:!0,...s===void 0?{}:{retryAfterMs:s*1000},detail:{code:"telegram_rate_limited",message:`Telegram rate-limited ${e}.`,hint:s===void 0?"The outbox will back off and retry. Sustained rate limiting on one chat usually means replies are being split into many chunks — check the reply length.":`Telegram asked for ${s}s. The outbox honours that verbatim rather than applying its own backoff.`}});if(i===401)return new Re({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 Re({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 Re({message:`Telegram refused ${e}: ${r}`,status:i,retryable:!1,detail:{code:"telegram_message_too_long",message:"A chunk exceeded Telegram's message limit.",hint:"This is a chunking bug, not a configuration problem: the transport declares maxMessageChars and core splits to it. Report the reply length — the splitter reserves room for a code-fence reopen, so the effective limit is slightly under 4096."}});let o=i===400||i===403;return new Re({message:`Telegram refused ${e}: ${r}`,status:i,retryable:!o,detail:{code:o?"telegram_refused":"telegram_error",message:`Telegram refused ${e}: ${r}`,hint:o?"Telegram reports this as a client error, so it is not retried. The usual causes are a chat the bot was removed from, a user who blocked it, or a chat id from a different bot — a chat id is not portable between bots.":"Treated as transient and retried with backoff. A 5xx from Telegram is usually brief."}})}var rd=4096,id=30,rs=[1000,2000,5000,15000,30000],sd=350;class ss{id;type="telegram";limits={maxMessageChars:rd,idempotentSend:!1,minSendIntervalMs:sd,attachments:!0,voiceNotes:!0};#e;#n;#t;#r;#o;#s=0;#a=!1;#i;#c;constructor(e){this.id=e.id,this.#e=e.api??new nr({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.#i=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(tr(n,`registering the webhook for channel "${this.id}"`))}return}this.#c=this.#l(e,this.#i.signal)}async stop(){if(!this.#a)return;this.#a=!1,this.#i?.abort(),await this.#c?.catch(()=>{}),this.#c=void 0,this.#o?.status("disconnected"),this.#o=void 0}async send(e,t){let n=is(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 ts(r.path)],{type:"audio/ogg"}),filename:ns(r.path),...n===void 0?{}:{threadId:n}},t):await this.#e.sendPhoto({chatId:e.recipient,photo:new Blob([await ts(r.path)],{type:r.mimeType}),filename:ns(r.path),caption:e.text,...n===void 0?{}:{threadId:n}},t);return{ok:!0,providerMessageId:String(i.message_id)}}catch(r){if(r instanceof Re)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=is(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(!cd(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(tr(i,`checking the bot token for channel "${this.id}"`))}while(this.#a&&!t.aborted)try{let i=await this.#e.getUpdates({offset:this.#s,timeout:id},t);if(n>0)n=0,r=!0,e.status("connected","polling resumed");else if(!r)r=!0,e.status("connected","long-poll");for(let s of i)this.#s=Math.max(this.#s,s.update_id+1),this.#u(e,s)}catch(i){if(t.aborted)return;let s=rs[Math.min(n,rs.length-1)]??1000;if(n+=1,n===1||n%8===0)e.status("error",i instanceof Error?i.message:String(i)),e.error(tr(i,`polling channel "${this.id}"`));await ld(s,t)}}#u(e,t){let n=t.message;if(n===void 0)return;let r=n.text??n.caption??"",i=n.voice??n.audio,s=od(n);if(r.trim()===""&&i===void 0&&s===void 0)return;if(n.from?.is_bot===!0)return;let o=ad(n,r),c=s===void 0?[]:[{...s.file_size===void 0?{}:{sizeBytes:s.file_size},fetch:(l)=>this.#d(s.file_id,"photo",l)}];e.receive({...o,...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 od(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 ad(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 is(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function tr(e,t){if(e instanceof Re)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 cd(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 ld(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}var rr=(e)=>{let t=e.config,n=$t(t,"tokenEnv")??"TELEGRAM_BOT_TOKEN",r=e.env[n];if(r===void 0||r==="")throw new B({code:"telegram_token_missing",message:`Channel "${e.id}" needs ${n}, which is not set.`,hint:`Export ${n}, or add it to the .env beside the manifest — then restart the agent. Get a token from @BotFather with /newbot. The agent starts either way: a channel is optional, so this channel is reported broken rather than blocking the load. It is refused here rather than at the first poll because an unset variable is a configuration mistake and needs no network round trip to discover.`,field:`channels[${e.id}].tokenEnv`});let i=$t(t,"mode")??"longpoll";if(i!=="longpoll"&&i!=="webhook")throw new B({code:"telegram_mode_invalid",message:`Channel "${e.id}" declares mode "${i}".`,hint:"mode is longpoll or webhook, and the agent starts either way with this channel reported broken. Long-poll needs no inbound connectivity and is the right default for a laptop or a private network; webhook needs a public HTTPS URL and is lower latency.",field:`channels[${e.id}].mode`});let s=$t(t,"secretTokenEnv"),o=s===void 0?void 0:e.env[s];if(s!==void 0&&(o===void 0||o===""))throw new B({code:"telegram_secret_missing",message:`Channel "${e.id}" names secretTokenEnv ${s}, which is not set.`,hint:`Export ${s} with any random string, or remove secretTokenEnv. Naming a variable and leaving it empty would start a webhook that verifies nothing, which is worse than one that never claimed to.`,field:`channels[${e.id}].secretTokenEnv`});let c=$t(t,"apiBaseUrl"),l=$t(t,"webhookUrl");return new ss({id:e.id,token:r,mode:i,...l===void 0?{}:{webhookUrl:l},...o===void 0||o===""?{}:{secretToken:o},...c===void 0?{}:{api:new nr({token:r,baseUrl:c})}})};function $t(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var ud="0.1.0",os={name:"telegram",version:ud,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["api.telegram.org"]},{kind:"env",vars:["TELEGRAM_BOT_TOKEN"]}],setup(e){e.defineChannel("telegram",rr)}};import{createRequire as dd}from"node:module";import{isAbsolute as Md,resolve as Ld}from"node:path";import{appendFile as Js,mkdir as zy,readFile as Fy}from"node:fs/promises";import{join as Hs}from"node:path";import{appendFile as Ra,mkdir as By,readFile as Ky,writeFile as qy}from"node:fs/promises";import{join as Wy}from"node:path";import{randomBytes as Hw}from"node:crypto";import{chmodSync as Xs,mkdirSync as Vw,readdirSync as Gw,rmSync as Yw}from"node:fs";import{readFile as Qs}from"node:fs/promises";import{join as Xw}from"node:path";var C=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),mn=dd(import.meta.url),z=C(function(e){var t=Symbol.for("yaml.alias"),n=Symbol.for("yaml.document"),r=Symbol.for("yaml.map"),i=Symbol.for("yaml.pair"),s=Symbol.for("yaml.scalar"),o=Symbol.for("yaml.seq"),c=Symbol.for("yaml.node.type"),l=(y)=>!!y&&typeof y==="object"&&y[c]===t,a=(y)=>!!y&&typeof y==="object"&&y[c]===n,d=(y)=>!!y&&typeof y==="object"&&y[c]===r,f=(y)=>!!y&&typeof y==="object"&&y[c]===i,h=(y)=>!!y&&typeof y==="object"&&y[c]===s,u=(y)=>!!y&&typeof y==="object"&&y[c]===o;function p(y){if(y&&typeof y==="object")switch(y[c]){case r:case o:return!0}return!1}function m(y){if(y&&typeof y==="object")switch(y[c]){case t:case r:case s:case o:return!0}return!1}var g=(y)=>(h(y)||p(y))&&!!y.anchor;e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=c,e.PAIR=i,e.SCALAR=s,e.SEQ=o,e.hasAnchor=g,e.isAlias=l,e.isCollection=p,e.isDocument=a,e.isMap=d,e.isNode=m,e.isPair=f,e.isScalar=h,e.isSeq=u}),gn=C(function(e){var t=z(),n=Symbol("break visit"),r=Symbol("skip children"),i=Symbol("remove node");function s(h,u){let p=a(u);if(t.isDocument(h)){if(o(null,h.contents,p,Object.freeze([h]))===i)h.contents=null}else o(null,h,p,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;function o(h,u,p,m){let g=d(h,u,p,m);if(t.isNode(g)||t.isPair(g))return f(h,m,g),o(h,g,p,m);if(typeof g!=="symbol"){if(t.isCollection(u)){m=Object.freeze(m.concat(u));for(let y=0;y<u.items.length;++y){let w=o(y,u.items[y],p,m);if(typeof w==="number")y=w-1;else if(w===n)return n;else if(w===i)u.items.splice(y,1),y-=1}}else if(t.isPair(u)){m=Object.freeze(m.concat(u));let y=o("key",u.key,p,m);if(y===n)return n;else if(y===i)u.key=null;let w=o("value",u.value,p,m);if(w===n)return n;else if(w===i)u.value=null}}return g}async function c(h,u){let p=a(u);if(t.isDocument(h)){if(await l(null,h.contents,p,Object.freeze([h]))===i)h.contents=null}else await l(null,h,p,Object.freeze([]))}c.BREAK=n,c.SKIP=r,c.REMOVE=i;async function l(h,u,p,m){let g=await d(h,u,p,m);if(t.isNode(g)||t.isPair(g))return f(h,m,g),l(h,g,p,m);if(typeof g!=="symbol"){if(t.isCollection(u)){m=Object.freeze(m.concat(u));for(let y=0;y<u.items.length;++y){let w=await l(y,u.items[y],p,m);if(typeof w==="number")y=w-1;else if(w===n)return n;else if(w===i)u.items.splice(y,1),y-=1}}else if(t.isPair(u)){m=Object.freeze(m.concat(u));let y=await l("key",u.key,p,m);if(y===n)return n;else if(y===i)u.key=null;let w=await l("value",u.value,p,m);if(w===n)return n;else if(w===i)u.value=null}}return g}function a(h){if(typeof h==="object"&&(h.Collection||h.Node||h.Value))return Object.assign({Alias:h.Node,Map:h.Node,Scalar:h.Node,Seq:h.Node},h.Value&&{Map:h.Value,Scalar:h.Value,Seq:h.Value},h.Collection&&{Map:h.Collection,Seq:h.Collection},h);return h}function d(h,u,p,m){if(typeof p==="function")return p(h,u,m);if(t.isMap(u))return p.Map?.(h,u,m);if(t.isSeq(u))return p.Seq?.(h,u,m);if(t.isPair(u))return p.Pair?.(h,u,m);if(t.isScalar(u))return p.Scalar?.(h,u,m);if(t.isAlias(u))return p.Alias?.(h,u,m);return}function f(h,u,p){let m=u[u.length-1];if(t.isCollection(m))m.items[h]=p;else if(t.isPair(m))if(h==="key")m.key=p;else m.value=p;else if(t.isDocument(m))m.contents=p;else{let g=t.isAlias(m)?"alias":"scalar";throw Error(`Cannot replace node with ${g} parent`)}}e.visit=s,e.visitAsync=c}),lo=C(function(e){var t=z(),n=gn(),r={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},i=(o)=>o.replace(/[!,[\]{}]/g,(c)=>r[c]);class s{constructor(o,c){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},s.defaultYaml,o),this.tags=Object.assign({},s.defaultTags,c)}clone(){let o=new s(this.yaml,this.tags);return o.docStart=this.docStart,o}atDocument(){let o=new s(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:s.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},s.defaultTags);break}return o}add(o,c){if(this.atNextDocument)this.yaml={explicit:s.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},s.defaultTags),this.atNextDocument=!1;let l=o.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[d,f]=l;return this.tags[d]=f,!0}case"%YAML":{if(this.yaml.explicit=!0,l.length!==1)return c(0,"%YAML directive should contain exactly one part"),!1;let[d]=l;if(d==="1.1"||d==="1.2")return this.yaml.version=d,!0;else{let f=/^\d+\.\d+$/.test(d);return c(6,`Unsupported YAML version ${d}`,f),!1}}default:return c(0,`Unknown directive ${a}`,!0),!1}}tagName(o,c){if(o==="!")return"!";if(o[0]!=="!")return c(`Not a valid tag: ${o}`),null;if(o[1]==="<"){let f=o.slice(2,-1);if(f==="!"||f==="!!")return c(`Verbatim tags aren't resolved, so ${o} is invalid.`),null;if(o[o.length-1]!==">")c("Verbatim tags must end with a >");return f}let[,l,a]=o.match(/^(.*!)([^!]*)$/s);if(!a)c(`The ${o} tag has no suffix`);let d=this.tags[l];if(d)try{return d+decodeURIComponent(a)}catch(f){return c(String(f)),null}if(l==="!")return o;return c(`Could not resolve tag: ${o}`),null}tagString(o){for(let[c,l]of Object.entries(this.tags))if(o.startsWith(l))return c+i(o.substring(l.length));return o[0]==="!"?o:`!<${o}>`}toString(o){let c=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],l=Object.entries(this.tags),a;if(o&&l.length>0&&t.isNode(o.contents)){let d={};n.visit(o.contents,(f,h)=>{if(t.isNode(h)&&h.tag)d[h.tag]=!0}),a=Object.keys(d)}else a=[];for(let[d,f]of l){if(d==="!!"&&f==="tag:yaml.org,2002:")continue;if(!o||a.some((h)=>h.startsWith(f)))c.push(`%TAG ${d} ${f}`)}return c.join(`
|
|
9
|
+
`)}}s.defaultYaml={explicit:!1,version:"1.2"},s.defaultTags={"!!":"tag:yaml.org,2002:"},e.Directives=s}),Or=C(function(e){var t=z(),n=gn();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,d){if(d.anchor)l.add(d.anchor)}}),l}function s(c,l){for(let a=1;;++a){let d=`${c}${a}`;if(!l.has(d))return d}}function o(c,l){let a=[],d=new Map,f=null;return{onAnchor:(h)=>{a.push(h),f??(f=i(c));let u=s(l,f);return f.add(u),u},setAnchors:()=>{for(let h of a){let u=d.get(h);if(typeof u==="object"&&u.anchor&&(t.isScalar(u.node)||t.isCollection(u.node)))u.node.anchor=u.anchor;else{let p=Error("Failed to resolve repeated object (this should not happen)");throw p.source=h,p}}},sourceObjects:d}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=s}),uo=C(function(e){function t(n,r,i,s){if(s&&typeof s==="object")if(Array.isArray(s))for(let o=0,c=s.length;o<c;++o){let l=s[o],a=t(n,s,String(o),l);if(a===void 0)delete s[o];else if(a!==l)s[o]=a}else if(s instanceof Map)for(let o of Array.from(s.keys())){let c=s.get(o),l=t(n,s,o,c);if(l===void 0)s.delete(o);else if(l!==c)s.set(o,l)}else if(s instanceof Set)for(let o of Array.from(s)){let c=t(n,s,o,o);if(c===void 0)s.delete(o);else if(c!==o)s.delete(o),s.add(c)}else for(let[o,c]of Object.entries(s)){let l=t(n,s,o,c);if(l===void 0)delete s[o];else if(l!==c)s[o]=l}return n.call(r,i,s)}e.applyReviver=t}),tt=C(function(e){var t=z();function n(r,i,s){if(Array.isArray(r))return r.map((o,c)=>n(o,String(c),s));if(r&&typeof r.toJSON==="function"){if(!s||!t.hasAnchor(r))return r.toJSON(i,s);let o={aliasCount:0,count:1,res:void 0};s.anchors.set(r,o),s.onCreate=(l)=>{o.res=l,delete s.onCreate};let c=r.toJSON(i,s);if(s.onCreate)s.onCreate(c);return c}if(typeof r==="bigint"&&!s?.keep)return Number(r);return r}e.toJS=n}),Nr=C(function(e){var t=uo(),n=z(),r=tt();class i{constructor(s){Object.defineProperty(this,n.NODE_TYPE,{value:s})}clone(){let s=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)s.range=this.range.slice();return s}toJS(s,{mapAsMap:o,maxAliasCount:c,onAnchor:l,reviver:a}={}){if(!n.isDocument(s))throw TypeError("A document argument is required");let d={anchors:new Map,doc:s,keep:!0,mapAsMap:o===!0,mapKeyWarned:!1,maxAliasCount:typeof c==="number"?c:100},f=r.toJS(this,"",d);if(typeof l==="function")for(let{count:h,res:u}of d.anchors.values())l(u,h);return typeof a==="function"?t.applyReviver(a,{"":f},"",f):f}}e.NodeBase=i}),yn=C(function(e){var t=Or(),n=gn(),r=z(),i=Nr(),s=tt();class o 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 d;if(a?.aliasResolveCache)d=a.aliasResolveCache;else if(d=[],n.visit(l,{Node:(h,u)=>{if(r.isAlias(u)||r.hasAnchor(u))d.push(u)}}),a)a.aliasResolveCache=d;let f=void 0;for(let h of d){if(h===this)break;if(h.anchor===this.source)f=h}return f}toJSON(l,a){if(!a)return{source:this.source};let{anchors:d,doc:f,maxAliasCount:h}=a,u=this.resolve(f,a);if(!u){let m=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(m)}let p=d.get(u);if(!p)s.toJS(u,null,a),p=d.get(u);if(p?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(h>=0){if(p.count+=1,p.aliasCount===0)p.aliasCount=c(f,u,d);if(p.count*p.aliasCount>h)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return p.res}toString(l,a,d){let f=`*${this.source}`;if(l){if(t.anchorIsValid(this.source),l.options.verifyAliasOrder&&!l.anchors.has(this.source)){let h=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(h)}if(l.implicitKey)return`${f} `}return f}}function c(l,a,d){if(r.isAlias(a)){let f=a.resolve(l),h=d&&f&&d.get(f);return h?h.count*h.aliasCount:0}else if(r.isCollection(a)){let f=0;for(let h of a.items){let u=c(l,h,d);if(u>f)f=u}return f}else if(r.isPair(a)){let f=c(l,a.key,d),h=c(l,a.value,d);return Math.max(f,h)}return 1}e.Alias=o}),se=C(function(e){var t=z(),n=Nr(),r=tt(),i=(o)=>!o||typeof o!=="function"&&typeof o!=="object";class s extends n.NodeBase{constructor(o){super(t.SCALAR);this.value=o}toJSON(o,c){return c?.keep?this.value:r.toJS(this.value,o,c)}toString(){return String(this.value)}}s.BLOCK_FOLDED="BLOCK_FOLDED",s.BLOCK_LITERAL="BLOCK_LITERAL",s.PLAIN="PLAIN",s.QUOTE_DOUBLE="QUOTE_DOUBLE",s.QUOTE_SINGLE="QUOTE_SINGLE",e.Scalar=s,e.isScalarValue=i}),wn=C(function(e){var t=yn(),n=z(),r=se(),i="tag:yaml.org,2002:";function s(c,l,a){if(l){let d=a.filter((h)=>h.tag===l),f=d.find((h)=>!h.format)??d[0];if(!f)throw Error(`Tag ${l} not found`);return f}return a.find((d)=>d.identify?.(c)&&!d.format)}function o(c,l,a){if(n.isDocument(c))c=c.contents;if(n.isNode(c))return c;if(n.isPair(c)){let w=a.schema[n.MAP].createNode?.(a.schema,null,a);return w.items.push(c),w}if(c instanceof String||c instanceof Number||c instanceof Boolean||typeof BigInt<"u"&&c instanceof BigInt)c=c.valueOf();let{aliasDuplicateObjects:d,onAnchor:f,onTagObj:h,schema:u,sourceObjects:p}=a,m=void 0;if(d&&c&&typeof c==="object")if(m=p.get(c),m)return m.anchor??(m.anchor=f(c)),new t.Alias(m.anchor);else m={anchor:null,node:null},p.set(c,m);if(l?.startsWith("!!"))l=i+l.slice(2);let g=s(c,l,u.tags);if(!g){if(c&&typeof c.toJSON==="function")c=c.toJSON();if(!c||typeof c!=="object"){let w=new r.Scalar(c);if(m)m.node=w;return w}g=c instanceof Map?u[n.MAP]:(Symbol.iterator in Object(c))?u[n.SEQ]:u[n.MAP]}if(h)h(g),delete a.onTagObj;let y=g?.createNode?g.createNode(a.schema,c,a):typeof g?.nodeClass?.from==="function"?g.nodeClass.from(a.schema,c,a):new r.Scalar(c);if(l)y.tag=l;else if(!g.default)y.tag=g.tag;if(m)m.node=y;return y}e.createNode=o}),Ir=C(function(e){var t=wn(),n=z(),r=Nr();function i(c,l,a){let d=a;for(let f=l.length-1;f>=0;--f){let h=l[f];if(typeof h==="number"&&Number.isInteger(h)&&h>=0){let u=[];u[h]=d,d=u}else d=new Map([[h,d]])}return t.createNode(d,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:c,sourceObjects:new Map})}var s=(c)=>c==null||typeof c==="object"&&!!c[Symbol.iterator]().next().done;class o 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(s(c))this.add(l);else{let[a,...d]=c,f=this.get(a,!0);if(n.isCollection(f))f.addIn(d,l);else if(f===void 0&&this.schema)this.set(a,i(this.schema,d,l));else throw Error(`Expected YAML collection at ${a}. Remaining path: ${d}`)}}deleteIn(c){let[l,...a]=c;if(a.length===0)return this.delete(l);let d=this.get(l,!0);if(n.isCollection(d))return d.deleteIn(a);else throw Error(`Expected YAML collection at ${l}. Remaining path: ${a}`)}getIn(c,l){let[a,...d]=c,f=this.get(a,!0);if(d.length===0)return!l&&n.isScalar(f)?f.value:f;else return n.isCollection(f)?f.getIn(d,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 d=this.get(l,!0);return n.isCollection(d)?d.hasIn(a):!1}setIn(c,l){let[a,...d]=c;if(d.length===0)this.set(a,l);else{let f=this.get(a,!0);if(n.isCollection(f))f.setIn(d,l);else if(f===void 0&&this.schema)this.set(a,i(this.schema,d,l));else throw Error(`Expected YAML collection at ${a}. Remaining path: ${d}`)}}}e.Collection=o,e.collectionFromPath=i,e.isEmptyPath=s}),vn=C(function(e){var t=(i)=>i.replace(/^(?!$)(?: $)?/gm,"#");function n(i,s){if(/^\n+$/.test(i))return i.substring(1);return s?i.replace(/^(?! *$)/gm,s):i}var r=(i,s,o)=>i.endsWith(`
|
|
10
|
+
`)?n(o,s):o.includes(`
|
|
11
|
+
`)?`
|
|
12
|
+
`+n(o,s):(i.endsWith(" ")?"":" ")+o;e.indentComment=n,e.lineComment=r,e.stringifyComment=t}),fd=C(function(e){var t="flow",n="block",r="quoted";function i(o,c,l="flow",{indentAtStart:a,lineWidth:d=80,minContentWidth:f=20,onFold:h,onOverflow:u}={}){if(!d||d<0)return o;if(d<f)f=0;let p=Math.max(1+f,1+d-c.length);if(o.length<=p)return o;let m=[],g={},y=d-c.length;if(typeof a==="number")if(a>d-Math.max(2,f))m.push(0);else y=d-a;let w=void 0,v=void 0,T=!1,b=-1,k=-1,A=-1;if(l===n){if(b=s(o,b,c.length),b!==-1)y=b+p}for(let I;I=o[b+=1];){if(l===r&&I==="\\"){switch(k=b,o[b+1]){case"x":b+=3;break;case"u":b+=5;break;case"U":b+=9;break;default:b+=1}A=b}if(I===`
|
|
13
|
+
`){if(l===n)b=s(o,b,c.length);y=b+c.length+p,w=void 0}else{if(I===" "&&v&&v!==" "&&v!==`
|
|
14
|
+
`&&v!=="\t"){let O=o[b+1];if(O&&O!==" "&&O!==`
|
|
15
|
+
`&&O!=="\t")w=b}if(b>=y)if(w)m.push(w),y=w+p,w=void 0;else if(l===r){while(v===" "||v==="\t")v=I,I=o[b+=1],T=!0;let O=b>A+1?b-2:k-1;if(g[O])return o;m.push(O),g[O]=!0,y=O+p,w=void 0}else T=!0}v=I}if(T&&u)u();if(m.length===0)return o;if(h)h();let N=o.slice(0,m[0]);for(let I=0;I<m.length;++I){let O=m[I],R=m[I+1]||o.length;if(O===0)N=`
|
|
16
|
+
${c}${o.slice(0,R)}`;else{if(l===r&&g[O])N+=`${o[O]}\\`;N+=`
|
|
17
|
+
${c}${o.slice(O+1,R)}`}}return N}function s(o,c,l){let a=c,d=c+1,f=o[d];while(f===" "||f==="\t")if(c<d+l)f=o[++c];else{do f=o[++c];while(f&&f!==`
|
|
18
|
+
`);a=c,d=c+1,f=o[d]}return a}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=i}),bn=C(function(e){var t=se(),n=fd(),r=(u,p)=>({indentAtStart:p?u.indent.length:u.indentAtStart,lineWidth:u.options.lineWidth,minContentWidth:u.options.minContentWidth}),i=(u)=>/^(%|---|\.\.\.)/m.test(u);function s(u,p,m){if(!p||p<0)return!1;let g=p-m,y=u.length;if(y<=g)return!1;for(let w=0,v=0;w<y;++w)if(u[w]===`
|
|
19
|
+
`){if(w-v>g)return!0;if(v=w+1,y-v<=g)return!1}return!0}function o(u,p){let m=JSON.stringify(u);if(p.options.doubleQuotedAsJSON)return m;let{implicitKey:g}=p,y=p.options.doubleQuotedMinMultiLineLength,w=p.indent||(i(u)?" ":""),v="",T=0;for(let b=0,k=m[b];k;k=m[++b]){if(k===" "&&m[b+1]==="\\"&&m[b+2]==="n")v+=m.slice(T,b)+"\\ ",b+=1,T=b,k="\\";if(k==="\\")switch(m[b+1]){case"u":{v+=m.slice(T,b);let A=m.substr(b+2,4);switch(A){case"0000":v+="\\0";break;case"0007":v+="\\a";break;case"000b":v+="\\v";break;case"001b":v+="\\e";break;case"0085":v+="\\N";break;case"00a0":v+="\\_";break;case"2028":v+="\\L";break;case"2029":v+="\\P";break;default:if(A.substr(0,2)==="00")v+="\\x"+A.substr(2);else v+=m.substr(b,6)}b+=5,T=b+1}break;case"n":if(g||m[b+2]==='"'||m.length<y)b+=1;else{v+=m.slice(T,b)+`
|
|
20
|
+
|
|
21
|
+
`;while(m[b+2]==="\\"&&m[b+3]==="n"&&m[b+4]!=='"')v+=`
|
|
22
|
+
`,b+=2;if(v+=w,m[b+2]===" ")v+="\\";b+=1,T=b+1}break;default:b+=1}}return v=T?v+m.slice(T):m,g?v:n.foldFlowLines(v,w,n.FOLD_QUOTED,r(p,!1))}function c(u,p){if(p.options.singleQuote===!1||p.implicitKey&&u.includes(`
|
|
23
|
+
`)||/[ \t]\n|\n[ \t]/.test(u))return o(u,p);let m=p.indent||(i(u)?" ":""),g="'"+u.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
24
|
+
${m}`)+"'";return p.implicitKey?g:n.foldFlowLines(g,m,n.FOLD_FLOW,r(p,!1))}function l(u,p){let{singleQuote:m}=p.options,g;if(m===!1)g=o;else{let y=u.includes('"'),w=u.includes("'");if(y&&!w)g=c;else if(w&&!y)g=o;else g=m?c:o}return g(u,p)}var a;try{a=new RegExp(`(^|(?<!
|
|
25
|
+
))
|
|
26
|
+
+(?!
|
|
27
|
+
|$)`,"g")}catch{a=/\n+(?!\n|$)/g}function d({comment:u,type:p,value:m},g,y,w){let{blockQuote:v,commentString:T,lineWidth:b}=g.options;if(!v||/\n[\t ]+$/.test(m))return l(m,g);let k=g.indent||(g.forceBlockIndent||i(m)?" ":""),A=v==="literal"?!0:v==="folded"||p===t.Scalar.BLOCK_FOLDED?!1:p===t.Scalar.BLOCK_LITERAL?!0:!s(m,b,k.length);if(!m)return A?`|
|
|
28
|
+
`:`>
|
|
29
|
+
`;let N,I;for(I=m.length;I>0;--I){let j=m[I-1];if(j!==`
|
|
30
|
+
`&&j!=="\t"&&j!==" ")break}let O=m.substring(I),R=O.indexOf(`
|
|
31
|
+
`);if(R===-1)N="-";else if(m===O||R!==O.length-1){if(N="+",w)w()}else N="";if(O){if(m=m.slice(0,-O.length),O[O.length-1]===`
|
|
32
|
+
`)O=O.slice(0,-1);O=O.replace(a,`$&${k}`)}let x=!1,F,re=-1;for(F=0;F<m.length;++F){let j=m[F];if(j===" ")x=!0;else if(j===`
|
|
33
|
+
`)re=F;else break}let Y=m.substring(0,re<F?re+1:F);if(Y)m=m.substring(Y.length),Y=Y.replace(/\n+/g,`$&${k}`);let ie=(x?k?"2":"1":"")+N;if(u){if(ie+=" "+T(u.replace(/ ?[\r\n]+/g," ")),y)y()}if(!A){let j=m.replace(/\n+/g,`
|
|
34
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${k}`),ce=!1,H=r(g,!0);if(v!=="folded"&&p!==t.Scalar.BLOCK_FOLDED)H.onOverflow=()=>{ce=!0};let le=n.foldFlowLines(`${Y}${j}${O}`,k,n.FOLD_BLOCK,H);if(!ce)return`>${ie}
|
|
35
|
+
${k}${le}`}return m=m.replace(/\n+/g,`$&${k}`),`|${ie}
|
|
36
|
+
${k}${Y}${m}${O}`}function f(u,p,m,g){let{type:y,value:w}=u,{actualString:v,implicitKey:T,indent:b,indentStep:k,inFlow:A}=p;if(T&&w.includes(`
|
|
37
|
+
`)||A&&/[[\]{},]/.test(w))return l(w,p);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(w))return T||A||!w.includes(`
|
|
38
|
+
`)?l(w,p):d(u,p,m,g);if(!T&&!A&&y!==t.Scalar.PLAIN&&w.includes(`
|
|
39
|
+
`))return d(u,p,m,g);if(i(w)){if(b==="")return p.forceBlockIndent=!0,d(u,p,m,g);else if(T&&b===k)return l(w,p)}let N=w.replace(/\n+/g,`$&
|
|
40
|
+
${b}`);if(v){let I=(x)=>x.default&&x.tag!=="tag:yaml.org,2002:str"&&x.test?.test(N),{compat:O,tags:R}=p.doc.schema;if(R.some(I)||O?.some(I))return l(w,p)}return T?N:n.foldFlowLines(N,b,n.FOLD_FLOW,r(p,!1))}function h(u,p,m,g){let{implicitKey:y,inFlow:w}=p,v=typeof u.value==="string"?u:Object.assign({},u,{value:String(u.value)}),{type:T}=u;if(T!==t.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(v.value))T=t.Scalar.QUOTE_DOUBLE}let b=(A)=>{switch(A){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return y||w?l(v.value,p):d(v,p,m,g);case t.Scalar.QUOTE_DOUBLE:return o(v.value,p);case t.Scalar.QUOTE_SINGLE:return c(v.value,p);case t.Scalar.PLAIN:return f(v,p,m,g);default:return null}},k=b(T);if(k===null){let{defaultKeyType:A,defaultStringType:N}=p.options,I=y&&A||N;if(k=b(I),k===null)throw Error(`Unsupported default string type ${I}`)}return k}e.stringifyString=h}),_n=C(function(e){var t=Or(),n=z(),r=vn(),i=bn();function s(a,d){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,d),h;switch(f.collectionStyle){case"block":h=!1;break;case"flow":h=!0;break;default:h=null}return{anchors:new Set,doc:a,flowCollectionPadding:f.flowCollectionPadding?" ":"",indent:"",indentStep:typeof f.indent==="number"?" ".repeat(f.indent):" ",inFlow:h,options:f}}function o(a,d){if(d.tag){let u=a.filter((p)=>p.tag===d.tag);if(u.length>0)return u.find((p)=>p.format===d.format)??u[0]}let f=void 0,h;if(n.isScalar(d)){h=d.value;let u=a.filter((p)=>p.identify?.(h));if(u.length>1){let p=u.filter((m)=>m.test);if(p.length>0)u=p}f=u.find((p)=>p.format===d.format)??u.find((p)=>!p.format)}else h=d,f=a.find((u)=>u.nodeClass&&h instanceof u.nodeClass);if(!f){let u=h?.constructor?.name??(h===null?"null":typeof h);throw Error(`Tag not resolved for ${u} value`)}return f}function c(a,d,{anchors:f,doc:h}){if(!h.directives)return"";let u=[],p=(n.isScalar(a)||n.isCollection(a))&&a.anchor;if(p&&t.anchorIsValid(p))f.add(p),u.push(`&${p}`);let m=a.tag??(d.default?null:d.tag);if(m)u.push(h.directives.tagString(m));return u.join(" ")}function l(a,d,f,h){if(n.isPair(a))return a.toString(d,f,h);if(n.isAlias(a)){if(d.doc.directives)return a.toString(d);if(d.resolvedAliases?.has(a))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(d.resolvedAliases)d.resolvedAliases.add(a);else d.resolvedAliases=new Set([a]);a=a.resolve(d.doc)}}let u=void 0,p=n.isNode(a)?a:d.doc.createNode(a,{onTagObj:(y)=>u=y});u??(u=o(d.doc.schema.tags,p));let m=c(p,u,d);if(m.length>0)d.indentAtStart=(d.indentAtStart??0)+m.length+1;let g=typeof u.stringify==="function"?u.stringify(p,d,f,h):n.isScalar(p)?i.stringifyString(p,d,f,h):p.toString(d,f,h);if(!m)return g;return n.isScalar(p)||g[0]==="{"||g[0]==="["?`${m} ${g}`:`${m}
|
|
41
|
+
${d.indent}${g}`}e.createStringifyContext=s,e.stringify=l}),hd=C(function(e){var t=z(),n=se(),r=_n(),i=vn();function s({key:o,value:c},l,a,d){let{allNullValues:f,doc:h,indent:u,indentStep:p,options:{commentString:m,indentSeq:g,simpleKeys:y}}=l,w=t.isNode(o)&&o.comment||null;if(y){if(w)throw Error("With simple keys, key nodes cannot have comments");if(t.isCollection(o)||!t.isNode(o)&&typeof o==="object")throw Error("With simple keys, collection cannot be used as a key value")}let v=!y&&(!o||w&&c==null&&!l.inFlow||t.isCollection(o)||(t.isScalar(o)?o.type===n.Scalar.BLOCK_FOLDED||o.type===n.Scalar.BLOCK_LITERAL:typeof o==="object"));l=Object.assign({},l,{allNullValues:!1,implicitKey:!v&&(y||!f),indent:u+p});let T=!1,b=!1,k=r.stringify(o,l,()=>T=!0,()=>b=!0);if(!v&&!l.inFlow&&k.length>1024){if(y)throw Error("With simple keys, single line scalar must not span more than 1024 characters");v=!0}if(l.inFlow){if(f||c==null){if(T&&a)a();return k===""?"?":v?`? ${k}`:k}}else if(f&&!y||c==null&&v){if(k=`? ${k}`,w&&!T)k+=i.lineComment(k,l.indent,m(w));else if(b&&d)d();return k}if(T)w=null;if(v){if(w)k+=i.lineComment(k,l.indent,m(w));k=`? ${k}
|
|
42
|
+
${u}:`}else if(k=`${k}:`,w)k+=i.lineComment(k,l.indent,m(w));let A,N,I;if(t.isNode(c))A=!!c.spaceBefore,N=c.commentBefore,I=c.comment;else if(A=!1,N=null,I=null,c&&typeof c==="object")c=h.createNode(c);if(l.implicitKey=!1,!v&&!w&&t.isScalar(c))l.indentAtStart=k.length+1;if(b=!1,!g&&p.length>=2&&!l.inFlow&&!v&&t.isSeq(c)&&!c.flow&&!c.tag&&!c.anchor)l.indent=l.indent.substring(2);let O=!1,R=r.stringify(c,l,()=>O=!0,()=>b=!0),x=" ";if(w||A||N){if(x=A?`
|
|
43
|
+
`:"",N){let F=m(N);x+=`
|
|
44
|
+
${i.indentComment(F,l.indent)}`}if(R===""&&!l.inFlow){if(x===`
|
|
45
|
+
`&&I)x=`
|
|
46
|
+
|
|
47
|
+
`}else x+=`
|
|
48
|
+
${l.indent}`}else if(!v&&t.isCollection(c)){let F=R[0],re=R.indexOf(`
|
|
49
|
+
`),Y=re!==-1,Te=l.inFlow??c.flow??c.items.length===0;if(Y||!Te){let ie=!1;if(Y&&(F==="&"||F==="!")){let j=R.indexOf(" ");if(F==="&"&&j!==-1&&j<re&&R[j+1]==="!")j=R.indexOf(" ",j+1);if(j===-1||re<j)ie=!0}if(!ie)x=`
|
|
50
|
+
${l.indent}`}}else if(R===""||R[0]===`
|
|
51
|
+
`)x="";if(k+=x+R,l.inFlow){if(O&&a)a()}else if(I&&!O)k+=i.lineComment(k,l.indent,m(I));else if(b&&d)d();return k}e.stringifyPair=s}),fo=C(function(e){var t=mn("process");function n(i,...s){if(i==="debug")console.log(...s)}function r(i,s){if(i==="debug"||i==="warn")if(typeof t.emitWarning==="function")t.emitWarning(s);else console.warn(s)}e.debug=n,e.warn=r}),Cr=C(function(e){var t=z(),n=se(),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:o}),stringify:()=>r},s=(a,d)=>(i.identify(d)||t.isScalar(d)&&(!d.type||d.type===n.Scalar.PLAIN)&&i.identify(d.value))&&a?.doc.schema.tags.some((f)=>f.tag===i.tag&&f.default);function o(a,d,f){let h=l(a,f);if(t.isSeq(h))for(let u of h.items)c(a,d,u);else if(Array.isArray(h))for(let u of h)c(a,d,u);else c(a,d,h)}function c(a,d,f){let h=l(a,f);if(!t.isMap(h))throw Error("Merge sources must be maps or map aliases");let u=h.toJSON(null,a,Map);for(let[p,m]of u)if(d instanceof Map){if(!d.has(p))d.set(p,m)}else if(d instanceof Set)d.add(p);else if(!Object.prototype.hasOwnProperty.call(d,p))Object.defineProperty(d,p,{value:m,writable:!0,enumerable:!0,configurable:!0});return d}function l(a,d){return a&&t.isAlias(d)?d.resolve(a.doc,a):d}e.addMergeToJSMap=o,e.isMergeKey=s,e.merge=i}),ho=C(function(e){var t=fo(),n=Cr(),r=_n(),i=z(),s=tt();function o(l,a,{key:d,value:f}){if(i.isNode(d)&&d.addToJSMap)d.addToJSMap(l,a,f);else if(n.isMergeKey(l,d))n.addMergeToJSMap(l,a,f);else{let h=s.toJS(d,"",l);if(a instanceof Map)a.set(h,s.toJS(f,h,l));else if(a instanceof Set)a.add(h);else{let u=c(d,h,l),p=s.toJS(f,u,l);if(u in a)Object.defineProperty(a,u,{value:p,writable:!0,enumerable:!0,configurable:!0});else a[u]=p}}return a}function c(l,a,d){if(a===null)return"";if(typeof a!=="object")return String(a);if(i.isNode(l)&&d?.doc){let f=r.createStringifyContext(d.doc,{});f.anchors=new Set;for(let u of d.anchors.keys())f.anchors.add(u.anchor);f.inFlow=!0,f.inStringifyKey=!0;let h=l.toString(f);if(!d.mapKeyWarned){let u=JSON.stringify(h);if(u.length>40)u=u.substring(0,36)+'..."';t.warn(d.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${u}. Set mapAsMap: true to use object keys.`),d.mapKeyWarned=!0}return h}return JSON.stringify(a)}e.addPairToJSMap=o}),nt=C(function(e){var t=wn(),n=hd(),r=ho(),i=z();function s(c,l,a){let d=t.createNode(c,void 0,a),f=t.createNode(l,void 0,a);return new o(d,f)}class o{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 o(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=o,e.createPair=s}),po=C(function(e){var t=z(),n=_n(),r=vn();function i(l,a,d){return(a.inFlow??l.flow?o:s)(l,a,d)}function s({comment:l,items:a},d,{blockItemPrefix:f,flowChars:h,itemIndent:u,onChompKeep:p,onComment:m}){let{indent:g,options:{commentString:y}}=d,w=Object.assign({},d,{indent:u,type:null}),v=!1,T=[];for(let k=0;k<a.length;++k){let A=a[k],N=null;if(t.isNode(A)){if(!v&&A.spaceBefore)T.push("");if(c(d,T,A.commentBefore,v),A.comment)N=A.comment}else if(t.isPair(A)){let O=t.isNode(A.key)?A.key:null;if(O){if(!v&&O.spaceBefore)T.push("");c(d,T,O.commentBefore,v)}}v=!1;let I=n.stringify(A,w,()=>N=null,()=>v=!0);if(N)I+=r.lineComment(I,u,y(N));if(v&&N)v=!1;T.push(f+I)}let b;if(T.length===0)b=h.start+h.end;else{b=T[0];for(let k=1;k<T.length;++k){let A=T[k];b+=A?`
|
|
52
|
+
${g}${A}`:`
|
|
53
|
+
`}}if(l){if(b+=`
|
|
54
|
+
`+r.indentComment(y(l),g),m)m()}else if(v&&p)p();return b}function o({items:l},a,{flowChars:d,itemIndent:f}){let{indent:h,indentStep:u,flowCollectionPadding:p,options:{commentString:m}}=a;f+=u;let g=Object.assign({},a,{indent:f,inFlow:!0,type:null}),y=!1,w=0,v=[];for(let k=0;k<l.length;++k){let A=l[k],N=null;if(t.isNode(A)){if(A.spaceBefore)v.push("");if(c(a,v,A.commentBefore,!1),A.comment)N=A.comment}else if(t.isPair(A)){let O=t.isNode(A.key)?A.key:null;if(O){if(O.spaceBefore)v.push("");if(c(a,v,O.commentBefore,!1),O.comment)y=!0}let R=t.isNode(A.value)?A.value:null;if(R){if(R.comment)N=R.comment;if(R.commentBefore)y=!0}else if(A.value==null&&O?.comment)N=O.comment}if(N)y=!0;let I=n.stringify(A,g,()=>N=null);if(y||(y=v.length>w||I.includes(`
|
|
55
|
+
`)),k<l.length-1)I+=",";else if(a.options.trailingComma){if(a.options.lineWidth>0)y||(y=v.reduce((O,R)=>O+R.length+2,2)+(I.length+2)>a.options.lineWidth);if(y)I+=","}if(N)I+=r.lineComment(I,f,m(N));v.push(I),w=v.length}let{start:T,end:b}=d;if(v.length===0)return T+b;else{if(!y){let k=v.reduce((A,N)=>A+N.length+2,2);y=a.options.lineWidth>0&&k>a.options.lineWidth}if(y){let k=T;for(let A of v)k+=A?`
|
|
56
|
+
${u}${h}${A}`:`
|
|
57
|
+
`;return`${k}
|
|
58
|
+
${h}${b}`}else return`${T}${p}${v.join(" ")}${p}${b}`}}function c({indent:l,options:{commentString:a}},d,f,h){if(f&&h)f=f.replace(/^\n+/,"");if(f){let u=r.indentComment(a(f),l);d.push(u.trimStart())}}e.stringifyCollection=i}),rt=C(function(e){var t=po(),n=ho(),r=Ir(),i=z(),s=nt(),o=se();function c(a,d){let f=i.isScalar(d)?d.value:d;for(let h of a)if(i.isPair(h)){if(h.key===d||h.key===f)return h;if(i.isScalar(h.key)&&h.key.value===f)return h}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,d,f){let{keepUndefined:h,replacer:u}=f,p=new this(a),m=(g,y)=>{if(typeof u==="function")y=u.call(d,g,y);else if(Array.isArray(u)&&!u.includes(g))return;if(y!==void 0||h)p.items.push(s.createPair(g,y,f))};if(d instanceof Map)for(let[g,y]of d)m(g,y);else if(d&&typeof d==="object")for(let g of Object.keys(d))m(g,d[g]);if(typeof a.sortMapEntries==="function")p.items.sort(a.sortMapEntries);return p}add(a,d){let f;if(i.isPair(a))f=a;else if(!a||typeof a!=="object"||!("key"in a))f=new s.Pair(a,a?.value);else f=new s.Pair(a.key,a.value);let h=c(this.items,f.key),u=this.schema?.sortMapEntries;if(h){if(!d)throw Error(`Key ${f.key} already set`);if(i.isScalar(h.value)&&o.isScalarValue(f.value))h.value.value=f.value;else h.value=f.value}else if(u){let p=this.items.findIndex((m)=>u(f,m)<0);if(p===-1)this.items.push(f);else this.items.splice(p,0,f)}else this.items.push(f)}delete(a){let d=c(this.items,a);if(!d)return!1;return this.items.splice(this.items.indexOf(d),1).length>0}get(a,d){let h=c(this.items,a)?.value;return(!d&&i.isScalar(h)?h.value:h)??void 0}has(a){return!!c(this.items,a)}set(a,d){this.add(new s.Pair(a,d),!0)}toJSON(a,d,f){let h=f?new f:d?.mapAsMap?new Map:{};if(d?.onCreate)d.onCreate(h);for(let u of this.items)n.addPairToJSMap(d,h,u);return h}toString(a,d,f){if(!a)return JSON.stringify(this);for(let h of this.items)if(!i.isPair(h))throw Error(`Map items must all be pairs; found ${JSON.stringify(h)} 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:d})}}e.YAMLMap=l,e.findPair=c}),Pt=C(function(e){var t=z(),n=rt(),r={collection:"map",default:!0,nodeClass:n.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(i,s){if(!t.isMap(i))s("Expected a mapping for this tag");return i},createNode:(i,s,o)=>n.YAMLMap.from(i,s,o)};e.map=r}),it=C(function(e){var t=wn(),n=po(),r=Ir(),i=z(),s=se(),o=tt();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 d=l(a);if(typeof d!=="number")return!1;return this.items.splice(d,1).length>0}get(a,d){let f=l(a);if(typeof f!=="number")return;let h=this.items[f];return!d&&i.isScalar(h)?h.value:h}has(a){let d=l(a);return typeof d==="number"&&d<this.items.length}set(a,d){let f=l(a);if(typeof f!=="number")throw Error(`Expected a valid index, not ${a}.`);let h=this.items[f];if(i.isScalar(h)&&s.isScalarValue(d))h.value=d;else this.items[f]=d}toJSON(a,d){let f=[];if(d?.onCreate)d.onCreate(f);let h=0;for(let u of this.items)f.push(o.toJS(u,String(h++),d));return f}toString(a,d,f){if(!a)return JSON.stringify(this);return n.stringifyCollection(this,a,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(a.indent||"")+" ",onChompKeep:f,onComment:d})}static from(a,d,f){let{replacer:h}=f,u=new this(a);if(d&&Symbol.iterator in Object(d)){let p=0;for(let m of d){if(typeof h==="function"){let g=d instanceof Set?m:String(p++);m=h.call(d,g,m)}u.items.push(t.createNode(m,void 0,f))}}return u}}function l(a){let d=i.isScalar(a)?a.value:a;if(d&&typeof d==="string")d=Number(d);return typeof d==="number"&&Number.isInteger(d)&&d>=0?d:null}e.YAMLSeq=c}),Rt=C(function(e){var t=z(),n=it(),r={collection:"seq",default:!0,nodeClass:n.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(i,s){if(!t.isSeq(i))s("Expected a sequence for this tag");return i},createNode:(i,s,o)=>n.YAMLSeq.from(i,s,o)};e.seq=r}),kn=C(function(e){var t=bn(),n={identify:(r)=>typeof r==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(r)=>r,stringify(r,i,s,o){return i=Object.assign({actualString:!0},i),t.stringifyString(r,i,s,o)}};e.string=n}),Pr=C(function(e){var t=se(),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}),mo=C(function(e){var t=se(),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},s){if(r&&n.test.test(r)){let o=r[0]==="t"||r[0]==="T";if(i===o)return r}return i?s.options.trueStr:s.options.falseStr}};e.boolTag=n}),Mt=C(function(e){function t({format:n,minFractionDigits:r,tag:i,value:s}){if(typeof s==="bigint")return String(s);let o=typeof s==="number"?s:Number(s);if(!isFinite(o))return isNaN(o)?".nan":o<0?"-.inf":".inf";let c=Object.is(s,-0)?"-0":JSON.stringify(s);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}),yo=C(function(e){var t=se(),n=Mt(),r={identify:(o)=>typeof o==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(o)=>o.slice(-3).toLowerCase()==="nan"?NaN:o[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:n.stringifyNumber},i={identify:(o)=>typeof o==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(o)=>parseFloat(o),stringify(o){let c=Number(o.value);return isFinite(c)?c.toExponential():n.stringifyNumber(o)}},s={identify:(o)=>typeof o==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(o){let c=new t.Scalar(parseFloat(o)),l=o.indexOf(".");if(l!==-1&&o[o.length-1]==="0")c.minFractionDigits=o.length-l-1;return c},stringify:n.stringifyNumber};e.float=s,e.floatExp=i,e.floatNaN=r}),wo=C(function(e){var t=Mt(),n=(l)=>typeof l==="bigint"||Number.isInteger(l),r=(l,a,d,{intAsBigInt:f})=>f?BigInt(l):parseInt(l.substring(a),d);function i(l,a,d){let{value:f}=l;if(n(f)&&f>=0)return d+f.toString(a);return t.stringifyNumber(l)}var s={identify:(l)=>n(l)&&l>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(l,a,d)=>r(l,2,8,d),stringify:(l)=>i(l,8,"0o")},o={identify:n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(l,a,d)=>r(l,0,10,d),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,d)=>r(l,2,16,d),stringify:(l)=>i(l,16,"0x")};e.int=o,e.intHex=c,e.intOct=s}),pd=C(function(e){var t=Pt(),n=Pr(),r=Rt(),i=kn(),s=mo(),o=yo(),c=wo(),l=[t.map,r.seq,i.string,n.nullTag,s.boolTag,c.intOct,c.int,c.intHex,o.floatNaN,o.floatExp,o.float];e.schema=l}),md=C(function(e){var t=se(),n=Pt(),r=Rt();function i(a){return typeof a==="bigint"||Number.isInteger(a)}var s=({value:a})=>JSON.stringify(a),o=[{identify:(a)=>typeof a==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(a)=>a,stringify:s},{identify:(a)=>a==null,createNode:()=>new t.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:s},{identify:(a)=>typeof a==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(a)=>a==="true",stringify:s},{identify:i,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(a,d,{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:s}],c={default:!0,tag:"",test:/^/,resolve(a,d){return d(`Unresolved plain scalar ${JSON.stringify(a)}`),a}},l=[n.map,r.seq].concat(o,c);e.schema=l}),vo=C(function(e){var t=mn("buffer"),n=se(),r=bn(),i={identify:(s)=>s instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(s,o){if(typeof t.Buffer==="function")return t.Buffer.from(s,"base64");else if(typeof atob==="function"){let c=atob(s.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 o("This environment does not support reading binary tags; either Buffer or atob is required"),s},stringify({comment:s,type:o,value:c},l,a,d){if(!c)return"";let f=c,h;if(typeof t.Buffer==="function")h=f instanceof t.Buffer?f.toString("base64"):t.Buffer.from(f.buffer).toString("base64");else if(typeof btoa==="function"){let u="";for(let p=0;p<f.length;++p)u+=String.fromCharCode(f[p]);h=btoa(u)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(o??(o=n.Scalar.BLOCK_LITERAL),o!==n.Scalar.QUOTE_DOUBLE){let u=Math.max(l.options.lineWidth-l.indent.length,l.options.minContentWidth),p=Math.ceil(h.length/u),m=Array(p);for(let g=0,y=0;g<p;++g,y+=u)m[g]=h.substr(y,u);h=m.join(o===n.Scalar.BLOCK_LITERAL?`
|
|
59
|
+
`:" ")}return r.stringifyString({comment:s,type:o,value:h},l,a,d)}};e.binary=i}),Rr=C(function(e){var t=z(),n=nt(),r=se(),i=it();function s(l,a){if(t.isSeq(l))for(let d=0;d<l.items.length;++d){let f=l.items[d];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 h=f.items[0]||new n.Pair(new r.Scalar(null));if(f.commentBefore)h.key.commentBefore=h.key.commentBefore?`${f.commentBefore}
|
|
60
|
+
${h.key.commentBefore}`:f.commentBefore;if(f.comment){let u=h.value??h.key;u.comment=u.comment?`${f.comment}
|
|
61
|
+
${u.comment}`:f.comment}f=h}l.items[d]=t.isPair(f)?f:new n.Pair(f)}else a("Expected a sequence for this tag");return l}function o(l,a,d){let{replacer:f}=d,h=new i.YAMLSeq(l);h.tag="tag:yaml.org,2002:pairs";let u=0;if(a&&Symbol.iterator in Object(a))for(let p of a){if(typeof f==="function")p=f.call(a,String(u++),p);let m,g;if(Array.isArray(p))if(p.length===2)m=p[0],g=p[1];else throw TypeError(`Expected [key, value] tuple: ${p}`);else if(p&&p instanceof Object){let y=Object.keys(p);if(y.length===1)m=y[0],g=p[m];else throw TypeError(`Expected tuple with one key, not ${y.length} keys`)}else m=p;h.items.push(n.createPair(m,g,d))}return h}var c={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:s,createNode:o};e.createPairs=o,e.pairs=c,e.resolvePairs=s}),bo=C(function(e){var t=z(),n=tt(),r=rt(),i=it(),s=Rr();class o 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=o.tag}toJSON(l,a){if(!a)return super.toJSON(l);let d=new Map;if(a?.onCreate)a.onCreate(d);for(let f of this.items){let h,u;if(t.isPair(f))h=n.toJS(f.key,"",a),u=n.toJS(f.value,h,a);else h=n.toJS(f,"",a);if(d.has(h))throw Error("Ordered maps must not include duplicate keys");d.set(h,u)}return d}static from(l,a,d){let f=s.createPairs(l,a,d),h=new this;return h.items=f.items,h}}o.tag="tag:yaml.org,2002:omap";var c={collection:"seq",identify:(l)=>l instanceof Map,nodeClass:o,default:!1,tag:"tag:yaml.org,2002:omap",resolve(l,a){let d=s.resolvePairs(l,a),f=[];for(let{key:h}of d.items)if(t.isScalar(h))if(f.includes(h.value))a(`Ordered maps must not include duplicate keys: ${h.value}`);else f.push(h.value);return Object.assign(new o,d)},createNode:(l,a,d)=>o.from(l,a,d)};e.YAMLOMap=o,e.omap=c}),gd=C(function(e){var t=se();function n({value:s,source:o},c){if(o&&(s?r:i).test.test(o))return o;return s?c.options.trueStr:c.options.falseStr}var r={identify:(s)=>s===!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:(s)=>s===!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}),yd=C(function(e){var t=se(),n=Mt(),r={identify:(o)=>typeof o==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(o)=>o.slice(-3).toLowerCase()==="nan"?NaN:o[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:n.stringifyNumber},i={identify:(o)=>typeof o==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(o)=>parseFloat(o.replace(/_/g,"")),stringify(o){let c=Number(o.value);return isFinite(c)?c.toExponential():n.stringifyNumber(o)}},s={identify:(o)=>typeof o==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(o){let c=new t.Scalar(parseFloat(o.replace(/_/g,""))),l=o.indexOf(".");if(l!==-1){let a=o.substring(l+1).replace(/_/g,"");if(a[a.length-1]==="0")c.minFractionDigits=a.length}return c},stringify:n.stringifyNumber};e.float=s,e.floatExp=i,e.floatNaN=r}),wd=C(function(e){var t=Mt(),n=(a)=>typeof a==="bigint"||Number.isInteger(a);function r(a,d,f,{intAsBigInt:h}){let u=a[0];if(u==="-"||u==="+")d+=1;if(a=a.substring(d).replace(/_/g,""),h){switch(f){case 2:a=`0b${a}`;break;case 8:a=`0o${a}`;break;case 16:a=`0x${a}`;break}let m=BigInt(a);return u==="-"?BigInt(-1)*m:m}let p=parseInt(a,f);return u==="-"?-1*p:p}function i(a,d,f){let{value:h}=a;if(n(h)){let u=h.toString(d);return h<0?"-"+f+u.substr(1):f+u}return t.stringifyNumber(a)}var s={identify:n,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(a,d,f)=>r(a,2,2,f),stringify:(a)=>i(a,2,"0b")},o={identify:n,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(a,d,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,d,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,d,f)=>r(a,2,16,f),stringify:(a)=>i(a,16,"0x")};e.int=c,e.intBin=s,e.intHex=l,e.intOct=o}),_o=C(function(e){var t=z(),n=nt(),r=rt();class i extends r.YAMLMap{constructor(o){super(o);this.tag=i.tag}add(o){let c;if(t.isPair(o))c=o;else if(o&&typeof o==="object"&&"key"in o&&"value"in o&&o.value===null)c=new n.Pair(o.key,null);else c=new n.Pair(o,null);if(!r.findPair(this.items,c.key))this.items.push(c)}get(o,c){let l=r.findPair(this.items,o);return!c&&t.isPair(l)?t.isScalar(l.key)?l.key.value:l.key:l}set(o,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,o);if(l&&!c)this.items.splice(this.items.indexOf(l),1);else if(!l&&c)this.items.push(new n.Pair(o))}toJSON(o,c){return super.toJSON(o,c,Set)}toString(o,c,l){if(!o)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},o,{allNullValues:!0}),c,l);else throw Error("Set items must all have null values")}static from(o,c,l){let{replacer:a}=l,d=new this(o);if(c&&Symbol.iterator in Object(c))for(let f of c){if(typeof a==="function")f=a.call(c,f,f);d.items.push(n.createPair(f,null,l))}return d}}i.tag="tag:yaml.org,2002:set";var s={collection:"map",identify:(o)=>o instanceof Set,nodeClass:i,default:!1,tag:"tag:yaml.org,2002:set",createNode:(o,c,l)=>i.from(o,c,l),resolve(o,c){if(t.isMap(o))if(o.hasAllNullValues(!0))return Object.assign(new i,o);else c("Set items must all have null values");else c("Expected a mapping for this tag");return o}};e.YAMLSet=i,e.set=s}),ko=C(function(e){var t=Mt();function n(c,l){let a=c[0],d=a==="-"||a==="+"?c.substring(1):c,f=(u)=>l?BigInt(u):Number(u),h=d.replace(/_/g,"").split(":").reduce((u,p)=>u*f(60)+f(p),f(0));return a==="-"?f(-1)*h:h}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 d="";if(l<0)d="-",l*=a(-1);let f=a(60),h=[l%f];if(l<60)h.unshift(0);else if(l=(l-h[0])/f,h.unshift(l%f),l>=60)l=(l-h[0])/f,h.unshift(l);return d+h.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},s={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},o={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(o.test);if(!l)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,a,d,f,h,u,p]=l.map(Number),m=l[7]?Number((l[7]+"00").substr(1,3)):0,g=Date.UTC(a,d-1,f,h||0,u||0,p||0,m),y=l[8];if(y&&y!=="Z"){let w=n(y,!1);if(Math.abs(w)<30)w*=60;g-=60000*w}return new Date(g)},stringify:({value:c})=>c?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};e.floatTime=s,e.intTime=i,e.timestamp=o}),vd=C(function(e){var t=Pt(),n=Pr(),r=Rt(),i=kn(),s=vo(),o=gd(),c=yd(),l=wd(),a=Cr(),d=bo(),f=Rr(),h=_o(),u=ko(),p=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,l.intBin,l.intOct,l.int,l.intHex,c.floatNaN,c.floatExp,c.float,s.binary,a.merge,d.omap,f.pairs,h.set,u.intTime,u.floatTime,u.timestamp];e.schema=p}),bd=C(function(e){var t=Pt(),n=Pr(),r=Rt(),i=kn(),s=mo(),o=yo(),c=wo(),l=pd(),a=md(),d=vo(),f=Cr(),h=bo(),u=Rr(),p=vd(),m=_o(),g=ko(),y=new Map([["core",l.schema],["failsafe",[t.map,r.seq,i.string]],["json",a.schema],["yaml11",p.schema],["yaml-1.1",p.schema]]),w={binary:d.binary,bool:s.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:c.int,intHex:c.intHex,intOct:c.intOct,intTime:g.intTime,map:t.map,merge:f.merge,null:n.nullTag,omap:h.omap,pairs:u.pairs,seq:r.seq,set:m.set,timestamp:g.timestamp},v={"tag:yaml.org,2002:binary":d.binary,"tag:yaml.org,2002:merge":f.merge,"tag:yaml.org,2002:omap":h.omap,"tag:yaml.org,2002:pairs":u.pairs,"tag:yaml.org,2002:set":m.set,"tag:yaml.org,2002:timestamp":g.timestamp};function T(b,k,A){let N=y.get(k);if(N&&!b)return A&&!N.includes(f.merge)?N.concat(f.merge):N.slice();let I=N;if(!I)if(Array.isArray(b))I=[];else{let O=Array.from(y.keys()).filter((R)=>R!=="yaml11").map((R)=>JSON.stringify(R)).join(", ");throw Error(`Unknown schema "${k}"; use one of ${O} or define customTags array`)}if(Array.isArray(b))for(let O of b)I=I.concat(O);else if(typeof b==="function")I=b(I.slice());if(A)I=I.concat(f.merge);return I.reduce((O,R)=>{let x=typeof R==="string"?w[R]:R;if(!x){let F=JSON.stringify(R),re=Object.keys(w).map((Y)=>JSON.stringify(Y)).join(", ");throw Error(`Unknown custom tag ${F}; use one of ${re}`)}if(!O.includes(x))O.push(x);return O},[])}e.coreKnownTags=v,e.getTags=T}),So=C(function(e){var t=z(),n=Pt(),r=Rt(),i=kn(),s=bd(),o=(l,a)=>l.key<a.key?-1:l.key>a.key?1:0;class c{constructor({compat:l,customTags:a,merge:d,resolveKnownTags:f,schema:h,sortMapEntries:u,toStringDefaults:p}){this.compat=Array.isArray(l)?s.getTags(l,"compat"):l?s.getTags(null,l):null,this.name=typeof h==="string"&&h||"core",this.knownTags=f?s.coreKnownTags:{},this.tags=s.getTags(a,this.name,d),this.toStringOptions=p??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?o:null}clone(){let l=Object.create(c.prototype,Object.getOwnPropertyDescriptors(this));return l.tags=this.tags.slice(),l}}e.Schema=c}),_d=C(function(e){var t=z(),n=_n(),r=vn();function i(s,o){let c=[],l=o.directives===!0;if(o.directives!==!1&&s.directives){let u=s.directives.toString(s);if(u)c.push(u),l=!0;else if(s.directives.docStart)l=!0}if(l)c.push("---");let a=n.createStringifyContext(s,o),{commentString:d}=a.options;if(s.commentBefore){if(c.length!==1)c.unshift("");let u=d(s.commentBefore);c.unshift(r.indentComment(u,""))}let f=!1,h=null;if(s.contents){if(t.isNode(s.contents)){if(s.contents.spaceBefore&&l)c.push("");if(s.contents.commentBefore){let m=d(s.contents.commentBefore);c.push(r.indentComment(m,""))}a.forceBlockIndent=!!s.comment,h=s.contents.comment}let u=h?void 0:()=>f=!0,p=n.stringify(s.contents,a,()=>h=null,u);if(h)p+=r.lineComment(p,"",d(h));if((p[0]==="|"||p[0]===">")&&c[c.length-1]==="---")c[c.length-1]=`--- ${p}`;else c.push(p)}else c.push(n.stringify(s.contents,a));if(s.directives?.docEnd)if(s.comment){let u=d(s.comment);if(u.includes(`
|
|
62
|
+
`))c.push("..."),c.push(r.indentComment(u,""));else c.push(`... ${u}`)}else c.push("...");else{let u=s.comment;if(u&&f)u=u.replace(/^\n+/,"");if(u){if((!f||h)&&c[c.length-1]!=="")c.push("");c.push(r.indentComment(d(u),""))}}return c.join(`
|
|
63
|
+
`)+`
|
|
64
|
+
`}e.stringifyDocument=i}),Sn=C(function(e){var t=yn(),n=Ir(),r=z(),i=nt(),s=tt(),o=So(),c=_d(),l=Or(),a=uo(),d=wn(),f=lo();class h{constructor(p,m,g){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let y=null;if(typeof m==="function"||Array.isArray(m))y=m;else if(g===void 0&&m)g=m,m=void 0;let w=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},g);this.options=w;let{version:v}=w;if(g?._directives){if(this.directives=g._directives.atDocument(),this.directives.yaml.explicit)v=this.directives.yaml.version}else this.directives=new f.Directives({version:v});this.setSchema(v,g),this.contents=p===void 0?null:this.createNode(p,y,g)}clone(){let p=Object.create(h.prototype,{[r.NODE_TYPE]:{value:r.DOC}});if(p.commentBefore=this.commentBefore,p.comment=this.comment,p.errors=this.errors.slice(),p.warnings=this.warnings.slice(),p.options=Object.assign({},this.options),this.directives)p.directives=this.directives.clone();if(p.schema=this.schema.clone(),p.contents=r.isNode(this.contents)?this.contents.clone(p.schema):this.contents,this.range)p.range=this.range.slice();return p}add(p){if(u(this.contents))this.contents.add(p)}addIn(p,m){if(u(this.contents))this.contents.addIn(p,m)}createAlias(p,m){if(!p.anchor){let g=l.anchorNames(this);p.anchor=!m||g.has(m)?l.findNewAnchor(m||"a",g):m}return new t.Alias(p.anchor)}createNode(p,m,g){let y=void 0;if(typeof m==="function")p=m.call({"":p},"",p),y=m;else if(Array.isArray(m)){let F=(Y)=>typeof Y==="number"||Y instanceof String||Y instanceof Number,re=m.filter(F).map(String);if(re.length>0)m=m.concat(re);y=m}else if(g===void 0&&m)g=m,m=void 0;let{aliasDuplicateObjects:w,anchorPrefix:v,flow:T,keepUndefined:b,onTagObj:k,tag:A}=g??{},{onAnchor:N,setAnchors:I,sourceObjects:O}=l.createNodeAnchors(this,v||"a"),R={aliasDuplicateObjects:w??!0,keepUndefined:b??!1,onAnchor:N,onTagObj:k,replacer:y,schema:this.schema,sourceObjects:O},x=d.createNode(p,A,R);if(T&&r.isCollection(x))x.flow=!0;return I(),x}createPair(p,m,g={}){let y=this.createNode(p,null,g),w=this.createNode(m,null,g);return new i.Pair(y,w)}delete(p){return u(this.contents)?this.contents.delete(p):!1}deleteIn(p){if(n.isEmptyPath(p)){if(this.contents==null)return!1;return this.contents=null,!0}return u(this.contents)?this.contents.deleteIn(p):!1}get(p,m){return r.isCollection(this.contents)?this.contents.get(p,m):void 0}getIn(p,m){if(n.isEmptyPath(p))return!m&&r.isScalar(this.contents)?this.contents.value:this.contents;return r.isCollection(this.contents)?this.contents.getIn(p,m):void 0}has(p){return r.isCollection(this.contents)?this.contents.has(p):!1}hasIn(p){if(n.isEmptyPath(p))return this.contents!==void 0;return r.isCollection(this.contents)?this.contents.hasIn(p):!1}set(p,m){if(this.contents==null)this.contents=n.collectionFromPath(this.schema,[p],m);else if(u(this.contents))this.contents.set(p,m)}setIn(p,m){if(n.isEmptyPath(p))this.contents=m;else if(this.contents==null)this.contents=n.collectionFromPath(this.schema,Array.from(p),m);else if(u(this.contents))this.contents.setIn(p,m)}setSchema(p,m={}){if(typeof p==="number")p=String(p);let g;switch(p){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new f.Directives({version:"1.1"});g={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=p;else this.directives=new f.Directives({version:p});g={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;g=null;break;default:{let y=JSON.stringify(p);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${y}`)}}if(m.schema instanceof Object)this.schema=m.schema;else if(g)this.schema=new o.Schema(Object.assign(g,m));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:p,jsonArg:m,mapAsMap:g,maxAliasCount:y,onAnchor:w,reviver:v}={}){let T={anchors:new Map,doc:this,keep:!p,mapAsMap:g===!0,mapKeyWarned:!1,maxAliasCount:typeof y==="number"?y:100},b=s.toJS(this.contents,m??"",T);if(typeof w==="function")for(let{count:k,res:A}of T.anchors.values())w(A,k);return typeof v==="function"?a.applyReviver(v,{"":b},"",b):b}toJSON(p,m){return this.toJS({json:!0,jsonArg:p,mapAsMap:!1,onAnchor:m})}toString(p={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in p&&(!Number.isInteger(p.indent)||Number(p.indent)<=0)){let m=JSON.stringify(p.indent);throw Error(`"indent" option must be a positive integer, not ${m}`)}return c.stringifyDocument(this,p)}}function u(p){if(r.isCollection(p))return!0;throw Error("Expected a YAML collection as document contents")}e.Document=h}),$n=C(function(e){class t extends Error{constructor(s,o,c,l){super();this.name=s,this.code=c,this.message=l,this.pos=o}}class n extends t{constructor(s,o,c){super("YAMLParseError",s,o,c)}}class r extends t{constructor(s,o,c){super("YAMLWarning",s,o,c)}}var i=(s,o)=>(c)=>{if(c.pos[0]===-1)return;c.linePos=c.pos.map((h)=>o.linePos(h));let{line:l,col:a}=c.linePos[0];c.message+=` at line ${l}, column ${a}`;let d=a-1,f=s.substring(o.lineStarts[l-1],o.lineStarts[l]).replace(/[\n\r]+$/,"");if(d>=60&&f.length>80){let h=Math.min(d-39,f.length-79);f="…"+f.substring(h),d-=h-1}if(f.length>80)f=f.substring(0,79)+"…";if(l>1&&/^ *$/.test(f.substring(0,d))){let h=s.substring(o.lineStarts[l-2],o.lineStarts[l-1]);if(h.length>80)h=h.substring(0,79)+`…
|
|
65
|
+
`;f=h+f}if(/[^ ]/.test(f)){let h=1,u=c.linePos[1];if(u?.line===l&&u.col>a)h=Math.max(1,Math.min(u.col-a,80-d));let p=" ".repeat(d)+"^".repeat(h);c.message+=`:
|
|
66
|
+
|
|
67
|
+
${f}
|
|
68
|
+
${p}
|
|
69
|
+
`}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=i}),Tn=C(function(e){function t(n,{flow:r,indicator:i,next:s,offset:o,onError:c,parentIndent:l,startOnNewline:a}){let d=!1,f=a,h=a,u="",p="",m=!1,g=!1,y=null,w=null,v=null,T=null,b=null,k=null,A=null;for(let O of n){if(g){if(O.type!=="space"&&O.type!=="newline"&&O.type!=="comma")c(O.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");g=!1}if(y){if(f&&O.type!=="comment"&&O.type!=="newline")c(y,"TAB_AS_INDENT","Tabs are not allowed as indentation");y=null}switch(O.type){case"space":if(!r&&(i!=="doc-start"||s?.type!=="flow-collection")&&O.source.includes("\t"))y=O;h=!0;break;case"comment":{if(!h)c(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=O.source.substring(1)||" ";if(!u)u=R;else u+=p+R;p="",f=!1;break}case"newline":if(f){if(u)u+=O.source;else if(!k||i!=="seq-item-ind")d=!0}else p+=O.source;if(f=!0,m=!0,w||v)T=O;h=!0;break;case"anchor":if(w)c(O,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(O.source.endsWith(":"))c(O.offset+O.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);w=O,A??(A=O.offset),f=!1,h=!1,g=!0;break;case"tag":{if(v)c(O,"MULTIPLE_TAGS","A node can have at most one tag");v=O,A??(A=O.offset),f=!1,h=!1,g=!0;break}case i:if(w||v)c(O,"BAD_PROP_ORDER",`Anchors and tags must be after the ${O.source} indicator`);if(k)c(O,"UNEXPECTED_TOKEN",`Unexpected ${O.source} in ${r??"collection"}`);k=O,f=i==="seq-item-ind"||i==="explicit-key-ind",h=!1;break;case"comma":if(r){if(b)c(O,"UNEXPECTED_TOKEN",`Unexpected , in ${r}`);b=O,f=!1,h=!1;break}default:c(O,"UNEXPECTED_TOKEN",`Unexpected ${O.type} token`),f=!1,h=!1}}let N=n[n.length-1],I=N?N.offset+N.source.length:o;if(g&&s&&s.type!=="space"&&s.type!=="newline"&&s.type!=="comma"&&(s.type!=="scalar"||s.source!==""))c(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(y&&(f&&y.indent<=l||s?.type==="block-map"||s?.type==="block-seq"))c(y,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:b,found:k,spaceBefore:d,comment:u,hasNewline:m,anchor:w,tag:v,newlineAfterProp:T,end:I,start:A??I}}e.resolveProps=t}),Mr=C(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}),$o=C(function(e){var t=Mr();function n(r,i,s){if(i?.type==="flow-collection"){let o=i.end[0];if(o.indent===r&&(o.source==="]"||o.source==="}")&&t.containsNewline(i))s(o,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}e.flowIndentCheck=n}),To=C(function(e){var t=z();function n(r,i,s){let{uniqueKeys:o}=r.options;if(o===!1)return!1;let c=typeof o==="function"?o:(l,a)=>l===a||t.isScalar(l)&&t.isScalar(a)&&l.value===a.value;return i.some((l)=>c(l.key,s))}e.mapIncludes=n}),kd=C(function(e){var t=nt(),n=rt(),r=Tn(),i=Mr(),s=$o(),o=To(),c="All mapping items must start at the same column";function l({composeNode:a,composeEmptyNode:d},f,h,u,p){let g=new(p?.nodeClass??n.YAMLMap)(f.schema);if(f.atRoot)f.atRoot=!1;let y=h.offset,w=null;for(let v of h.items){let{start:T,key:b,sep:k,value:A}=v,N=r.resolveProps(T,{indicator:"explicit-key-ind",next:b??k?.[0],offset:y,onError:u,parentIndent:h.indent,startOnNewline:!0}),I=!N.found;if(I){if(b){if(b.type==="block-seq")u(y,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in b&&b.indent!==h.indent)u(y,"BAD_INDENT",c)}if(!N.anchor&&!N.tag&&!k){if(w=N.end,N.comment)if(g.comment)g.comment+=`
|
|
71
|
+
`+N.comment;else g.comment=N.comment;continue}if(N.newlineAfterProp||i.containsNewline(b))u(b??T[T.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(N.found?.indent!==h.indent)u(y,"BAD_INDENT",c);f.atKey=!0;let O=N.end,R=b?a(f,b,N,u):d(f,O,T,null,N,u);if(f.schema.compat)s.flowIndentCheck(h.indent,b,u);if(f.atKey=!1,o.mapIncludes(f,g.items,R))u(O,"DUPLICATE_KEY","Map keys must be unique");let x=r.resolveProps(k??[],{indicator:"map-value-ind",next:A,offset:R.range[2],onError:u,parentIndent:h.indent,startOnNewline:!b||b.type==="block-scalar"});if(y=x.end,x.found){if(I){if(A?.type==="block-map"&&!x.hasNewline)u(y,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(f.options.strict&&N.start<x.found.offset-1024)u(R.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let F=A?a(f,A,x,u):d(f,y,k,null,x,u);if(f.schema.compat)s.flowIndentCheck(h.indent,A,u);y=F.range[2];let re=new t.Pair(R,F);if(f.options.keepSourceTokens)re.srcToken=v;g.items.push(re)}else{if(I)u(R.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(x.comment)if(R.comment)R.comment+=`
|
|
72
|
+
`+x.comment;else R.comment=x.comment;let F=new t.Pair(R);if(f.options.keepSourceTokens)F.srcToken=v;g.items.push(F)}}if(w&&w<y)u(w,"IMPOSSIBLE","Map comment with trailing content");return g.range=[h.offset,y,w??y],g}e.resolveBlockMap=l}),Sd=C(function(e){var t=it(),n=Tn(),r=$o();function i({composeNode:s,composeEmptyNode:o},c,l,a,d){let h=new(d?.nodeClass??t.YAMLSeq)(c.schema);if(c.atRoot)c.atRoot=!1;if(c.atKey)c.atKey=!1;let u=l.offset,p=null;for(let{start:m,value:g}of l.items){let y=n.resolveProps(m,{indicator:"seq-item-ind",next:g,offset:u,onError:a,parentIndent:l.indent,startOnNewline:!0});if(!y.found)if(y.anchor||y.tag||g)if(g?.type==="block-seq")a(y.end,"BAD_INDENT","All sequence items must start at the same column");else a(u,"MISSING_CHAR","Sequence item without - indicator");else{if(p=y.end,y.comment)h.comment=y.comment;continue}let w=g?s(c,g,y,a):o(c,y.end,m,null,y,a);if(c.schema.compat)r.flowIndentCheck(l.indent,g,a);u=w.range[2],h.items.push(w)}return h.range=[l.offset,u,p??u],h}e.resolveBlockSeq=i}),Lt=C(function(e){function t(n,r,i,s){let o="";if(n){let c=!1,l="";for(let a of n){let{source:d,type:f}=a;switch(f){case"space":c=!0;break;case"comment":{if(i&&!c)s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let h=d.substring(1)||" ";if(!o)o=h;else o+=l+h;l="";break}case"newline":if(o)l+=d;c=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${f} at node end`)}r+=d.length}}return{comment:o,offset:r}}e.resolveEnd=t}),$d=C(function(e){var t=z(),n=nt(),r=rt(),i=it(),s=Lt(),o=Tn(),c=Mr(),l=To(),a="Block collections are not allowed within flow collections",d=(h)=>h&&(h.type==="block-map"||h.type==="block-seq");function f({composeNode:h,composeEmptyNode:u},p,m,g,y){let w=m.start.source==="{",v=w?"flow map":"flow sequence",b=new(y?.nodeClass??(w?r.YAMLMap:i.YAMLSeq))(p.schema);b.flow=!0;let k=p.atRoot;if(k)p.atRoot=!1;if(p.atKey)p.atKey=!1;let A=m.offset+m.start.source.length;for(let x=0;x<m.items.length;++x){let F=m.items[x],{start:re,key:Y,sep:Te,value:ie}=F,j=o.resolveProps(re,{flow:v,indicator:"explicit-key-ind",next:Y??Te?.[0],offset:A,onError:g,parentIndent:m.indent,startOnNewline:!1});if(!j.found){if(!j.anchor&&!j.tag&&!Te&&!ie){if(x===0&&j.comma)g(j.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${v}`);else if(x<m.items.length-1)g(j.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${v}`);if(j.comment)if(b.comment)b.comment+=`
|
|
73
|
+
`+j.comment;else b.comment=j.comment;A=j.end;continue}if(!w&&p.options.strict&&c.containsNewline(Y))g(Y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(x===0){if(j.comma)g(j.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${v}`)}else{if(!j.comma)g(j.start,"MISSING_CHAR",`Missing , between ${v} items`);if(j.comment){let ce="";e:for(let H of re)switch(H.type){case"comma":case"space":break;case"comment":ce=H.source.substring(1);break e;default:break e}if(ce){let H=b.items[b.items.length-1];if(t.isPair(H))H=H.value??H.key;if(H.comment)H.comment+=`
|
|
74
|
+
`+ce;else H.comment=ce;j.comment=j.comment.substring(ce.length+1)}}}if(!w&&!Te&&!j.found){let ce=ie?h(p,ie,j,g):u(p,j.end,Te,null,j,g);if(b.items.push(ce),A=ce.range[2],d(ie))g(ce.range,"BLOCK_IN_FLOW",a)}else{p.atKey=!0;let ce=j.end,H=Y?h(p,Y,j,g):u(p,ce,re,null,j,g);if(d(Y))g(H.range,"BLOCK_IN_FLOW",a);p.atKey=!1;let le=o.resolveProps(Te??[],{flow:v,indicator:"map-value-ind",next:ie,offset:H.range[2],onError:g,parentIndent:m.indent,startOnNewline:!1});if(le.found){if(!w&&!j.found&&p.options.strict){if(Te)for(let Ae of Te){if(Ae===le.found)break;if(Ae.type==="newline"){g(Ae,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(j.start<le.found.offset-1024)g(le.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(ie)if("source"in ie&&ie.source?.[0]===":")g(ie,"MISSING_CHAR",`Missing space after : in ${v}`);else g(le.start,"MISSING_CHAR",`Missing , or : between ${v} items`);let at=ie?h(p,ie,le,g):le.found?u(p,le.end,Te,null,le,g):null;if(at){if(d(ie))g(at.range,"BLOCK_IN_FLOW",a)}else if(le.comment)if(H.comment)H.comment+=`
|
|
75
|
+
`+le.comment;else H.comment=le.comment;let Vn=new n.Pair(H,at);if(p.options.keepSourceTokens)Vn.srcToken=F;if(w){let Ae=b;if(l.mapIncludes(p,Ae.items,H))g(ce,"DUPLICATE_KEY","Map keys must be unique");Ae.items.push(Vn)}else{let Ae=new r.YAMLMap(p.schema);Ae.flow=!0,Ae.items.push(Vn);let xi=(at??H).range;Ae.range=[H.range[0],xi[1],xi[2]],b.items.push(Ae)}A=at?at.range[2]:le.end}}let N=w?"}":"]",[I,...O]=m.end,R=A;if(I?.source===N)R=I.offset+I.source.length;else{let x=v[0].toUpperCase()+v.substring(1),F=k?`${x} must end with a ${N}`:`${x} in block collection must be sufficiently indented and end with a ${N}`;if(g(A,k?"MISSING_CHAR":"BAD_INDENT",F),I&&I.source.length!==1)O.unshift(I)}if(O.length>0){let x=s.resolveEnd(O,R,p.options.strict,g);if(x.comment)if(b.comment)b.comment+=`
|
|
76
|
+
`+x.comment;else b.comment=x.comment;b.range=[m.offset,R,x.offset]}else b.range=[m.offset,R,R];return b}e.resolveFlowCollection=f}),Td=C(function(e){var t=z(),n=se(),r=rt(),i=it(),s=kd(),o=Sd(),c=$d();function l(d,f,h,u,p,m){let g=h.type==="block-map"?s.resolveBlockMap(d,f,h,u,m):h.type==="block-seq"?o.resolveBlockSeq(d,f,h,u,m):c.resolveFlowCollection(d,f,h,u,m),y=g.constructor;if(p==="!"||p===y.tagName)return g.tag=y.tagName,g;if(p)g.tag=p;return g}function a(d,f,h,u,p){let m=u.tag,g=!m?null:f.directives.tagName(m.source,(k)=>p(m,"TAG_RESOLVE_FAILED",k));if(h.type==="block-seq"){let{anchor:k,newlineAfterProp:A}=u,N=k&&m?k.offset>m.offset?k:m:k??m;if(N&&(!A||A.offset<N.offset))p(N,"MISSING_CHAR","Missing newline after block sequence props")}let y=h.type==="block-map"?"map":h.type==="block-seq"?"seq":h.start.source==="{"?"map":"seq";if(!m||!g||g==="!"||g===r.YAMLMap.tagName&&y==="map"||g===i.YAMLSeq.tagName&&y==="seq")return l(d,f,h,p,g);let w=f.schema.tags.find((k)=>k.tag===g&&k.collection===y);if(!w){let k=f.schema.knownTags[g];if(k?.collection===y)f.schema.tags.push(Object.assign({},k,{default:!1})),w=k;else{if(k)p(m,"BAD_COLLECTION_TYPE",`${k.tag} used for ${y} collection, but expects ${k.collection??"scalar"}`,!0);else p(m,"TAG_RESOLVE_FAILED",`Unresolved tag: ${g}`,!0);return l(d,f,h,p,g)}}let v=l(d,f,h,p,g,w),T=w.resolve?.(v,(k)=>p(m,"TAG_RESOLVE_FAILED",k),f.options)??v,b=t.isNode(T)?T:new n.Scalar(T);if(b.range=v.range,b.tag=g,w?.format)b.format=w.format;return b}e.composeCollection=a}),Eo=C(function(e){var t=se();function n(s,o,c){let l=o.offset,a=r(o,s.options.strict,c);if(!a)return{value:"",type:null,comment:"",range:[l,l,l]};let d=a.mode===">"?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,f=o.source?i(o.source):[],h=f.length;for(let T=f.length-1;T>=0;--T){let b=f[T][1];if(b===""||b==="\r")h=T;else break}if(h===0){let T=a.chomp==="+"&&f.length>0?`
|
|
77
|
+
`.repeat(Math.max(1,f.length-1)):"",b=l+a.length;if(o.source)b+=o.source.length;return{value:T,type:d,comment:a.comment,range:[l,b,b]}}let u=o.indent+a.indent,p=o.offset+a.length,m=0;for(let T=0;T<h;++T){let[b,k]=f[T];if(k===""||k==="\r"){if(a.indent===0&&b.length>u)u=b.length}else{if(b.length<u)c(p+b.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(a.indent===0)u=b.length;if(m=T,u===0&&!s.atRoot)c(p,"BAD_INDENT","Block scalar values in collections must be indented");break}p+=b.length+k.length+1}for(let T=f.length-1;T>=h;--T)if(f[T][0].length>u)h=T+1;let g="",y="",w=!1;for(let T=0;T<m;++T)g+=f[T][0].slice(u)+`
|
|
78
|
+
`;for(let T=m;T<h;++T){let[b,k]=f[T];p+=b.length+k.length+1;let A=k[k.length-1]==="\r";if(A)k=k.slice(0,-1);if(k&&b.length<u){let I=`Block scalar lines must not be less indented than their ${a.indent?"explicit indentation indicator":"first line"}`;c(p-k.length-(A?2:1),"BAD_INDENT",I),b=""}if(d===t.Scalar.BLOCK_LITERAL)g+=y+b.slice(u)+k,y=`
|
|
79
|
+
`;else if(b.length>u||k[0]==="\t"){if(y===" ")y=`
|
|
80
|
+
`;else if(!w&&y===`
|
|
81
|
+
`)y=`
|
|
82
|
+
|
|
83
|
+
`;g+=y+b.slice(u)+k,y=`
|
|
84
|
+
`,w=!0}else if(k==="")if(y===`
|
|
85
|
+
`)g+=`
|
|
86
|
+
`;else y=`
|
|
87
|
+
`;else g+=y+k,y=" ",w=!1}switch(a.chomp){case"-":break;case"+":for(let T=h;T<f.length;++T)g+=`
|
|
88
|
+
`+f[T][0].slice(u);if(g[g.length-1]!==`
|
|
89
|
+
`)g+=`
|
|
90
|
+
`;break;default:g+=`
|
|
91
|
+
`}let v=l+a.length+o.source.length;return{value:g,type:d,comment:a.comment,range:[l,v,v]}}function r({offset:s,props:o},c,l){if(o[0].type!=="block-scalar-header")return l(o[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:a}=o[0],d=a[0],f=0,h="",u=-1;for(let y=1;y<a.length;++y){let w=a[y];if(!h&&(w==="-"||w==="+"))h=w;else{let v=Number(w);if(!f&&v)f=v;else if(u===-1)u=s+y}}if(u!==-1)l(u,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${a}`);let p=!1,m="",g=a.length;for(let y=1;y<o.length;++y){let w=o[y];switch(w.type){case"space":p=!0;case"newline":g+=w.source.length;break;case"comment":if(c&&!p)l(w,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");g+=w.source.length,m=w.source.substring(1);break;case"error":l(w,"UNEXPECTED_TOKEN",w.message),g+=w.source.length;break;default:{let v=`Unexpected token in block scalar header: ${w.type}`;l(w,"UNEXPECTED_TOKEN",v);let T=w.source;if(T&&typeof T==="string")g+=T.length}}}return{mode:d,indent:f,chomp:h,comment:m,length:g}}function i(s){let o=s.split(/\n( *)/),c=o[0],l=c.match(/^( *)/),d=[l?.[1]?[l[1],c.slice(l[1].length)]:["",c]];for(let f=1;f<o.length;f+=2)d.push([o[f],o[f+1]]);return d}e.resolveBlockScalar=n}),Ao=C(function(e){var t=se(),n=Lt();function r(f,h,u){let{offset:p,type:m,source:g,end:y}=f,w,v,T=(A,N,I)=>u(p+A,N,I);switch(m){case"scalar":w=t.Scalar.PLAIN,v=i(g,T);break;case"single-quoted-scalar":w=t.Scalar.QUOTE_SINGLE,v=s(g,T);break;case"double-quoted-scalar":w=t.Scalar.QUOTE_DOUBLE,v=c(g,T);break;default:return u(f,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${m}`),{value:"",type:null,comment:"",range:[p,p+g.length,p+g.length]}}let b=p+g.length,k=n.resolveEnd(y,b,h,u);return{value:v,type:w,comment:k.comment,range:[p,b,k.offset]}}function i(f,h){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)h(0,"BAD_SCALAR_START",`Plain value cannot start with ${u}`);return o(f)}function s(f,h){if(f[f.length-1]!=="'"||f.length===1)h(f.length,"MISSING_CHAR","Missing closing 'quote");return o(f.slice(1,-1)).replace(/''/g,"'")}function o(f){let h,u;try{h=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
92
|
+
`,"sy"),u=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
93
|
+
`,"sy")}catch{h=/(.*?)[ \t]*\r?\n/sy,u=/[ \t]*(.*?)[ \t]*\r?\n/sy}let p=h.exec(f);if(!p)return f;let m=p[1],g=" ",y=h.lastIndex;u.lastIndex=y;while(p=u.exec(f)){if(p[1]==="")if(g===`
|
|
94
|
+
`)m+=g;else g=`
|
|
95
|
+
`;else m+=g+p[1],g=" ";y=u.lastIndex}let w=/[ \t]*(.*)/sy;return w.lastIndex=y,p=w.exec(f),m+g+(p?.[1]??"")}function c(f,h){let u="";for(let p=1;p<f.length-1;++p){let m=f[p];if(m==="\r"&&f[p+1]===`
|
|
96
|
+
`)continue;if(m===`
|
|
97
|
+
`){let{fold:g,offset:y}=l(f,p);u+=g,p=y}else if(m==="\\"){let g=f[++p],y=a[g];if(y)u+=y;else if(g===`
|
|
98
|
+
`){g=f[p+1];while(g===" "||g==="\t")g=f[++p+1]}else if(g==="\r"&&f[p+1]===`
|
|
99
|
+
`){g=f[++p+1];while(g===" "||g==="\t")g=f[++p+1]}else if(g==="x"||g==="u"||g==="U"){let w=g==="x"?2:g==="u"?4:8;u+=d(f,p+1,w,h),p+=w}else{let w=f.substr(p-1,2);h(p-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${w}`),u+=w}}else if(m===" "||m==="\t"){let g=p,y=f[p+1];while(y===" "||y==="\t")y=f[++p+1];if(y!==`
|
|
100
|
+
`&&!(y==="\r"&&f[p+2]===`
|
|
101
|
+
`))u+=p>g?f.slice(g,p+1):m}else u+=m}if(f[f.length-1]!=='"'||f.length===1)h(f.length,"MISSING_CHAR",'Missing closing "quote');return u}function l(f,h){let u="",p=f[h+1];while(p===" "||p==="\t"||p===`
|
|
102
|
+
`||p==="\r"){if(p==="\r"&&f[h+2]!==`
|
|
103
|
+
`)break;if(p===`
|
|
104
|
+
`)u+=`
|
|
105
|
+
`;h+=1,p=f[h+1]}if(!u)u=" ";return{fold:u,offset:h}}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 d(f,h,u,p){let m=f.substr(h,u),y=m.length===u&&/^[0-9a-fA-F]+$/.test(m)?parseInt(m,16):NaN;try{return String.fromCodePoint(y)}catch{let w=f.substr(h-2,u+2);return p(h-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${w}`),w}}e.resolveFlowScalar=r}),Ed=C(function(e){var t=z(),n=se(),r=Eo(),i=Ao();function s(l,a,d,f){let{value:h,type:u,comment:p,range:m}=a.type==="block-scalar"?r.resolveBlockScalar(l,a,f):i.resolveFlowScalar(a,l.options.strict,f),g=d?l.directives.tagName(d.source,(v)=>f(d,"TAG_RESOLVE_FAILED",v)):null,y;if(l.options.stringKeys&&l.atKey)y=l.schema[t.SCALAR];else if(g)y=o(l.schema,h,g,d,f);else if(a.type==="scalar")y=c(l,h,a,f);else y=l.schema[t.SCALAR];let w;try{let v=y.resolve(h,(T)=>f(d??a,"TAG_RESOLVE_FAILED",T),l.options);w=t.isScalar(v)?v:new n.Scalar(v)}catch(v){let T=v instanceof Error?v.message:String(v);f(d??a,"TAG_RESOLVE_FAILED",T),w=new n.Scalar(h)}if(w.range=m,w.source=h,u)w.type=u;if(g)w.tag=g;if(y.format)w.format=y.format;if(p)w.comment=p;return w}function o(l,a,d,f,h){if(d==="!")return l[t.SCALAR];let u=[];for(let m of l.tags)if(!m.collection&&m.tag===d)if(m.default&&m.test)u.push(m);else return m;for(let m of u)if(m.test?.test(a))return m;let p=l.knownTags[d];if(p&&!p.collection)return l.tags.push(Object.assign({},p,{default:!1,test:void 0})),p;return h(f,"TAG_RESOLVE_FAILED",`Unresolved tag: ${d}`,d!=="tag:yaml.org,2002:str"),l[t.SCALAR]}function c({atKey:l,directives:a,schema:d},f,h,u){let p=d.tags.find((m)=>(m.default===!0||l&&m.default==="key")&&m.test?.test(f))||d[t.SCALAR];if(d.compat){let m=d.compat.find((g)=>g.default&&g.test?.test(f))??d[t.SCALAR];if(p.tag!==m.tag){let g=a.tagString(p.tag),y=a.tagString(m.tag),w=`Value may be parsed as either ${g} or ${y}`;u(h,"TAG_RESOLVE_FAILED",w,!0)}}return p}e.composeScalar=s}),Ad=C(function(e){function t(n,r,i){if(r){i??(i=r.length);for(let s=i-1;s>=0;--s){let o=r[s];switch(o.type){case"space":case"comment":case"newline":n-=o.source.length;continue}o=r[++s];while(o?.type==="space")n+=o.source.length,o=r[++s];break}}return n}e.emptyScalarPosition=t}),Od=C(function(e){var t=yn(),n=z(),r=Td(),i=Ed(),s=Lt(),o=Ad(),c={composeNode:l,composeEmptyNode:a};function l(f,h,u,p){let m=f.atKey,{spaceBefore:g,comment:y,anchor:w,tag:v}=u,T,b=!0;switch(h.type){case"alias":if(T=d(f,h,p),w||v)p(h,"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(T=i.composeScalar(f,h,v,p),w)T.anchor=w.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(T=r.composeCollection(c,f,h,u,p),w)T.anchor=w.source.substring(1)}catch(k){let A=k instanceof Error?k.message:String(k);p(h,"RESOURCE_EXHAUSTION",A)}break;default:{let k=h.type==="error"?h.message:`Unsupported token (type: ${h.type})`;p(h,"UNEXPECTED_TOKEN",k),b=!1}}if(T??(T=a(f,h.offset,void 0,null,u,p)),w&&T.anchor==="")p(w,"BAD_ALIAS","Anchor cannot be an empty string");if(m&&f.options.stringKeys&&(!n.isScalar(T)||typeof T.value!=="string"||T.tag&&T.tag!=="tag:yaml.org,2002:str"))p(v??h,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(g)T.spaceBefore=!0;if(y)if(h.type==="scalar"&&h.source==="")T.comment=y;else T.commentBefore=y;if(f.options.keepSourceTokens&&b)T.srcToken=h;return T}function a(f,h,u,p,{spaceBefore:m,comment:g,anchor:y,tag:w,end:v},T){let b={type:"scalar",offset:o.emptyScalarPosition(h,u,p),indent:-1,source:""},k=i.composeScalar(f,b,w,T);if(y){if(k.anchor=y.source.substring(1),k.anchor==="")T(y,"BAD_ALIAS","Anchor cannot be an empty string")}if(m)k.spaceBefore=!0;if(g)k.comment=g,k.range[2]=v;return k}function d({options:f},{offset:h,source:u,end:p},m){let g=new t.Alias(u.substring(1));if(g.source==="")m(h,"BAD_ALIAS","Alias cannot be an empty string");if(g.source.endsWith(":"))m(h+u.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let y=h+u.length,w=s.resolveEnd(p,y,f.strict,m);if(g.range=[h,y,w.offset],w.comment)g.comment=w.comment;return g}e.composeEmptyNode=a,e.composeNode=l}),Nd=C(function(e){var t=Sn(),n=Od(),r=Lt(),i=Tn();function s(o,c,{offset:l,start:a,value:d,end:f},h){let u=Object.assign({_directives:c},o),p=new t.Document(void 0,u),m={atKey:!1,atRoot:!0,directives:p.directives,options:p.options,schema:p.schema},g=i.resolveProps(a,{indicator:"doc-start",next:d??f?.[0],offset:l,onError:h,parentIndent:0,startOnNewline:!0});if(g.found){if(p.directives.docStart=!0,d&&(d.type==="block-map"||d.type==="block-seq")&&!g.hasNewline)h(g.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}p.contents=d?n.composeNode(m,d,g,h):n.composeEmptyNode(m,g.end,a,null,g,h);let y=p.contents.range[2],w=r.resolveEnd(f,y,!1,h);if(w.comment)p.comment=w.comment;return p.range=[l,y,w.offset],p}e.composeDoc=s}),Oo=C(function(e){var t=mn("process"),n=lo(),r=Sn(),i=$n(),s=z(),o=Nd(),c=Lt();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:h,source:u}=f;return[h,h+(typeof u==="string"?u.length:1)]}function a(f){let h="",u=!1,p=!1;for(let m=0;m<f.length;++m){let g=f[m];switch(g[0]){case"#":h+=(h===""?"":p?`
|
|
107
|
+
|
|
108
|
+
`:`
|
|
109
|
+
`)+(g.substring(1)||" "),u=!0,p=!1;break;case"%":if(f[m+1]?.[0]!=="#")m+=1;u=!1;break;default:if(!u)p=!0;u=!1}}return{comment:h,afterEmptyLine:p}}class d{constructor(f={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(h,u,p,m)=>{let g=l(h);if(m)this.warnings.push(new i.YAMLWarning(g,u,p));else this.errors.push(new i.YAMLParseError(g,u,p))},this.directives=new n.Directives({version:f.version||"1.2"}),this.options=f}decorate(f,h){let{comment:u,afterEmptyLine:p}=a(this.prelude);if(u){let m=f.contents;if(h)f.comment=f.comment?`${f.comment}
|
|
110
|
+
${u}`:u;else if(p||f.directives.docStart||!m)f.commentBefore=u;else if(s.isCollection(m)&&!m.flow&&m.items.length>0){let g=m.items[0];if(s.isPair(g))g=g.key;let y=g.commentBefore;g.commentBefore=y?`${u}
|
|
111
|
+
${y}`:u}else{let g=m.commentBefore;m.commentBefore=g?`${u}
|
|
112
|
+
${g}`:u}}if(h){for(let m=0;m<this.errors.length;++m)f.errors.push(this.errors[m]);for(let m=0;m<this.warnings.length;++m)f.warnings.push(this.warnings[m])}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,h=!1,u=-1){for(let p of f)yield*this.next(p);yield*this.end(h,u)}*next(f){if(t.env.LOG_STREAM)console.dir(f,{depth:null});switch(f.type){case"directive":this.directives.add(f.source,(h,u,p)=>{let m=l(f);m[0]+=h,this.onError(m,"BAD_DIRECTIVE",u,p)}),this.prelude.push(f.source),this.atDirectives=!0;break;case"document":{let h=o.composeDoc(this.options,this.directives,f,this.onError);if(this.atDirectives&&!h.directives.docStart)this.onError(f,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(h,!1),this.doc)yield this.doc;this.doc=h,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(f.source);break;case"error":{let h=f.source?`${f.message}: ${JSON.stringify(f.source)}`:f.message,u=new i.YAMLParseError(l(f),"UNEXPECTED_TOKEN",h);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 h=c.resolveEnd(f.end,f.offset+f.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),h.comment){let u=this.doc.comment;this.doc.comment=u?`${u}
|
|
113
|
+
${h.comment}`:h.comment}this.doc.range[2]=h.offset;break}default:this.errors.push(new i.YAMLParseError(l(f),"UNEXPECTED_TOKEN",`Unsupported token ${f.type}`))}}*end(f=!1,h=-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),p=new r.Document(void 0,u);if(this.atDirectives)this.onError(h,"MISSING_CHAR","Missing directives-end indicator line");p.range=[0,h,h],this.decorate(p,!1),yield p}}}e.Composer=d}),Id=C(function(e){var t=Eo(),n=Ao(),r=$n(),i=bn();function s(f,h=!0,u){if(f){let p=(m,g,y)=>{let w=typeof m==="number"?m:Array.isArray(m)?m[0]:m.offset;if(u)u(w,g,y);else throw new r.YAMLParseError([w,w+1],g,y)};switch(f.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return n.resolveFlowScalar(f,h,p);case"block-scalar":return t.resolveBlockScalar({options:{strict:h}},f,p)}}return null}function o(f,h){let{implicitKey:u=!1,indent:p,inFlow:m=!1,offset:g=-1,type:y="PLAIN"}=h,w=i.stringifyString({type:y,value:f},{implicitKey:u,indent:p>0?" ".repeat(p):"",inFlow:m,options:{blockQuote:!0,lineWidth:-1}}),v=h.end??[{type:"newline",offset:-1,indent:p,source:`
|
|
114
|
+
`}];switch(w[0]){case"|":case">":{let T=w.indexOf(`
|
|
115
|
+
`),b=w.substring(0,T),k=w.substring(T+1)+`
|
|
116
|
+
`,A=[{type:"block-scalar-header",offset:g,indent:p,source:b}];if(!a(A,v))A.push({type:"newline",offset:-1,indent:p,source:`
|
|
117
|
+
`});return{type:"block-scalar",offset:g,indent:p,props:A,source:k}}case'"':return{type:"double-quoted-scalar",offset:g,indent:p,source:w,end:v};case"'":return{type:"single-quoted-scalar",offset:g,indent:p,source:w,end:v};default:return{type:"scalar",offset:g,indent:p,source:w,end:v}}}function c(f,h,u={}){let{afterKey:p=!1,implicitKey:m=!1,inFlow:g=!1,type:y}=u,w="indent"in f?f.indent:null;if(p&&typeof w==="number")w+=2;if(!y)switch(f.type){case"single-quoted-scalar":y="QUOTE_SINGLE";break;case"double-quoted-scalar":y="QUOTE_DOUBLE";break;case"block-scalar":{let T=f.props[0];if(T.type!=="block-scalar-header")throw Error("Invalid block scalar header");y=T.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:y="PLAIN"}let v=i.stringifyString({type:y,value:h},{implicitKey:m||w===null,indent:w!==null&&w>0?" ".repeat(w):"",inFlow:g,options:{blockQuote:!0,lineWidth:-1}});switch(v[0]){case"|":case">":l(f,v);break;case'"':d(f,v,"double-quoted-scalar");break;case"'":d(f,v,"single-quoted-scalar");break;default:d(f,v,"scalar")}}function l(f,h){let u=h.indexOf(`
|
|
118
|
+
`),p=h.substring(0,u),m=h.substring(u+1)+`
|
|
119
|
+
`;if(f.type==="block-scalar"){let g=f.props[0];if(g.type!=="block-scalar-header")throw Error("Invalid block scalar header");g.source=p,f.source=m}else{let{offset:g}=f,y="indent"in f?f.indent:-1,w=[{type:"block-scalar-header",offset:g,indent:y,source:p}];if(!a(w,"end"in f?f.end:void 0))w.push({type:"newline",offset:-1,indent:y,source:`
|
|
120
|
+
`});for(let v of Object.keys(f))if(v!=="type"&&v!=="offset")delete f[v];Object.assign(f,{type:"block-scalar",indent:y,props:w,source:m})}}function a(f,h){if(h)for(let u of h)switch(u.type){case"space":case"comment":f.push(u);break;case"newline":return f.push(u),!0}return!1}function d(f,h,u){switch(f.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":f.type=u,f.source=h;break;case"block-scalar":{let p=f.props.slice(1),m=h.length;if(f.props[0].type==="block-scalar-header")m-=f.props[0].source.length;for(let g of p)g.offset+=m;delete f.props,Object.assign(f,{type:u,source:h,end:p});break}case"block-map":case"block-seq":{let m={type:"newline",offset:f.offset+h.length,indent:f.indent,source:`
|
|
121
|
+
`};delete f.items,Object.assign(f,{type:u,source:h,end:[m]});break}default:{let p="indent"in f?f.indent:-1,m="end"in f&&Array.isArray(f.end)?f.end.filter((g)=>g.type==="space"||g.type==="comment"||g.type==="newline"):[];for(let g of Object.keys(f))if(g!=="type"&&g!=="offset")delete f[g];Object.assign(f,{type:u,indent:p,source:h,end:m})}}}e.createScalarToken=o,e.resolveAsScalar=s,e.setScalarValue=c}),Cd=C(function(e){var t=(i)=>("type"in i)?n(i):r(i);function n(i){switch(i.type){case"block-scalar":{let s="";for(let o of i.props)s+=n(o);return s+i.source}case"block-map":case"block-seq":{let s="";for(let o of i.items)s+=r(o);return s}case"flow-collection":{let s=i.start.source;for(let o of i.items)s+=r(o);for(let o of i.end)s+=o.source;return s}case"document":{let s=r(i);if(i.end)for(let o of i.end)s+=o.source;return s}default:{let s=i.source;if("end"in i&&i.end)for(let o of i.end)s+=o.source;return s}}}function r({start:i,key:s,sep:o,value:c}){let l="";for(let a of i)l+=a.source;if(s)l+=n(s);if(o)for(let a of o)l+=a.source;if(c)l+=n(c);return l}e.stringify=t}),Pd=C(function(e){var t=Symbol("break visit"),n=Symbol("skip children"),r=Symbol("remove item");function i(o,c){if("type"in o&&o.type==="document")o={start:o.start,value:o.value};s(Object.freeze([]),o,c)}i.BREAK=t,i.SKIP=n,i.REMOVE=r,i.itemAtPath=(o,c)=>{let l=o;for(let[a,d]of c){let f=l?.[a];if(f&&"items"in f)l=f.items[d];else return}return l},i.parentCollection=(o,c)=>{let l=i.itemAtPath(o,c.slice(0,-1)),a=c[c.length-1][0],d=l?.[a];if(d&&"items"in d)return d;throw Error("Parent collection not found")};function s(o,c,l){let a=l(c,o);if(typeof a==="symbol")return a;for(let d of["key","value"]){let f=c[d];if(f&&"items"in f){for(let h=0;h<f.items.length;++h){let u=s(Object.freeze(o.concat([[d,h]])),f.items[h],l);if(typeof u==="number")h=u-1;else if(u===t)return t;else if(u===r)f.items.splice(h,1),h-=1}if(typeof a==="function"&&d==="key")a=a(c,o)}}return typeof a==="function"?a(c,o):a}e.visit=i}),Lr=C(function(e){var t=Id(),n=Cd(),r=Pd(),i="\uFEFF",s="\x02",o="\x18",c="\x1F",l=(h)=>!!h&&("items"in h),a=(h)=>!!h&&(h.type==="scalar"||h.type==="single-quoted-scalar"||h.type==="double-quoted-scalar"||h.type==="block-scalar");function d(h){switch(h){case i:return"<BOM>";case s:return"<DOC>";case o:return"<FLOW_END>";case c:return"<SCALAR>";default:return JSON.stringify(h)}}function f(h){switch(h){case i:return"byte-order-mark";case s:return"doc-mode";case o:return"flow-error-end";case c:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
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(h[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=s,e.FLOW_END=o,e.SCALAR=c,e.isCollection=l,e.isScalar=a,e.prettyToken=d,e.tokenType=f}),No=C(function(e){var t=Lr();function n(a){switch(a){case void 0:case" ":case`
|
|
124
|
+
`:case"\r":case"\t":return!0;default:return!1}}var r=new Set("0123456789ABCDEFabcdef"),i=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),s=new Set(",[]{}"),o=new Set(` ,[]{}
|
|
125
|
+
\r `),c=(a)=>!a||o.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,d=!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=!d;let f=this.next??"stream";while(f&&(d||this.hasChars(1)))f=yield*this.parseNext(f)}atLineEnd(){let a=this.pos,d=this.buffer[a];while(d===" "||d==="\t")d=this.buffer[++a];if(!d||d==="#"||d===`
|
|
126
|
+
`)return!0;if(d==="\r")return this.buffer[a+1]===`
|
|
127
|
+
`;return!1}charAt(a){return this.buffer[this.pos+a]}continueScalar(a){let d=this.buffer[a];if(this.indentNext>0){let f=0;while(d===" ")d=this.buffer[++f+a];if(d==="\r"){let h=this.buffer[f+a+1];if(h===`
|
|
128
|
+
`||!h&&!this.atEnd)return a+f+1}return d===`
|
|
129
|
+
`||f>=this.indentNext||!d&&!this.atEnd?a+f:-1}if(d==="-"||d==="."){let f=this.buffer.substr(a,3);if((f==="---"||f==="...")&&n(this.buffer[a+3]))return-1}return a}getLine(){let a=this.lineEndPos;if(typeof a!=="number"||a!==-1&&a<this.pos)a=this.buffer.indexOf(`
|
|
130
|
+
`,this.pos),this.lineEndPos=a;if(a===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[a-1]==="\r")a-=1;return this.buffer.substring(this.pos,a)}hasChars(a){return this.pos+a<=this.buffer.length}setNext(a){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=a,null}peek(a){return this.buffer.substr(this.pos,a)}*parseNext(a){switch(a){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let a=this.getLine();if(a===null)return this.setNext("stream");if(a[0]===t.BOM)yield*this.pushCount(1),a=a.substring(1);if(a[0]==="%"){let d=a.length,f=a.indexOf("#");while(f!==-1){let u=a[f-1];if(u===" "||u==="\t"){d=f-1;break}else f=a.indexOf("#",f+1)}while(!0){let u=a[d-1];if(u===" "||u==="\t")d-=1;else break}let h=(yield*this.pushCount(d))+(yield*this.pushSpaces(!0));return yield*this.pushCount(a.length-h),this.pushNewline(),"stream"}if(this.atLineEnd()){let d=yield*this.pushSpaces(!0);return yield*this.pushCount(a.length-d),yield*this.pushNewline(),"stream"}return yield t.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let a=this.charAt(0);if(!a&&!this.atEnd)return this.setNext("line-start");if(a==="-"||a==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let d=this.peek(3);if((d==="---"||d==="...")&&n(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,d==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!n(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[a,d]=this.peek(2);if(!d&&!this.atEnd)return this.setNext("block-start");if((a==="-"||a==="?"||a===":")&&n(d)){let f=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=f,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let a=this.getLine();if(a===null)return this.setNext("doc");let d=yield*this.pushIndicators();switch(a[d]){case"#":yield*this.pushCount(a.length-d);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(c),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return d+=yield*this.parseBlockScalarHeader(),d+=yield*this.pushSpaces(!0),yield*this.pushCount(a.length-d),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let a,d,f=-1;do{if(a=yield*this.pushNewline(),a>0)d=yield*this.pushSpaces(!1),this.indentValue=f=d;else d=0;d+=yield*this.pushSpaces(!0)}while(a+d>0);let h=this.getLine();if(h===null)return this.setNext("flow");if(f!==-1&&f<this.indentNext&&h[0]!=="#"||f===0&&(h.startsWith("---")||h.startsWith("..."))&&n(h[3])){if(!(f===this.indentNext-1&&this.flowLevel===1&&(h[0]==="]"||h[0]==="}")))return this.flowLevel=0,yield t.FLOW_END,yield*this.parseLineStart()}let u=0;while(h[u]===",")u+=yield*this.pushCount(1),u+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(u+=yield*this.pushIndicators(),h[u]){case void 0:return"flow";case"#":return yield*this.pushCount(h.length-u),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(c),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let p=this.charAt(1);if(this.flowKey||n(p)||p===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let a=this.charAt(0),d=this.buffer.indexOf(a,this.pos+1);if(a==="'")while(d!==-1&&this.buffer[d+1]==="'")d=this.buffer.indexOf("'",d+2);else while(d!==-1){let u=0;while(this.buffer[d-1-u]==="\\")u+=1;if(u%2===0)break;d=this.buffer.indexOf('"',d+1)}let f=this.buffer.substring(0,d),h=f.indexOf(`
|
|
131
|
+
`,this.pos);if(h!==-1){while(h!==-1){let u=this.continueScalar(h+1);if(u===-1)break;h=f.indexOf(`
|
|
132
|
+
`,u)}if(h!==-1)d=h-(f[h-1]==="\r"?2:1)}if(d===-1){if(!this.atEnd)return this.setNext("quoted-scalar");d=this.buffer.length}return yield*this.pushToIndex(d+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let a=this.pos;while(!0){let d=this.buffer[++a];if(d==="+")this.blockScalarKeep=!0;else if(d>"0"&&d<="9")this.blockScalarIndent=Number(d)-1;else if(d!=="-")break}return yield*this.pushUntil((d)=>n(d)||d==="#")}*parseBlockScalar(){let a=this.pos-1,d=0,f;e:for(let u=this.pos;f=this.buffer[u];++u)switch(f){case" ":d+=1;break;case`
|
|
133
|
+
`:a=u,d=0;break;case"\r":{let p=this.buffer[u+1];if(!p&&!this.atEnd)return this.setNext("block-scalar");if(p===`
|
|
134
|
+
`)break}default:break e}if(!f&&!this.atEnd)return this.setNext("block-scalar");if(d>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=d;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let u=this.continueScalar(a+1);if(u===-1)break;a=this.buffer.indexOf(`
|
|
135
|
+
`,u)}while(a!==-1);if(a===-1){if(!this.atEnd)return this.setNext("block-scalar");a=this.buffer.length}}let h=a+1;f=this.buffer[h];while(f===" ")f=this.buffer[++h];if(f==="\t"){while(f==="\t"||f===" "||f==="\r"||f===`
|
|
136
|
+
`)f=this.buffer[++h];a=h-1}else if(!this.blockScalarKeep)do{let u=a-1,p=this.buffer[u];if(p==="\r")p=this.buffer[--u];let m=u;while(p===" ")p=this.buffer[--u];if(p===`
|
|
137
|
+
`&&u>=this.pos&&u+1+d>m)a=u;else break}while(!0);return yield t.SCALAR,yield*this.pushToIndex(a+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let a=this.flowLevel>0,d=this.pos-1,f=this.pos-1,h;while(h=this.buffer[++f])if(h===":"){let u=this.buffer[f+1];if(n(u)||a&&s.has(u))break;d=f}else if(n(h)){let u=this.buffer[f+1];if(h==="\r")if(u===`
|
|
138
|
+
`)f+=1,h=`
|
|
139
|
+
`,u=this.buffer[f+1];else d=f;if(u==="#"||a&&s.has(u))break;if(h===`
|
|
140
|
+
`){let p=this.continueScalar(f+1);if(p===-1)break;f=Math.max(f,p-2)}}else{if(a&&s.has(h))break;d=f}if(!h&&!this.atEnd)return this.setNext("plain-scalar");return yield t.SCALAR,yield*this.pushToIndex(d+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,d){let f=this.buffer.slice(this.pos,a);if(f)return yield f,this.pos+=f.length,f.length;else if(d)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 d=this.flowLevel>0,f=this.charAt(1);if(n(f)||d&&s.has(f)){if(!d)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,d=this.buffer[a];while(!n(d)&&d!==">")d=this.buffer[++a];return yield*this.pushToIndex(d===">"?a+1:a,!1)}else{let a=this.pos+1,d=this.buffer[a];while(d)if(i.has(d))d=this.buffer[++a];else if(d==="%"&&r.has(this.buffer[a+1])&&r.has(this.buffer[a+2]))d=this.buffer[a+=3];else break;return yield*this.pushToIndex(a,!1)}}*pushNewline(){let a=this.buffer[this.pos];if(a===`
|
|
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 d=this.pos-1,f;do f=this.buffer[++d];while(f===" "||a&&f==="\t");let h=d-this.pos;if(h>0)yield this.buffer.substr(this.pos,h),this.pos=d;return h}*pushUntil(a){let d=this.pos,f=this.buffer[d];while(!a(f))f=this.buffer[++d];return yield*this.pushToIndex(d,!1)}}e.Lexer=l}),Io=C(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 o=r+i>>1;if(this.lineStarts[o]<n)r=o+1;else i=o}if(this.lineStarts[r]===n)return{line:r+1,col:1};if(r===0)return{line:0,col:n};let s=this.lineStarts[r-1];return{line:r,col:n-s+1}}}}e.LineCounter=t}),Co=C(function(e){var t=mn("process"),n=Lr(),r=No();function i(h,u){for(let p=0;p<h.length;++p)if(h[p].type===u)return!0;return!1}function s(h){for(let u=0;u<h.length;++u)switch(h[u].type){case"space":case"comment":case"newline":break;default:return u}return-1}function o(h){switch(h?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function c(h){switch(h.type){case"document":return h.start;case"block-map":{let u=h.items[h.items.length-1];return u.sep??u.start}case"block-seq":return h.items[h.items.length-1].start;default:return[]}}function l(h){if(h.length===0)return[];let u=h.length;e:while(--u>=0)switch(h[u].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}while(h[++u]?.type==="space");return h.splice(u,h.length)}function a(h,u){if(u.length<1e5)Array.prototype.push.apply(h,u);else for(let p=0;p<u.length;++p)h.push(u[p])}function d(h){if(h.start.type==="flow-seq-start"){for(let u of h.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,o(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(h){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=h}*parse(h,u=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let p of this.lexer.lex(h,u))yield*this.next(p);if(!u)yield*this.end()}*next(h){if(this.source=h,t.env.LOG_TOKENS)console.log("|",n.prettyToken(h));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=h.length;return}let u=n.tokenType(h);if(!u){let p=`Not a YAML token: ${h}`;yield*this.pop({type:"error",offset:this.offset,message:p,source:h}),this.offset+=h.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+h.length);break;case"space":if(this.atNewLine&&h[0]===" ")this.indent+=h.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=h.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=h.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 h=this.peek(1);if(this.type==="doc-end"&&h?.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(!h)return yield*this.stream();switch(h.type){case"document":return yield*this.document(h);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(h);case"block-scalar":return yield*this.blockScalar(h);case"block-map":return yield*this.blockMap(h);case"block-seq":return yield*this.blockSequence(h);case"flow-collection":return yield*this.flowCollection(h);case"doc-end":return yield*this.documentEnd(h)}yield*this.pop()}peek(h){return this.stack[this.stack.length-h]}*pop(h){let u=h??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 p=this.peek(1);if(u.type==="block-scalar")u.indent="indent"in p?p.indent:0;else if(u.type==="flow-collection"&&p.type==="document")u.indent=0;if(u.type==="flow-collection")d(u);switch(p.type){case"document":p.value=u;break;case"block-scalar":p.props.push(u);break;case"block-map":{let m=p.items[p.items.length-1];if(m.value){p.items.push({start:[],key:u,sep:[]}),this.onKeyLine=!0;return}else if(m.sep)m.value=u;else{Object.assign(m,{key:u,sep:[]}),this.onKeyLine=!m.explicitKey;return}break}case"block-seq":{let m=p.items[p.items.length-1];if(m.value)p.items.push({start:[],value:u});else m.value=u;break}case"flow-collection":{let m=p.items[p.items.length-1];if(!m||m.value)p.items.push({start:[],key:u,sep:[]});else if(m.sep)m.value=u;else Object.assign(m,{key:u,sep:[]});return}default:yield*this.pop(),yield*this.pop(u)}if((p.type==="document"||p.type==="block-map"||p.type==="block-seq")&&(u.type==="block-map"||u.type==="block-seq")){let m=u.items[u.items.length-1];if(m&&!m.sep&&!m.value&&m.start.length>0&&s(m.start)===-1&&(u.indent===0||m.start.every((g)=>g.type!=="comment"||g.indent<u.indent))){if(p.type==="document")p.end=m.start;else p.items.push({start:m.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 h={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")h.start.push(this.sourceToken);this.stack.push(h);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(h){if(h.value)return yield*this.lineEnd(h);switch(this.type){case"doc-start":{if(s(h.start)!==-1)yield*this.pop(),yield*this.step();else h.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":h.start.push(this.sourceToken);return}let u=this.startBlockValue(h);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(h){if(this.type==="map-value-ind"){let u=c(this.peek(2)),p=l(u),m;if(h.end)m=h.end,m.push(this.sourceToken),delete h.end;else m=[this.sourceToken];let g={type:"block-map",offset:h.offset,indent:h.indent,items:[{start:p,key:h,sep:m}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=g}else yield*this.lineEnd(h)}*blockScalar(h){switch(this.type){case"space":case"comment":case"newline":h.props.push(this.sourceToken);return;case"scalar":if(h.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let u=this.source.indexOf(`
|
|
143
|
+
`)+1;while(u!==0)this.onNewLine(this.offset+u),u=this.source.indexOf(`
|
|
144
|
+
`,u)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(h){let u=h.items[h.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,u.value){let p="end"in u.value?u.value.end:void 0;if((Array.isArray(p)?p[p.length-1]:void 0)?.type==="comment")p?.push(this.sourceToken);else h.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)h.items.push({start:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else{if(this.atIndentedComment(u.start,h.indent)){let m=h.items[h.items.length-2]?.value?.end;if(Array.isArray(m)){a(m,u.start),m.push(this.sourceToken),h.items.pop();return}}u.start.push(this.sourceToken)}return}if(this.indent>=h.indent){let p=!this.onKeyLine&&this.indent===h.indent,m=p&&(u.sep||u.explicitKey)&&this.type!=="seq-item-ind",g=[];if(m&&u.sep&&!u.value){let y=[];for(let w=0;w<u.sep.length;++w){let v=u.sep[w];switch(v.type){case"newline":y.push(w);break;case"space":break;case"comment":if(v.indent>h.indent)y.length=0;break;default:y.length=0}}if(y.length>=2)g=u.sep.splice(y[1])}switch(this.type){case"anchor":case"tag":if(m||u.value)g.push(this.sourceToken),h.items.push({start:g}),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(m||u.value)g.push(this.sourceToken),h.items.push({start:g,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 y=l(u.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:y,key:null,sep:[this.sourceToken]}]})}else if(u.value)h.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:g,key:null,sep:[this.sourceToken]}]});else if(o(u.key)&&!i(u.sep,"newline")){let y=l(u.start),{key:w,sep:v}=u;v.push(this.sourceToken),delete u.key,delete u.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:y,key:w,sep:v}]})}else if(g.length>0)u.sep=u.sep.concat(g,this.sourceToken);else u.sep.push(this.sourceToken);else if(!u.sep)Object.assign(u,{key:null,sep:[this.sourceToken]});else if(u.value||m)h.items.push({start:g,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 y=this.flowScalar(this.type);if(m||u.value)h.items.push({start:g,key:y,sep:[]}),this.onKeyLine=!0;else if(u.sep)this.stack.push(y);else Object.assign(u,{key:y,sep:[]}),this.onKeyLine=!0;return}default:{let y=this.startBlockValue(h);if(y){if(y.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(p)h.items.push({start:g});this.stack.push(y);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(h){let u=h.items[h.items.length-1];switch(this.type){case"newline":if(u.value){let p="end"in u.value?u.value.end:void 0;if((Array.isArray(p)?p[p.length-1]:void 0)?.type==="comment")p?.push(this.sourceToken);else h.items.push({start:[this.sourceToken]})}else u.start.push(this.sourceToken);return;case"space":case"comment":if(u.value)h.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(u.start,h.indent)){let m=h.items[h.items.length-2]?.value?.end;if(Array.isArray(m)){a(m,u.start),m.push(this.sourceToken),h.items.pop();return}}u.start.push(this.sourceToken)}return;case"anchor":case"tag":if(u.value||this.indent<=h.indent)break;u.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==h.indent)break;if(u.value||i(u.start,"seq-item-ind"))h.items.push({start:[this.sourceToken]});else u.start.push(this.sourceToken);return}if(this.indent>h.indent){let p=this.startBlockValue(h);if(p){this.stack.push(p);return}}yield*this.pop(),yield*this.step()}*flowCollection(h){let u=h.items[h.items.length-1];if(this.type==="flow-error-end"){let p;do yield*this.pop(),p=this.peek(1);while(p?.type==="flow-collection")}else if(h.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!u||u.sep)h.items.push({start:[this.sourceToken]});else u.start.push(this.sourceToken);return;case"map-value-ind":if(!u||u.value)h.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)h.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 m=this.flowScalar(this.type);if(!u||u.value)h.items.push({start:[],key:m,sep:[]});else if(u.sep)this.stack.push(m);else Object.assign(u,{key:m,sep:[]});return}case"flow-map-end":case"flow-seq-end":h.end.push(this.sourceToken);return}let p=this.startBlockValue(h);if(p)this.stack.push(p);else yield*this.pop(),yield*this.step()}else{let p=this.peek(2);if(p.type==="block-map"&&(this.type==="map-value-ind"&&p.indent===h.indent||this.type==="newline"&&!p.items[p.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&p.type!=="flow-collection"){let m=c(p),g=l(m);d(h);let y=h.end.splice(1,h.end.length);y.push(this.sourceToken);let w={type:"block-map",offset:h.offset,indent:h.indent,items:[{start:g,key:h,sep:y}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=w}else yield*this.lineEnd(h)}}flowScalar(h){if(this.onNewLine){let u=this.source.indexOf(`
|
|
145
|
+
`)+1;while(u!==0)this.onNewLine(this.offset+u),u=this.source.indexOf(`
|
|
146
|
+
`,u)+1}return{type:h,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(h){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(h),p=l(u);return p.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:p,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let u=c(h),p=l(u);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:p,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(h,u){if(this.type!=="comment")return!1;if(this.indent<=u)return!1;return h.every((p)=>p.type==="newline"||p.type==="space")}*documentEnd(h){if(this.type!=="doc-mode"){if(h.end)h.end.push(this.sourceToken);else h.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(h){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(h.end)h.end.push(this.sourceToken);else h.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}e.Parser=f}),Rd=C(function(e){var t=Oo(),n=Sn(),r=$n(),i=fo(),s=z(),o=Io(),c=Co();function l(u){let p=u.prettyErrors!==!1;return{lineCounter:u.lineCounter||p&&new o.LineCounter||null,prettyErrors:p}}function a(u,p={}){let{lineCounter:m,prettyErrors:g}=l(p),y=new c.Parser(m?.addNewLine),w=new t.Composer(p),v=Array.from(w.compose(y.parse(u)));if(g&&m)for(let T of v)T.errors.forEach(r.prettifyError(u,m)),T.warnings.forEach(r.prettifyError(u,m));if(v.length>0)return v;return Object.assign([],{empty:!0},w.streamInfo())}function d(u,p={}){let{lineCounter:m,prettyErrors:g}=l(p),y=new c.Parser(m?.addNewLine),w=new t.Composer(p),v=null;for(let T of w.compose(y.parse(u),!0,u.length))if(!v)v=T;else if(v.options.logLevel!=="silent"){v.errors.push(new r.YAMLParseError(T.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(g&&m)v.errors.forEach(r.prettifyError(u,m)),v.warnings.forEach(r.prettifyError(u,m));return v}function f(u,p,m){let g=void 0;if(typeof p==="function")g=p;else if(m===void 0&&p&&typeof p==="object")m=p;let y=d(u,m);if(!y)return null;if(y.warnings.forEach((w)=>i.warn(y.options.logLevel,w)),y.errors.length>0)if(y.options.logLevel!=="silent")throw y.errors[0];else y.errors=[];return y.toJS(Object.assign({reviver:g},m))}function h(u,p,m){let g=null;if(typeof p==="function"||Array.isArray(p))g=p;else if(m===void 0&&p)m=p;if(typeof m==="string")m=m.length;if(typeof m==="number"){let y=Math.round(m);m=y<1?void 0:y>8?{indent:8}:{indent:y}}if(u===void 0){let{keepUndefined:y}=m??p??{};if(!y)return}if(s.isDocument(u)&&!g)return u.toString(m);return new n.Document(u,g,m).toString(m)}e.parse=f,e.parseAllDocuments=a,e.parseDocument=d,e.stringify=h}),xd="dispach",Dd="Dispach",jd=1;function Po(e,t){return{slug:e,name:t,envPrefix:`${e.toUpperCase()}_`,stateDir:`.${e}`,apiVersion:`${e}/v${jd}`,packageScope:`@${e}`}}var Qt=Po(xd,Dd),en=`${Qt.envPrefix}BRAND`,Ud=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;function zd(e){return e.split("-").map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Fd(e){if(e===void 0)return Qt;let t=e.trim();if(t==="")throw Error(`${en} is set but empty. hint: unset ${en} 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(!Ud.test(t))throw Error(`${en}="${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===Qt.slug)return Qt;return Po(t,zd(t))}var xr=Fd(process.env[en]),Bd=Symbol.for("dispach.HarnessError");class Dr 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[Bd]=!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
|
+
`);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 mr extends Dr{static ERROR_NAME="ConfigError"}class yt extends Dr{static ERROR_NAME="ToolError"}function Kd(e,t){return new yt({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 qd(){return new yt({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 Wd(){return new yt({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 Zd(){return new yt({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 Jd(e){return new yt({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 e$="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),ut=Oe(27),Ro=Oe(7),t$=new RegExp(`${ut}\\[[0-?]*[ -/]*[@-~]`,"g"),n$=new RegExp(`${ut}\\][\\s\\S]*?(?:${Ro}|${ut}\\\\|$)`,"g"),r$=new RegExp(`${ut}[P^_X][\\s\\S]*?(?:${ut}\\\\|${Ro}|$)`,"g"),i$=new RegExp(`${ut}[@-Z\\\\-_0-9=><]?`,"g"),s$=new RegExp(`[${Oe(128)}-${Oe(159)}]`,"g"),o$=new RegExp(`[${Oe(0)}-${Oe(8)}${Oe(11)}${Oe(12)}${Oe(14)}-${Oe(31)}${Oe(127)}]`,"g");function Hd(e){return e==="untrusted"?"obu":"obs"}function Vd(e){return e.startsWith(`${Hd("untrusted")}_`)?"untrusted":"trusted"}var Gd=3.8;function Yd(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/Gd)+t}var Xd="<<<",Qd=">>>",a$=`# Tools
|
|
149
|
+
|
|
150
|
+
To use a tool, write an ACTION block. Start each line at the left margin, exactly like this:
|
|
151
|
+
|
|
152
|
+
ACTION: weather_lookup
|
|
153
|
+
city: Lisbon
|
|
154
|
+
units: celsius
|
|
155
|
+
END
|
|
156
|
+
|
|
157
|
+
That block is an example of the shape only. Your own tools are listed below — take the tool name and
|
|
158
|
+
every field name from that list, spelled exactly as it is written there.
|
|
159
|
+
|
|
160
|
+
Rules for a block:
|
|
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 \`${Xd}\` and close it with \`${Qd}\` alone on its own line.
|
|
163
|
+
- Finish every block with \`END\` alone on its own line.
|
|
164
|
+
- Several blocks are allowed. They run in the order you write them.
|
|
165
|
+
- Use only the tools listed below, only their listed fields, and always give every required field.
|
|
166
|
+
|
|
167
|
+
Anything you write outside a block is shown to the person you are talking to, so keep explanations
|
|
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.`;function gr(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 as(e,t="|"){return e.map((n)=>zo(n)).join(t)}function yr(e,t){if(typeof t==="bigint")return t.toString();return t}class Mo{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function jr(e){return new Mo(e)}function ef(e){return e===null||e===void 0}function Ur(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function tf(e,t){let n=e/t,r=Math.round(n),i=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<i)return 0;return n-r}var cs=Symbol("evaluating");function nf(e,t,n){let r=void 0;Object.defineProperty(e,t,{get(){if(r===cs)return;if(r===void 0)r=cs,r=n();return r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ze(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Lo(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function je(e){return Lo(e._zod.def)??e._zod.def.shape}function xo(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return Ze(this,t,r),r},enumerable:!0,configurable:!0})}function Do(e,t,n){if(t in e)Ze(e,t,n);else e[t]=n}function Xe(e,t,n,r){let i=je(t);for(let s of n){let o=Object.getOwnPropertyDescriptor(i,s);if(!o.enumerable)continue;if(o.get)xo(e,s,()=>{let c=t._zod.def.shape[s];return r?r(c,s):c});else Do(e,s,r?r(o.value,s):o.value)}}function rf(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)xo(e,n,()=>t[n]);else Do(e,n,r.value)}}function we(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function sf(e){return JSON.stringify(e)}function of(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var jo="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function rn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var af=jr(()=>{if(Ce.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function dt(e){if(rn(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(rn(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Uo(e){if(dt(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 cf=new Set(["string","number","symbol"]);function ft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(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 zo(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function lf(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Fo=(()=>({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]}))(),uf={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function df(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 s={};return Xe(s,e,En(e,t)),Je(e,we(n,{shape:s,checks:[]}))}function En(e,t){let n=je(e),r=[];for(let i of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,i)?.enumerable)throw Error(`Unrecognized key: "${String(i)}"`);if(t[i])r.push(i)}return r}function ff(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 s=new Set(En(e,t)),o={};return Xe(o,e,Reflect.ownKeys(je(e)).filter((c)=>!s.has(c))),Je(e,we(n,{shape:o,checks:[]}))}function hf(e,t){if(!dt(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let i=je(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Je(e,we(e._zod.def,{shape:Bo(e,t)}))}function Bo(e,t){let n={};return Xe(n,e,Reflect.ownKeys(je(e))),rf(n,t),n}function pf(e,t){if(!dt(t))throw Error("Invalid input to safeExtend: expected a plain object");return Je(e,we(e._zod.def,{shape:Bo(e,t)}))}function mf(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};Xe(n,e,Reflect.ownKeys(je(e))),Xe(n,t,Reflect.ownKeys(je(t)));let r=we(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Je(e,r)}function ls(e,t,n,r="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let c=n?new Set(En(t,n)):void 0,l={};return Xe(l,t,Reflect.ownKeys(je(t)),e&&((a,d)=>c&&!c.has(d)?a:new e({type:"optional",innerType:a}))),Je(t,we(t._zod.def,{shape:l,checks:[]}))}function gf(e,t,n){let r=n?new Set(En(t,n)):void 0,i={};return Xe(i,t,Reflect.ownKeys(je(t)),(s,o)=>r&&!r.has(o)?s:new e({type:"nonoptional",innerType:s})),Je(t,we(t._zod.def,{shape:i}))}function De(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 yf(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 lt(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Tt(e){return typeof e==="string"?e:e?.message}function us(e){let t=[];for(let n of e??[]){let r=n._zod.def;if(!/_(length|size)$|_equals$/.test(r.check))break;let i=r.maximum??r.length??r.size;if(i>=0)t.push([i,n])}return t}function wr(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function Ke(e,t,n){var r;let i=e.inst?._zod?.traits;if(i?.has("$ZodType"))if(i.has("$ZodCheck"))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst;let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,o=e.message?e.message:Tt(e.inst?._zod.def?.error?.(e))??Tt(s?.(e))??Tt(t?.error?.(e))??Tt(n.customError?.(e))??Tt(n.localeError?.(e))??"Invalid input",c={};for(let l of Object.keys(e)){if(l==="inst"||l==="schema"||l==="continue"||l==="input"||l==="__proto__")continue;c[l]=e[l]}if(c.path??(c.path=[]),c.message=o,t?.reportInput)c.input=e.input;return c}var wf=/[\uD800-\uDBFF]/;function Fr(e){let t=e.length;if(!wf.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320)n--,r++;return n}function Br(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function vf(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Ct(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}function bf(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else _f(e,n,r.value)}}function qe(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Ko(e,t,n){return qe(e,t,n,!1)}function qo(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return qe(this,n,r(this))},set(i){qe(this,n,i)}})}return t}function _f(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:qe(this,t,n.bind(this))},set(r){qe(this,t,r)}})}function kf(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var ir,Fe=!1,Sf={configurable:!0,get(){Fe=!0;return}};function U(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&ir!==e._zod){ir=void 0;return}ir=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Sf);let i=Fe;Fe=!1;try{let s=n(this);if(Fe)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s});return Fe=Fe||i,s}catch(s){throw delete this[t],Fe=Fe||i,s}},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i})}})}function $f(e,t,n,r){let i=kf(e,t);if(!i)return;Object.defineProperty(i,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,s),s.value=n(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:s})}})}var Tf="~constantCatch";function Ef(e){let t=()=>e;return t[Tf]=!0,t}var ds,sr={value:void 0,enumerable:!1},fs="captureStackTrace"in Error?Error:null;function Af(e){let t=fs;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return fs=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function E(e,t,n,r){let i={};function s(h){this.def=h,this.constr=f,this.traits=new Set}s.prototype=i;let o=n,c=o&&new WeakSet;function l(h,u){if(!h._zod){sr.value=new s(u);try{Object.defineProperty(h,"_zod",sr)}finally{sr.value=void 0}}else if(h._zod.traits.has(e))return;if(h._zod.traits.add(e),t(h,u),c){let m=Object.getPrototypeOf(h),g=h._zod.constr.prototype,y=m;while(y&&y!==g)y=Object.getPrototypeOf(y);let w=y??m;if(!c.has(w))c.add(w),bf(w,o)}let p=f.prototype;for(let m in p){if(!Object.prototype.hasOwnProperty.call(p,m))continue;if(!(m in h))h[m]=p[m].bind(h)}}let a=r?.Parent??Object;class d extends a{}Object.defineProperty(d,"name",{value:e});function f(h){let u=r?.Parent?Af(d):this;l(u,h);let p=u._zod.deferred;if(p){for(let g of p)g();u._zod.deferred=void 0}let m=globalThis.__zod_globalConfig?.postProcessor;if(m)m(u);return u}return Object.defineProperty(f,"init",{value:l}),Object.defineProperty(f,Symbol.hasInstance,{value:(h)=>{if(r?.Parent&&h instanceof r.Parent)return!0;return h?._zod?.traits?.has(e)}}),Object.defineProperty(f,"name",{value:e}),f}class Be extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Kr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(ds=globalThis).__zod_globalConfig??(ds.__zod_globalConfig={});var Ce=globalThis.__zod_globalConfig;function Me(e){if(e)Object.assign(Ce,e);return Ce}function Of(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,yr,2)),e.message}function Nf(e){this._zod.message=e}var If={get:Of,set:Nf,enumerable:!0,configurable:!0},or={value:void 0,enumerable:!1},hs=new WeakSet([Object.prototype,Error.prototype]),Wo=(e,t)=>{e.name="$ZodError",or.value=t,Object.defineProperty(e,"issues",or),or.value=void 0,Object.defineProperty(e,"message",If);let n=Object.getPrototypeOf(e);if(!hs.has(n))hs.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}})},Cf=E("$ZodError",Wo),c$=E("$ZodError",Wo,void 0,{Parent:Error});function Pf(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function Rf(e,t=(n)=>n.message){let n={},r=[];for(let i of e.issues)if(i.path.length>0)Pf(n,i.path[0],()=>[]).push(t(i));else r.push(t(i));return{formErrors:r,fieldErrors:n}}function Mf(e,t=(n)=>n.message){let n={_errors:[]},r=(i,s=[])=>{for(let o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map((c)=>r({issues:c},[...s,...o.path]));else if(o.code==="invalid_key")r({issues:o.issues},[...s,...o.path]);else if(o.code==="invalid_element")r({issues:o.issues},[...s,...o.path]);else{let c=[...s,...o.path];if(c.length===0)n._errors.push(t(o));else{let l=n,a=0;while(a<c.length){let d=c[a],f=a===c.length-1;if(d==="_errors"){if(f)l._errors.push(t(o));a++;continue}if(!Object.prototype.hasOwnProperty.call(l,d))Object.defineProperty(l,d,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let h=l[d];if(f)h._errors.push(t(o));l=h,a++}}}};return r(e),n}function An(e,t){return{callee:t?.callee??e,Err:t?.Err}}var qr=(e)=>{let t=(n,r,i,s)=>{let o=i?{...i,async:!1}:{async:!1},c=n._zod.run({value:r,issues:[]},o);if(c instanceof Promise)throw new Be;if(c.issues.length){let l=new(s?.Err??e)(c.issues.map((a)=>Ke(a,o,Me())));throw jo(l,s?.callee??t),l}return c.value};return t},Wr=(e)=>{let t=async(n,r,i,s)=>{let o=i?{...i,async:!0}:{async:!0},c=n._zod.run({value:r,issues:[]},o);if(c instanceof Promise)c=await c;if(c.issues.length){let l=new(s?.Err??e)(c.issues.map((a)=>Ke(a,o,Me())));throw jo(l,s?.callee??t),l}return c.value};return t},Zr=(e)=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Be;return s.issues.length?Zo(e,s.issues,i):{success:!0,data:s.value}};function Zo(e,t,n){let r;return{success:!1,get error(){if(!r)r=new e(t.map((i)=>Ke(i,n,Me()))),t=void 0,n=void 0;return r},set error(i){r=i,t=void 0,n=void 0}}}var Hr=(e)=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)s=await s;return s.issues.length?Zo(e,s.issues,i):{success:!0,data:s.value}},Lf=Symbol.for("zod.compile.invalid"),xf=Symbol.for("zod.compile.fallback"),Df=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Lf)return!0;if(r.definite===!0&&n===void 0)return!1}return jf(e,t,n)};function jf(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,s;if(i)r[xf]=!0,s=i({value:t,issues:[]},r);else s=e._zod.run({value:t,issues:[]},r);if(s instanceof Promise)throw new Be;return s.issues.length===0}var Uf=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);if(i instanceof Promise)i=await i;return i.issues.length===0},zf=(e)=>{let t=qr(e),n=(r,i,s,o)=>{let c=s?{...s,direction:"backward"}:{direction:"backward"};return t(r,i,c,An(n,o))};return n},Ff=(e)=>{let t=qr(e),n=(r,i,s,o)=>t(r,i,s,An(n,o));return n},Bf=(e)=>{let t=Wr(e),n=async(r,i,s,o)=>{let c=s?{...s,direction:"backward"}:{direction:"backward"};return await t(r,i,c,An(n,o))};return n},Kf=(e)=>{let t=Wr(e),n=async(r,i,s,o)=>await t(r,i,s,An(n,o));return n},qf=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return Zr(e)(t,n,i)},Wf=(e)=>(t,n,r)=>Zr(e)(t,n,r),Zf=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return Hr(e)(t,n,i)},Jf=(e)=>async(t,n,r)=>Hr(e)(t,n,r),Hf=/^[cC][0-9a-z]{6,}$/,Vf=/^[0-9a-z]+$/,Gf=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Yf=/^[0-9a-vA-V]{20}$/,Xf=/^[A-Za-z0-9]{27}$/,Qf=/^[a-zA-Z0-9_-]{21}$/;function eh(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var th=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,nh=/^([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})$/,ps=(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})$`)},rh=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ih="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function sh(){return new RegExp(ih,"u")}var oh=/^(?:(?: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])$/,ah=/^(([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}|:))$/,ch=/^((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])$/,lh=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,uh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,dh=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,fh=/^https?$/,hh=/^\+[1-9]\d{6,14}$/,Jo="(?:(?:\\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])))";function ph(e){return new RegExp(`^${e}$`)}var mh=ph(Jo);function vr(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}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function gh(e){return new RegExp(`^${vr(e)}$`)}function yh(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${vr({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${vr({precision:e.precision})}`:n;return new RegExp(`^${Jo}T(?:${r})$`)}var wh=/^[\s\S]{0,}$/,vh=/^-?\d+$/,Vr=/^-?\d+(?:\.\d+)?$/,bh=/^(?:true|false)$/i,_h=/^[^A-Z]*$/,kh=/^[^a-z]*$/,pe=E("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Gr=(e)=>{let t=e.value;return!ef(t)&&t.length!==void 0},sn={number:"number",bigint:"bigint",object:"date"},Ho=E("$ZodCheckLessThan",(e,t)=>{pe.init(e,t);let n=sn[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:sn[typeof r.value]??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})}}),Vo=E("$ZodCheckGreaterThan",(e,t)=>{pe.init(e,t);let n=sn[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:sn[typeof r.value]??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})}}),Sh=E("$ZodCheckMultipleOf",(e,t)=>{pe.init(e,t),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"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):tf(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})}}),$h=E("$ZodCheckNumberFormat",(e,t)=>{pe.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,s]=Fo[t.format];e._zod.check=(o)=>{let c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){if(c>0)o.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 o.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)o.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort});if(c>s)o.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Th=E("$ZodCheckMaxLength",(e,t)=>{var n;pe.init(e,t),(n=e._zod.def).when??(n.when=Gr),e._zod.check=(r)=>{let i=r.value,s=i.length;if((typeof i==="string"&&s>t.maximum?Fr(i):s)<=t.maximum)return;let c=Br(i);r.issues.push({origin:c,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Eh=E("$ZodCheckMinLength",(e,t)=>{var n;pe.init(e,t),(n=e._zod.def).when??(n.when=Gr),e._zod.check=(r)=>{let i=r.value,s=i.length;if((typeof i==="string"&&s>=t.minimum&&s<t.minimum*2?Fr(i):s)>=t.minimum)return;let c=Br(i);r.issues.push({origin:c,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ah=E("$ZodCheckLengthEquals",(e,t)=>{var n;pe.init(e,t),(n=e._zod.def).when??(n.when=Gr),e._zod.check=(r)=>{let i=r.value,s=i.length,o=typeof i==="string"&&s>=t.length&&s<=t.length*2?Fr(i):s;if(o===t.length)return;let c=Br(i),l=o>t.length;r.issues.push({origin:c,...l?{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(pe.init(e,t),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=()=>{})}),Oh=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})}}),Nh=E("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=_h),On.init(e,t)}),Ih=E("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=kh),On.init(e,t)}),Ch=E("$ZodCheckIncludes",(e,t)=>{pe.init(e,t);let n=ft(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=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})}}),Ph=E("$ZodCheckStartsWith",(e,t)=>{pe.init(e,t);let n=new RegExp(`^${ft(t.prefix)}.*`);t.pattern??(t.pattern=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})}}),Rh=E("$ZodCheckEndsWith",(e,t)=>{pe.init(e,t);let n=new RegExp(`.*${ft(t.suffix)}$`);t.pattern??(t.pattern=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})}}),Mh=E("$ZodCheckOverwrite",(e,t)=>{pe.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Go{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
170
|
+
`).filter((s)=>s),r=Math.min(...n.map((s)=>s.length-s.trimStart().length)),i=n.map((s)=>s.slice(r)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
171
|
+
${t.join(`
|
|
172
|
+
`)}
|
|
173
|
+
};`)(...Object.values(this.closed))}}var Lh={major:4,minor:6,patch:7},q=E("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Lh;let r=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let s of i)for(let o of s._zod.onattach)o(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(c,l,a)=>{if(c.memo)return c;let d=De(c),f;for(let h of l){if(h._zod.def.when){if(yf(c))continue;if(!h._zod.def.when(c))continue}else if(d)continue;let u=c.issues.length,p=h._zod.check(c);if(p instanceof Promise&&a?.async===!1)throw new Be;if(f||p instanceof Promise)f=(f??Promise.resolve()).then(async()=>{if(await p,c.issues.length===u)return;if(wr(c.issues,u,e),!d)d=De(c,u)});else{if(c.issues.length===u)continue;if(wr(c.issues,u,e),!d)d=De(c,u)}}if(f)return f.then(()=>c);return c},o=(c,l,a)=>{if(De(c))return c.aborted=!0,c;let d=s(l,i,a);if(d instanceof Promise){if(a.async===!1)throw new Be;return d.then((f)=>e._zod.parse(f,a))}return e._zod.parse(d,a)};e._zod.run=(c,l)=>{if(l.skipChecks)return e._zod.parse(c,l);if(l.direction==="backward"){let d=e._zod.parse({value:c.value,issues:[]},{...l,skipChecks:!0});if(d instanceof Promise)return d.then((f)=>o(f,c,l));return o(d,c,l)}let a=e._zod.parse(c,l);if(a instanceof Promise){if(l.async===!1)throw new Be;return a.then((d)=>s(d,i,l))}return s(a,i,l)}}},{get "~standard"(){return Ko(this,"~standard",Xo(this))},set "~standard"(e){qe(this,"~standard",e)}}),Yo=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>Ke(n,t,Me()))}:{value:e.value};async function xh(e,t){let n={async:!0};return Yo(await e._zod.run({value:t,issues:[]},n),n)}function Xo(e){return{validate:(t)=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Yo(r,n)}catch(r){}return xh(e,t)},vendor:"zod",version:1}}var Yr=E("$ZodString",(e,t)=>{q.init(e,t),e._zod.pattern=t.pattern??wh,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=E("$ZodStringFormat",(e,t)=>{On.init(e,t),Yr.init(e,t)}),Dh=E("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=nh),W.init(e,t)}),jh=E("$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=ps(r))}else t.pattern??(t.pattern=ps());W.init(e,t)}),Uh=E("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=rh),W.init(e,t)}),Qo=1,on=2;function ea(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function zh(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return ea(e)||on;return Fh(e,t)}function Fh(e,t){if(!t.normalize&&t.protocol?.source===fh.source&&!/^https?:\/\//i.test(e))return Qo;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??on}return new URL(e)}catch{return on}}var Bh=/[\t\n\r]/g;function ms(e){return e.replace(Bh,"")}function Kh(e,t){return t.lastIndex=0,t.test(e.hostname)}function qh(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var Wh=E("$ZodURL",(e,t)=>{W.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim(),i=zh(r,t);if(i===Qo){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(i===on){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=ms(r);return}if(t.hostname&&!Kh(i,t.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&&!qh(i,t.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort});n.value=t.normalize?i.href:ms(r);return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Zh=E("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=sh()),W.init(e,t)}),Jh=E("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Qf:eh(t.length)),W.init(e,t)}),Hh=E("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Hf),W.init(e,t)}),Vh=E("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Vf),W.init(e,t)}),Gh=E("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Gf),W.init(e,t)}),Yh=E("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Yf),W.init(e,t)}),Xh=E("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Xf),W.init(e,t)}),Qh=E("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=yh(t)),W.init(e,t)}),ep=E("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=mh),W.init(e,t)}),tp=E("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=gh(t)),W.init(e,t)}),np=E("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=th),W.init(e,t)}),rp=E("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=oh),W.init(e,t)}),ip=/^[0-9a-fA-F:.]+$/;function ta(e){if(!ip.test(e))return!1;return ea(`http://[${e}]`)}var sp=E("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ah),W.init(e,t),e._zod.check=(n)=>{if(!ta(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),op=E("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ch),W.init(e,t)});function ap(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);if(`${i}`!==r)return!1;if(i<0||i>128)return!1;return ta(n)}var cp=E("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lh),W.init(e,t),e._zod.check=(n)=>{if(!ap(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function na(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 ra=/^[0-9a-zA-Z+/]*={0,2}$/,lp=E("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ra),W.init(e,t),e._zod.check=(n)=>{if(na(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Xr=/^[A-Za-z0-9_-]*$/;function up(e){if(!Xr.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return na(n)}var dp=E("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Xr),W.init(e,t),e._zod.check=(n)=>{if(up(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),fp=E("$ZodE164",(e,t)=>{t.pattern??(t.pattern=hh),W.init(e,t)});function hp(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 pp=E("$ZodJWT",(e,t)=>{W.init(e,t),e._zod.check=(n)=>{if(hp(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),ia=E("$ZodNumber",(e,t)=>{q.init(e,t),e._zod.pattern=Vr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(o){}let i=n.value;if(typeof i==="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let s=typeof i==="number"?Number.isNaN(i)?"NaN":!Number.isFinite(i)?String(i):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),n}}),mp=E("$ZodNumberFormat",(e,t)=>{$h.init(e,t),ia.init(e,t)}),gp=E("$ZodBoolean",(e,t)=>{q.init(e,t),e._zod.pattern=bh,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(s){}let i=n.value;if(typeof i==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),yp=E("$ZodUnknown",(e,t)=>{q.init(e,t),e._zod.parse=(n)=>n}),wp=E("$ZodNever",(e,t)=>{q.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function vp(e,t){let n=us(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map((s)=>s[0])),i=e._zod.parse;e._zod.parse=(s,o)=>{let c=t(s.value);if(c>r&&!o?.skipChecks&&o?.direction!=="backward"){for(let[l,a]of us(e._zod.def.checks))if(c>l&&a._zod.def.when(s)){let d=s.issues.length;return a._zod.check(s),s.issues[d].continue=!1,wr(s.issues,d,e),s}}return i(s,o)}}var bp=(e)=>Array.isArray(e)?e.length:-1;function gs(e,t,n){if(e.issues.length)t.issues.push(...lt(n,e.issues));t.value[n]=e.value}var _p=E("$ZodArray",(e,t)=>{q.init(e,t);let n=Ce.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),r;r.value=n?n.alloc(e,r,Array(s.length),i):Array(s.length);let o=[],c=i?.abortEarly;for(let l=0;l<s.length;l++){let a=s[l],d=t.element._zod.run({value:a,issues:[]},i);if(d instanceof Promise)o.push(d.then((f)=>gs(f,r,l)));else if(gs(d,r,l),c&&d.issues.length!==0&&De(d))break}if(o.length)return Promise.all(o).then(()=>r);return r},vp(e,bp)});function an(e,t,n,r,i,s){let o=n in r,c=s==="optional";if(!o&&c&&i==="optional")return;if(e.issues.length){if(i!==void 0&&c&&!o)return;t.issues.push(...lt(n,e.issues))}if(!o&&i===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(o||i==="defaulted"&&!c)t.value[n]=void 0}else t.value[n]=e.value}var kp=[];function sa(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:kp,i=r.length?[...t,...r]:t;for(let o of i)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(o)}": expected a Zod schema`);let s=lf(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function oa(e,t,n,r,i,s,o){let c=[],l=i.keySet,a=i.catchall._zod,d=a.def.type,{optin:f,optout:h}=a,u=0;for(let p in t){if(o&&n.issues.length!==u){if(De(n,u))break;u=n.issues.length}if(l.has(p))continue;if(p==="__proto__"){if(d==="never")c.push(p);continue}if(d==="never"){c.push(p);continue}let m=a.run({value:t[p],issues:[]},r);if(m instanceof Promise)e.push(m.then((g)=>an(g,n,p,t,f,h)));else an(m,n,p,t,f,h)}if(c.length)n.issues.push({code:"unrecognized_keys",keys:c,input:t,inst:s,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}var Sp=E("$ZodObject",(e,t)=>{q.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let a=()=>{let d={...r};return Object.defineProperty(t,"shape",{value:d}),a.raw=d,d};a.raw=r,Object.defineProperty(t,"shape",{get:a})}let i=jr(()=>sa(t));U(e,"propValues",(a)=>{let d=a.def.shape,f={};for(let h in d){let u=d[h]._zod;if(u.values){if(!Object.prototype.hasOwnProperty.call(f,h))Ze(f,h,new Set);for(let p of u.values)f[h].add(p);if(u.optin!==void 0)f[h].add(void 0)}}return f});let s=rn,o=t.catchall,c,l=Ce.memoizer;l?.attach(e),e._zod.parse=(a,d)=>{c??(c=i.value);let f=a.value;if(!s(f))return a.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),a;a.value=l?l.alloc(e,a,{},d):{};let h=[],u=c.shape,p=d?.abortEarly,m=a.issues.length;for(let g of c.allKeys){if(p&&a.issues.length!==m){if(De(a,m))break;m=a.issues.length}if(g==="__proto__")continue;let y=u[g],w=y._zod.optin,v=y._zod.optout,T=y._zod.run({value:f[g],issues:[]},d);if(T instanceof Promise)h.push(T.then((b)=>an(b,a,g,f,w,v)));else an(T,a,g,f,w,v)}if(!o)return h.length?Promise.all(h).then(()=>a):a;return oa(h,f,a,d,i.value,e,p===!0)}}),$p=E("$ZodObjectJIT",(e,t)=>{Sp.init(e,t);let n=e._zod.parse,r=jr(()=>sa(t)),i=Ce.memoizer,s=(u)=>{let p=r.value,m=p.symbolKeys,g=new Go(["payload","ctx"],{shape:u,inst:e,memo:i,syms:m}),y=(b)=>`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`,w=(b,k)=>`
|
|
174
|
+
let ${b}_ab = false;
|
|
175
|
+
for (let i = 0; i < ${b}.issues.length; i++) {
|
|
176
|
+
const iss = ${b}.issues[i];
|
|
177
|
+
iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
|
|
178
|
+
payload.issues.push(iss);
|
|
179
|
+
if (iss.continue !== true) ${b}_ab = true;
|
|
180
|
+
}
|
|
181
|
+
if (${b}_ab && ctx && ctx.abortEarly) {
|
|
182
|
+
payload.value = newResult;
|
|
183
|
+
return payload;
|
|
184
|
+
}`;g.write("const input = payload.value;");let v=Object.create(null),T=0;for(let b of p.allKeys)v[b]=`key_${T++}`;g.write(i?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let b of p.allKeys){if(b==="__proto__")continue;let k=v[b],A=typeof b==="symbol"?`syms[${m.indexOf(b)}]`:sf(b),N=`${A} in input`,I=u[b],O=I?._zod?.optin,R=O!==void 0,x=I?._zod?.optout==="optional";if(g.write(`const ${k} = ${y(A)};`),R&&x){let F=O==="optional"?`${k}_present`:`${k}.value !== undefined || ${k}_present`;g.write(`
|
|
185
|
+
const ${k}_present = ${N};
|
|
186
|
+
if (!${k}.issues.length || ${k}_present) {
|
|
187
|
+
if (${k}.issues.length) {${w(k,A)}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (${F}) {
|
|
191
|
+
newResult[${A}] = ${k}.value;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
`)}else if(!R)g.write(`
|
|
196
|
+
const ${k}_present = ${N};
|
|
197
|
+
if (${k}.issues.length) {${w(k,A)}
|
|
198
|
+
}
|
|
199
|
+
if (!${k}_present && !${k}.issues.length) {
|
|
200
|
+
payload.issues.push({
|
|
201
|
+
code: "invalid_type",
|
|
202
|
+
expected: "nonoptional",
|
|
203
|
+
input: undefined,
|
|
204
|
+
path: [${A}]
|
|
205
|
+
});
|
|
206
|
+
if (ctx && ctx.abortEarly) {
|
|
207
|
+
payload.value = newResult;
|
|
208
|
+
return payload;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (${k}_present) {
|
|
213
|
+
newResult[${A}] = ${k}.value;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
`);else if(g.write(`
|
|
217
|
+
if (${k}.issues.length) {${w(k,A)}
|
|
218
|
+
}
|
|
219
|
+
`),O==="defaulted")g.write(`newResult[${A}] = ${k}.value;`);else g.write(`
|
|
220
|
+
if (${k}.value !== undefined || ${N}) {
|
|
221
|
+
newResult[${A}] = ${k}.value;
|
|
222
|
+
}
|
|
223
|
+
`)}return g.write("payload.value = newResult;"),g.write("return payload;"),g.compile()},o,c=rn,l=!Ce.jitless,d=l&&af.value,f=t.catchall,h;e._zod.parse=(u,p)=>{h??(h=r.value);let m=u.value;if(!c(m))return u.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),u;if(l&&d&&p?.async===!1&&p.jitless!==!0){if(!o)o=s(t.shape);if(u=o(u,p),!f)return u;return oa([],m,u,p,h,e,p?.abortEarly===!0)}return n(u,p)}});function ys(e,t,n,r){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let i=e.filter((s)=>!De(s));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((s)=>s.issues.map((o)=>Ke(o,r,Me())))}),t}var Tp=E("$ZodUnion",(e,t)=>{q.init(e,t),U(e,"optin",(r)=>r.def.options.some((i)=>i._zod.optin==="defaulted")?"defaulted":r.def.options.some((i)=>i._zod.optin!==void 0)?"optional":void 0),U(e,"optout",(r)=>r.def.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),U(e,"values",(r)=>{if(r.def.options.every((i)=>i._zod.values))return new Set(r.def.options.flatMap((i)=>Array.from(i._zod.values)));return}),U(e,"pattern",(r)=>{if(r.def.options.every((i)=>i._zod.pattern)){let i=r.def.options.map((s)=>s._zod.pattern);return new RegExp(`^(${i.map((s)=>Ur(s.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 s=!1,o=[];for(let c of t.options){let l=c._zod.run({value:r.value,issues:[]},i);if(l instanceof Promise)o.push(l),s=!0;else{if(l.issues.length===0)return l;o.push(l)}}if(!s)return ys(o,r,e,i);return Promise.all(o).then((c)=>ys(c,r,e,i))}}),Ep=E("$ZodIntersection",(e,t)=>{q.init(e,t),e._zod.parse=(n,r)=>{let i=n.value,s=t.left._zod.run({value:i,issues:[]},r),o=t.right._zod.run({value:i,issues:[]},r);if(s instanceof Promise||o instanceof Promise)return Promise.all([s,o]).then(([l,a])=>ws(n,l,a));return ws(n,s,o)}});function br(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(dt(e)&&dt(t)){let n=Object.keys(t),r=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),i={...e,...t};if(Object.prototype.hasOwnProperty.call(i,"__proto__"))delete i.__proto__;for(let s of r){if(s==="__proto__")continue;let o=br(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.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],s=t[r],o=br(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ws(e,t,n){let r=new Map,i,s=new Map,o=(a,d)=>{let f;if(a.code==="unrecognized_keys"&&!a.path?.length)i??(i=a),f=a.keys;else if(a.code==="invalid_key"&&a.origin==="record"&&a.path?.length===1){let h=String(a.path[0]);if(!s.has(h))s.set(h,a);f=[h]}else return!1;for(let h of f){if(!r.has(h))r.set(h,{});r.get(h)[d]=!0}return!0};for(let a of t.issues)if(!o(a,"l"))e.issues.push(a);for(let a of n.issues)if(!o(a,"r"))e.issues.push(a);let c=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(c.length){let a=i?c.filter((d)=>i.keys.includes(d)):[];if(a.length)e.issues.push({...i,keys:a});for(let d of c)if(!a.includes(d)&&s.has(d))e.issues.push(s.get(d))}let l=br(t.value,n.value);if(!l.valid){if(De(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`)}return e.value=l.data,e}var Ap=E("$ZodRecord",(e,t)=>{q.init(e,t);let n=Ce.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let s=r.value;if(!dt(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),r;let o=[],c=t.keyType._zod.values;if(c&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let l=new Set;for(let d of c)if(typeof d==="string"||typeof d==="number"||typeof d==="symbol"){if(l.add(typeof d==="number"?d.toString():d),d==="__proto__")continue;let f=t.keyType._zod.run({value:d,issues:[]},i);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map((p)=>Ke(p,i,Me())),input:d,path:[d],inst:e});continue}let h=f.value;if(h==="__proto__")continue;let u=t.valueType._zod.run({value:s[d],issues:[]},i);if(u instanceof Promise)o.push(u.then((p)=>{if(p.issues.length)r.issues.push(...lt(d,p.issues));r.value[h]=p.value}));else{if(u.issues.length)r.issues.push(...lt(d,u.issues));r.value[h]=u.value}}let a;for(let d in s)if(!l.has(d))if(t.mode==="loose"){if(d==="__proto__")continue;r.value[d]=s[d]}else a=a??[],a.push(d);if(a&&a.length>0)r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:a,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let l;for(let a of Reflect.ownKeys(s)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(s,a))continue;let d=t.keyType._zod.run({value:a,issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&Vr.test(a)&&d.issues.length){let p=t.keyType._zod.run({value:Number(a),issues:[]},i);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length===0)d=p}if(d.issues.length){if(t.mode==="loose")r.value[a]=s[a];else if(c)l=l??[],l.push(a);else r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((p)=>Ke(p,i,Me())),input:a,path:[a],inst:e});continue}let h=d.value;if(h==="__proto__")continue;let u=t.valueType._zod.run({value:s[a],issues:[]},i);if(u instanceof Promise)o.push(u.then((p)=>{if(p.issues.length)r.issues.push(...lt(a,p.issues));r.value[h]=p.value}));else{if(u.issues.length)r.issues.push(...lt(a,u.issues));r.value[h]=u.value}}if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:l,continue:!0})}if(o.length)return Promise.all(o).then(()=>r);return r}}),Op=E("$ZodEnum",(e,t)=>{q.init(e,t);let n=gr(t.entries),r=new Set(n);e._zod.values=r,U(e,"pattern",(i)=>{let s=gr(i.def.entries).filter((o)=>cf.has(typeof o));return new RegExp(s.length?`^(${s.map((o)=>ft(o.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(i,s)=>{let o=i.value;if(r.has(o))return i;return i.issues.push({code:"invalid_value",values:n,input:o,inst:e}),i}}),Np=E("$ZodLiteral",(e,t)=>{q.init(e,t);let n=new Set(t.values);e._zod.values=n,U(e,"pattern",(r)=>{let i=r.def.values;return new RegExp(i.length?`^(${i.map((s)=>typeof s==="string"?ft(s):s?ft(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,i)=>{let s=r.value;if(n.has(s))return r;return r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}}),Ip=E("$ZodTransform",(e,t)=>{q.init(e,t),e._zod.optin="optional",Ce.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Kr(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then((o)=>(n.value=o,n));if(i instanceof Promise)throw new Be;return n.value=i,n}});function vs(e,t){return e.value=t.issues.length?void 0:t.value,e}var aa=E("$ZodOptional",(e,t)=>{q.init(e,t),U(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",U(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),U(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Ur(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let i=t.innerType._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)return i.then((s)=>vs(n,s));return vs(n,i)}return t.innerType._zod.run(n,r)}}),Cp=E("$ZodExactOptional",(e,t)=>{aa.init(e,t),U(e,"values",(n)=>n.def.innerType._zod.values),U(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),Pp=E("$ZodNullable",(e,t)=>{q.init(e,t),U(e,"optin",(n)=>n.def.innerType._zod.optin),U(e,"optout",(n)=>n.def.innerType._zod.optout),U(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Ur(r.source)}|null)$`):void 0}),U(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),Rp=E("$ZodDefault",(e,t)=>{q.init(e,t),e._zod.optin="defaulted",U(e,"values",(n)=>n.def.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((s)=>bs(s,t));return bs(i,t)}});function bs(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Mp=E("$ZodPrefault",(e,t)=>{q.init(e,t),e._zod.optin="defaulted",U(e,"values",(n)=>n.def.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)}}),Lp=E("$ZodNonOptional",(e,t)=>{q.init(e,t),U(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter((i)=>i!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((s)=>_s(s,e));return _s(i,e)}});function _s(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}function ks(e,t,n,r){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((i)=>Ke(i,r,Me()))},input:e.value}),e}var xp=E("$ZodCatch",(e,t)=>{q.init(e,t),U(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),U(e,"optout",(n)=>n.def.innerType._zod.optout),U(e,"values",(n)=>n.def.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({value:n.value,issues:[]},r);if(i instanceof Promise)return i.then((s)=>ks(n,s,t,r));return ks(n,i,t,r)}}),Dp=E("$ZodPipe",(e,t)=>{q.init(e,t),U(e,"values",(n)=>n.def.in._zod.values),U(e,"optin",(n)=>n.def.in._zod.optin),U(e,"optout",(n)=>n.def.out._zod.optout),U(e,"propValues",(n)=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=t.out._zod.run(n,r);if(s instanceof Promise)return s.then((o)=>Wt(o,t.in,r));return Wt(s,t.in,r)}let i=t.in._zod.run(n,r);if(i instanceof Promise)return i.then((s)=>Wt(s,t.out,r));return Wt(i,t.out,r)}});function Wt(e,t,n){if(e.issues.some((r)=>r.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var jp=E("$ZodReadonly",(e,t)=>{q.init(e,t),U(e,"propValues",(n)=>n.def.innerType._zod.propValues),U(e,"values",(n)=>n.def.innerType._zod.values),U(e,"optin",(n)=>n.def.innerType?._zod?.optin),U(e,"optout",(n)=>n.def.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(Ss);return Ss(i)}});function Ss(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var Up=E("$ZodLazy",(e,t)=>{q.init(e,t),nf(e._zod,"innerType",()=>{let n=t;if(!n._cachedInner)n._cachedInner=t.getter();return n._cachedInner}),U(e,"pattern",(n)=>n.innerType?._zod?.pattern),U(e,"propValues",(n)=>n.innerType?._zod?.propValues),U(e,"optin",(n)=>n.innerType?._zod?.optin??void 0),U(e,"optout",(n)=>n.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),zp=E("$ZodCustom",(e,t)=>{pe.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((s)=>$s(s,n,r,e));$s(i,n,r,e);return}});function $s(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(Ct(i))}}class ca extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var _r="~memo",Es=[];function la(e){return e!==null&&typeof e==="object"}function ar(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var ua=new WeakMap,Et=0,tn=1,Nt=2;function nn(e,t,n){let r=ua.get(e);if(r!==void 0)return r?Nt:Et;if(t.has(e))return Nt;t.add(e);let i=Et,s=(d)=>{if(i!==Nt&&d?._zod){let f=nn(d,t,n);if(f>i)i=f}},o=(d,f)=>{let h=Et;for(let u of Reflect.ownKeys(d)){let p=Object.getOwnPropertyDescriptor(d,u);if(f&&!p.enumerable)continue;let m=p.get?tn:p.value?._zod?nn(p.value,t,n):Et;if(m>h)h=m}return h},c=(d)=>{if(d>i)i=d},l=e._zod.def;switch(l.type){case"object":{let d=Lo(l);c(d?o(d,!0):tn),s(l.catchall);break}case"array":s(l.element);break;case"tuple":for(let d of l.items)s(d);s(l.rest);break;case"record":case"map":s(l.keyType),s(l.valueType);break;case"set":s(l.valueType);break;case"union":for(let d of l.options)s(d);break;case"intersection":s(l.left),s(l.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(l.innerType);break;case"pipe":s(l.in),s(l.out);break;case"function":s(l.input),s(l.output);break;case"lazy":{let d=l._cachedInner??(n?e._zod.innerType:void 0);c(d?nn(d,t,!1):tn);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let d in l){let f=Object.getOwnPropertyDescriptor(l,d);if(!f||f.get)continue;let h=f.value;if(!h||typeof h!=="object")continue;if(h._zod)s(h);else if(Array.isArray(h))for(let u of h)s(u)}}return t.delete(e),Fp(e,i)}function Fp(e,t){if(t!==tn)ua.set(e,t===Nt);return t}function Bp(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var Zt,Jt=[],Kp={alloc(e,t,n){let r=Zt;if(!r)return n;Zt=void 0;let i={value:n,issues:null};return r.set(t.value,i),Jt.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(i,s)=>{if(s.direction!=="backward"&&Wp(s,i.value))throw new ca;return n(i,s)};if(e._zod.parse=r,e._zod.run===n)e._zod.run=r})},attach(e){var t;let n,r=!1,i,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let o=e._zod.parse,c=(l,a)=>{if(n===void 0){let y=nn(e,new Set,!1);if(y===Et){if(e._zod.parse=o,e._zod.run===c)e._zod.run=o;return o(l,a)}if(y===Nt||r)n=!0;else r=!0}let d=l.value;if(!la(d))return o(l,a);let f=a[_r];if(!f)f={buckets:new WeakMap,backEdges:void 0},a[_r]=f;let h;if(i===a)h=s;else h=Bp(f,e),i=a,s=h;let u=h.get(d);if(u){if(l.value=u.value,u.issues){if(u.issues.length)l.issues.push(...ar(u.issues))}else l.memo=!0,f.backEdges??(f.backEdges=new WeakSet),f.backEdges.add(u.value);return l}Zt=h;let p=Jt.length,m=o(l,a);Zt=void 0;let g=Jt.length>p?Jt.pop():void 0;if(m instanceof Promise)return m.then((y)=>{if(g)g.issues=y.issues.length?ar(y.issues):Es;return y});if(g)g.issues=m.issues.length?ar(m.issues):Es;return m};if(e._zod.parse=c,e._zod.run===o)e._zod.run=c})}};function qp(){return Kp}function Wp(e,t){let n=e[_r]?.backEdges;return n!==void 0&&la(t)&&n.has(t)}var Zp=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(s){return e[s]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function i(s,o){if(s==="number"&&typeof o==="number"&&!Number.isFinite(o))return String(o);return r[s]??s}return(s)=>{switch(s.code){case"invalid_type":{let o=i(s.expected),c=vf(s.input),l=i(c,s.input);return`Invalid input: expected ${o}, received ${l}`}case"invalid_value":if(s.values.length===1)return`Invalid input: expected ${zo(s.values[0])}`;return`Invalid option: expected one of ${as(s.values,"|")}`;case"too_big":{let o=s.exact?"exactly ":s.inclusive?"<=":"<",c=t(s.origin);if(c)return`Too big: expected ${s.origin??"value"} to have ${o}${s.maximum.toString()} ${c.unit??"elements"}`;return`Too big: expected ${s.origin??"value"} to be ${o}${s.maximum.toString()}`}case"too_small":{let o=s.exact?"exactly ":s.inclusive?">=":">",c=t(s.origin);if(c)return`Too small: expected ${s.origin} to have ${o}${s.minimum.toString()} ${c.unit}`;return`Too small: expected ${s.origin} to be ${o}${s.minimum.toString()}`}case"invalid_format":{let o=s;if(o.format==="starts_with")return`Invalid string: must start with "${o.prefix}"`;if(o.format==="ends_with")return`Invalid string: must end with "${o.suffix}"`;if(o.format==="includes")return`Invalid string: must include "${o.includes}"`;if(o.format==="regex")return`Invalid string: must match pattern ${o.pattern}`;return`Invalid ${n[o.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${as(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":if(s.options&&Array.isArray(s.options)&&s.options.length>0)return`Invalid discriminator value. Expected ${s.options.map((c)=>`'${c}'`).join(" | ")}`;if(s.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function Jp(){return{localeError:Zp()}}var As;class da{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 Hp(){return new da}(As=globalThis).__zod_globalRegistry??(As.__zod_globalRegistry=Hp());var At=globalThis.__zod_globalRegistry;function fa(e){if(e.checks)e.checks=[...e.checks];return e}function Vp(e,t){return new e(fa({type:"string",...M(t)}))}function Gp(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function Yp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function Xp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function Qp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function em(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function tm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function nm(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function rm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function im(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function sm(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function om(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function am(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function cm(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function lm(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function um(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function dm(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function fm(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function hm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function pm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function mm(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function gm(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function ym(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}function wm(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function vm(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function bm(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function _m(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function km(e,t){return new e(fa({type:"number",checks:[],...M(t)}))}function Sm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function $m(e,t){return new e({type:"boolean",...M(t)})}function Tm(e){return new e({type:"unknown"})}function Em(e,t){return new e({type:"never",...M(t)})}function Is(e,t){return new Ho({check:"less_than",...M(t),value:e,inclusive:!1})}function cr(e,t){return new Ho({check:"less_than",...M(t),value:e,inclusive:!0})}function Cs(e,t){return new Vo({check:"greater_than",...M(t),value:e,inclusive:!1})}function lr(e,t){return new Vo({check:"greater_than",...M(t),value:e,inclusive:!0})}function Ps(e,t){return new Sh({check:"multiple_of",...M(t),value:e})}function ha(e,t){return new Th({check:"max_length",...M(t),maximum:e})}function cn(e,t){return new Eh({check:"min_length",...M(t),minimum:e})}function pa(e,t){return new Ah({check:"length_equals",...M(t),length:e})}function Am(e,t){return new Oh({check:"string_format",format:"regex",...M(t),pattern:e})}function Om(e){return new Nh({check:"string_format",format:"lowercase",...M(e)})}function Nm(e){return new Ih({check:"string_format",format:"uppercase",...M(e)})}function Im(e,t){return new Ch({check:"string_format",format:"includes",...M(t),includes:e})}function Cm(e,t){return new Ph({check:"string_format",format:"starts_with",...M(t),prefix:e})}function Pm(e,t){return new Rh({check:"string_format",format:"ends_with",...M(t),suffix:e})}function wt(e){return new Mh({check:"overwrite",tx:e})}function Rm(e){return wt((t)=>t.normalize(e))}function Mm(){return wt((e)=>e.trim())}function Lm(){return wt((e)=>e.toLowerCase())}function xm(){return wt((e)=>e.toUpperCase())}function Dm(){return wt((e)=>of(e))}function jm(e,t,n){return new e({type:"array",element:t,...M(n)})}function Um(e,t,n){return new e({type:"custom",check:"custom",fn:t,...M(n)})}function zm(e,t){let n=Fm((r)=>(r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(Ct(i,r.value,n._zod.def));else{let s=i;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=r.value;s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(Ct(s))}},e(r.value,r)),t);return n}function Fm(e,t){let n=new pe({check:"custom",...M(t)});return n._zod.check=e,n}function It(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))Ze(e,r,n[r]);return e}function ma(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??At,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function We(e,t,n,r,i){let s=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw Error(i);return Object.assign(n,s),!0}function ee(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,n.schemaPath.includes(e))s.cycle=n.path;return s.schema}let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let c=e._zod.toJSONSchema?.();if(c)o.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,d);else{let h=o.schema,u=t.processors[i.type];if(!u)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);u(e,t,h,d)}let f=e._zod.parent;if(f){if(!o.ref)o.ref=f;ee(f,t,d),t.seen.get(f).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)It(o.schema,l);if(t.io==="input"&&ue(e))delete o.schema.examples,delete o.schema.default;if(t.io==="input"&&"_prefault"in o.schema)(r=o.schema).default??(r.default=o.schema._prefault);return delete o.schema._prefault,t.seen.get(e).schema}function Rs(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ga(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let o of e.seen.entries()){let c=e.metadataRegistry.get(o[0])?.id;if(c){let l=r.get(c);if(l&&l!==o[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,o[0])}}let i=(o)=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(o[0])?.id,h=e.external.uri??((p)=>p);if(f)return{ref:h(f)};let u=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=u,{defId:u,ref:`${h("__shared")}#/${c}/${Rs(u)}`}}let l="#",a=`${l}/${c}/`;if(o[1]===n&&!o[1].schema.id)return{ref:l};let d=o[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:a+Rs(d)}},s=(o)=>{if(o[1].schema.$ref)return;let c=o[1],{ref:l,defId:a}=i(o);if(c.def={...c.schema},a)c.defId=a;let d=c.schema;for(let f in d)delete d[f];d.$ref=l};if(e.cycles==="throw")for(let o of e.seen.entries()){let c=o[1];if(c.cycle)throw Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
224
|
+
|
|
225
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of e.seen.entries()){let c=o[1];if(t===o[0]){s(o);continue}if(e.external){let a=e.external.registry.get(o[0])?.id;if(t!==o[0]&&a){s(o);continue}}if(e.metadataRegistry.get(o[0])?.id){s(o);continue}if(c.cycle){s(o);continue}if(c.count>1){if(e.reused==="ref")s(o)}}if(e.external)e.sharedDefsExtractedFor=e.external}function ya(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;ya(r);let i=Object.keys(r);if(i.length!==1||i[0]!=="type")return;let s=r.type;for(let o of Array.isArray(s)?s:[s]){if(typeof o!=="string")return;if(!n.includes(o))n.push(o)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var wa=new Set(["type","properties","required","additionalProperties"]),Ls=["oneOf","anyOf"];function xs(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function kr(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let o in s)if(!wa.has(o))return null;t.push(s)}let n={},r=new Set;for(let s of t){for(let o in s.properties){if(Object.prototype.hasOwnProperty.call(n,o))continue;let c=[];for(let a of t){let d=a.properties?.[o]??xs(a);if(d===null||d===void 0)continue;if(!c.some((f)=>JSON.stringify(f)===JSON.stringify(d)))c.push(d)}let l=c.length===1?c[0]:kr(c)??{allOf:c};Ze(n,o,l)}for(let o of s.required??[])r.add(o)}let i={type:"object",properties:n};if(r.size)i.required=[...r];if(t.every((s)=>s.additionalProperties===!1))i.additionalProperties=!1;else{let s=[];for(let o of t){let c=xs(o);if(c&&!s.some((l)=>JSON.stringify(l)===JSON.stringify(c)))s.push(c)}if(s.length===1)i.additionalProperties=s[0];else if(s.length>1)i.additionalProperties={allOf:s}}return i}function Bm(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let i of wa)if(i in e)return;let n=t.filter((i)=>Ls.some((s)=>Array.isArray(i[s]))),r=null;if(!n.length)r=kr(t);else{let i=n[0],s=Ls.find((l)=>Array.isArray(i[l]));if(Object.keys(i).length!==1)return;let o=t.filter((l)=>l!==i),c=i[s].map((l)=>kr([...o,l]));if(c.some((l)=>!l))return;r={[s]:c}}if(!r)return;delete e.allOf,It(e,r)}function va(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,d={...a},f=l.ref;if(l.ref=null,f){r(f);let u=e.seen.get(f),p=u.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))a.allOf=a.allOf??[],a.allOf.push(p);else It(a,p);if(It(a,d),c._zod.parent===f)for(let g in a){if(g==="$ref"||g==="allOf")continue;if(!(g in d))delete a[g]}if(p.$ref&&u.def)for(let g in a){if(g==="$ref"||g==="allOf")continue;if(g in u.def&&JSON.stringify(a[g])===JSON.stringify(u.def[g]))delete a[g]}}let h=c._zod.parent;if(h&&h!==f){r(h);let u=e.seen.get(h);if(u?.schema.$ref){if(a.$ref=u.schema.$ref,u.def)for(let p in a){if(p==="$ref"||p==="allOf")continue;if(p in u.def&&JSON.stringify(a[p])===JSON.stringify(u.def[p]))delete a[p]}}}e.override({zodSchema:c,jsonSchema:a,path:l.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let c of[...e.seen.entries()].reverse())r(c[0]);if(e.target!=="openapi-3.0")for(let c of e.seen.entries())ya(c[1].def??c[1].schema);for(let c of e.deferred)c();if(e.intersections.length){let c=new Map;for(let l of e.seen.values())for(let a of[l.schema,l.def]){let d=a?.allOf;if(!Array.isArray(d))continue;let f=c.get(d);if(f)f.push(a);else c.set(d,[a])}for(let l of e.intersections)for(let a of c.get(l)??[])Bm(a)}}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)}It(i,n.defId?n.schema:n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&i.id===s)delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)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;Ze(o,l.defId,l.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(o).length>0)if(e.target==="draft-2020-12")i.$defs=o;else i.definitions=o;try{let c=JSON.parse(JSON.stringify(i));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:ln(t,"input",e.processors),output:ln(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch(c){throw Error("Error converting schema to JSON.")}}function ue(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 ue(r.element,n);if(r.type==="set")return ue(r.valueType,n);if(r.type==="lazy")return ue(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"||r.type==="catch")return ue(r.innerType,n);if(r.type==="intersection")return ue(r.left,n)||ue(r.right,n);if(r.type==="record"||r.type==="map")return ue(r.keyType,n)||ue(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return ue(r.in,n)||ue(r.out,n)}if(r.type==="object"){for(let i in r.shape)if(ue(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(ue(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(ue(i,n))return!0;if(r.rest&&ue(r.rest,n))return!0;return!1}return!1}var Km=(e,t={})=>(n)=>{let r=ma({...n,processors:t});return ee(e,r),ga(r,e),va(r,e)},ln=(e,t,n={})=>(r)=>{let{libraryOptions:i,target:s}=r??{},o=ma({...i??{},target:s,io:t,processors:n});return ee(e,o),ga(o,e),va(o,e)},pt=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},mt=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},Ds=(e,t)=>{pt(e,"minimum",t),mt(e,"maximum",t)},ba=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},_a=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},ka=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},Sa=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},js=(e,t)=>pt(e,"minimum",t.minimum),Us=(e,t)=>mt(e,"maximum",t.maximum),zs=(e)=>(t,n)=>{Sa(t,n.format);let[r,i]=e[n.format];pt(t,"minimum",r),mt(t,"maximum",i)},qm={greater_than:(e,t)=>pt(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>mt(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>ba(e,t.value),number_format:zs(Fo),bigint_format:zs(uf),min_length:js,max_length:Us,length_equals:(e,t)=>Ds(e,t.length),min_size:js,max_size:Us,size_equals:(e,t)=>Ds(e,t.size),string_format:(e,t)=>{if(Sa(e,t.format),t.pattern)_a(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>ka(e,t.mime)};function Ne(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let s of r)qm[s._zod.def.check]?.(t,s._zod.def);let i=e._zod.bag;if(i.minimum!==void 0)pt(t,"minimum",i.minimum);if(i.exclusiveMinimum!==void 0)pt(t,"exclusiveMinimum",i.exclusiveMinimum);if(i.maximum!==void 0)mt(t,"maximum",i.maximum);if(i.exclusiveMaximum!==void 0)mt(t,"exclusiveMaximum",i.exclusiveMaximum);if(i.multipleOf!==void 0)ba(t,i.multipleOf);if(i.format!==void 0){if(t.format??(t.format=i.format),i.format.includes("int"))t.isInt=!0}if(i.mime)ka(t,i.mime);for(let s of i.patterns??[])_a(t,s);return t}var Wm={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Zm=new Map([[ra,uh],[Xr,dh]]),$a=(e)=>Zm.get(e)??e,Jm=(e,t,n,r)=>{let i=n;i.type="string";let{minimum:s,maximum:o,format:c,patterns:l,contentEncoding:a,laxFormat:d}=Ne(e);if(typeof s==="number")i.minLength=s;if(typeof o==="number")i.maxLength=o;if(c){if(i.format=Wm[c]??c,i.format==="")delete i.format;if(c==="time"||d)delete i.format}if(a)i.contentEncoding=a;if(l&&l.size>0){let f=[...l].map($a);if(f.length===1)i.pattern=f[0].source;else if(f.length>1)i.allOf=[...f.map((h)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))]}},Hm=(e,t,n,r)=>{let i=n,{minimum:s,maximum:o,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:a,isInt:d}=Ne(e);i.type=d?"integer":"number";let f=typeof a==="number"&&a>=(s??Number.NEGATIVE_INFINITY),h=typeof l==="number"&&l<=(o??Number.POSITIVE_INFINITY),u=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(u)i.minimum=a,i.exclusiveMinimum=!0;else i.exclusiveMinimum=a;else if(typeof s==="number")i.minimum=s;if(h)if(u)i.maximum=l,i.exclusiveMaximum=!0;else i.exclusiveMaximum=l;else if(typeof o==="number")i.maximum=o;if(c){let p=new Set;for(let y of c)if(Number.isFinite(y)&&y!==0)p.add(Math.abs(y));else We(e,t,i,r,`A multipleOf divisor of ${y} cannot be represented in JSON Schema`);let[m,...g]=p;if(m!==void 0)i.multipleOf=m;if(g.length)i.allOf=[...i.allOf??[],...g.map((y)=>({multipleOf:y}))]}},Vm=(e,t,n,r)=>{n.type="boolean"},Gm=(e,t,n,r)=>{n.not={}},Ym=(e,t,n,r)=>{},Xm=(e,t,n,r)=>{let i=e._zod.def,s=gr(i.entries);if(s.length===0){n.not={};return}if(s.every((o)=>typeof o==="number"))n.type="number";if(s.every((o)=>typeof o==="string"))n.type="string";n.enum=s},Qm=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let s=[];for(let o of i.values)if(o===void 0){if(We(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==="bigint"){if(We(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(o))}else s.push(o);if(s.length===0);else if(s.length===1){let o=s[0];if(n.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[o];else n.const=o}else{if(s.every((o)=>typeof o==="number"))n.type="number";if(s.every((o)=>typeof o==="string"))n.type="string";if(s.every((o)=>typeof o==="boolean"))n.type="boolean";if(s.every((o)=>o===null))n.type="null";n.enum=s}},eg=(e,t,n,r)=>{We(e,t,n,r,"Custom types cannot be represented in JSON Schema")},tg=(e,t,n,r)=>{We(e,t,n,r,"Transforms cannot be represented in JSON Schema")},ng=(e,t,n,r)=>{let i=n,s=e._zod.def,{minimum:o,maximum:c}=Ne(e);if(typeof o==="number")i.minItems=o;if(typeof c==="number")i.maxItems=c;i.type="array",i.items=ee(s.element,t,{...r,path:[...r.path,"items"]})};function un(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return un(t.out);if(t.type==="catch")return un(t.innerType);return e._zod.optin}var rg=(e,t,n,r)=>{let i=n,s=e._zod.def,o=s.shape;if(Object.getOwnPropertySymbols(o).length&&We(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let a in o)Ze(i.properties,a,ee(o[a],t,{...r,path:[...r.path,"properties",a]}));let l=[];for(let a of Object.keys(o)){let d=s.shape[a];if(t.io==="input"?un(d)===void 0:d._zod.optout===void 0)l.push(a)}if(l.length>0)i.required=l;if(s.catchall?._zod.def.type==="never")i.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")i.additionalProperties=!1}else if(s.catchall)i.additionalProperties=ee(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},ig=(e,t,n,r)=>{let i=e._zod.def,s=i.inclusive===!1,o=i.options.map((c,l)=>ee(c,t,{...r,path:[...r.path,s?"oneOf":"anyOf",l]}));if(s)n.oneOf=o;else n.anyOf=o},sg=(e,t,n,r)=>{let i=e._zod.def,s=ee(i.left,t,{...r,path:[...r.path,"allOf",0]}),o=ee(i.right,t,{...r,path:[...r.path,"allOf",1]}),c=(a)=>("allOf"in a)&&Object.keys(a).length===1,l=[...c(s)?s.allOf:[s],...c(o)?o.allOf:[o]];n.allOf=l,t.intersections.push(l)};function Sr(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let p=e.get(t)?.def;if(!p)return t;let m=Sr(e,p,n);return m===p?t:m}for(let p of["anyOf","oneOf"]){let m=t[p];if(!Array.isArray(m))continue;let g=m.map((y)=>Sr(e,y,n));if(g.some((y,w)=>y!==m[w]))t={...t,[p]:g}}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes("string")&&r.some((p)=>p==="number"||p==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!i&&!s?.some((p)=>typeof p==="number"))return t;let{minimum:o,maximum:c,exclusiveMinimum:l,exclusiveMaximum:a,multipleOf:d,format:f,id:h,...u}=t;if(u.enum)u.enum=u.enum.map((p)=>typeof p==="number"?String(p):p);else if(typeof u.const==="number")u.const=String(u.const);if(!i)return u;if(u.type="string",!s)u.pattern=(r.includes("number")?Vr:vh).source;return u}var Tr=new WeakMap;function og(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of Tr.get(e)??[]){let i=e.seen.get(r),s=(i?.def??i?.schema)?.propertyNames;if(!s||s===!0||n.has(s))continue;let o=Sr(t,s,new Set);if(o!==s)n.set(s,o)}if(!n.size)return;for(let r of e.seen.values())for(let i of[r.schema,r.def]){let s=i&&n.get(i.propertyNames);if(s)i.propertyNames=s}}var ag=(e,t,n,r)=>{let i=n,s=e._zod.def;i.type="object";let o=s.keyType,c=Ne(o).patterns;if(s.mode==="loose"&&c&&c.size>0){let d=ee(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let f of c)Ze(i.patternProperties,$a(f).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){i.propertyNames=ee(s.keyType,t,{...r,path:[...r.path,"propertyNames"]});let d=Tr.get(t);if(!d)d=[],Tr.set(t,d),t.deferred.push(()=>og(t));d.push(e)}i.additionalProperties=ee(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let l=o._zod.values,a=t.io==="input"&&un(s.valueType)!==void 0;if(l&&!s.partial&&!a){let d=[...l].filter((f)=>typeof f==="string"||typeof f==="number");if(d.length>0)i.required=d.map(String)}},cg=(e,t,n,r)=>{let i=e._zod.def,s=ee(i.innerType,t,r),o=t.seen.get(e);if(t.target==="openapi-3.0")o.ref=i.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},lg=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let s=t.seen.get(e);s.ref=i.innerType},ei=Symbol();function Ta(e,t,n,r,i){let s=!1,o=JSON.stringify(e,(c,l)=>{if(typeof l!=="bigint")return l;return s=!0,null});if(!s)return JSON.parse(o);return We(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),ei}var ug=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let s=t.seen.get(e);s.ref=i.innerType;let o=Ta(i.defaultValue,e,t,n,r);if(o!==ei)n.default=o},dg=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let s=t.seen.get(e);if(s.ref=i.innerType,t.io!=="input")return;let o=Ta(i.defaultValue,e,t,n,r);if(o!==ei)n._prefault=o},fg=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let s=t.seen.get(e);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{We(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=o},hg=(e,t,n,r)=>{let i=e._zod.def,s=i.in._zod.traits.has("$ZodTransform"),o=t.io==="input"?s?i.out:i.in:i.out;ee(o,t,r);let c=t.seen.get(e);c.ref=o},pg=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let s=t.seen.get(e);s.ref=i.innerType,n.readOnly=!0},Ea=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let s=t.seen.get(e);s.ref=i.innerType},mg=(e,t,n,r)=>{let i=e._zod.innerType;ee(i,t,r);let s=t.seen.get(e);s.ref=i},Fs=new WeakSet([Object.prototype,Error.prototype]);function Ht(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var gg=(e,t)=>{Cf.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Fs.has(n))return;Fs.add(n),Ht(n,"format",(r)=>(i)=>Mf(r,i)),Ht(n,"flatten",(r)=>(i)=>Rf(r,i)),Ht(n,"addIssue",(r)=>(i)=>{r.issues.push(i),r.message=JSON.stringify(r.issues,yr,2)}),Ht(n,"addIssues",(r)=>(i)=>{r.issues.push(...i),r.message=JSON.stringify(r.issues,yr,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})},$e=E("ZodError",gg,void 0,{Parent:Error}),yg=qr($e),wg=Wr($e),vg=Zr($e),bg=Hr($e),_g=zf($e),kg=Ff($e),Sg=Bf($e),$g=Kf($e),Tg=qf($e),Eg=Wf($e),Ag=Zf($e),Og=Jf($e);function Ng(){if(!Ce.localeError)Me(Jp())}function Nn(){if(!Ce.memoizer)Me({memoizer:qp()})}var Z=E("ZodType",(e,t)=>(Ng(),q.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(we(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Je(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Ay(e,t))},superRefine(e,t){return this.check(Oy(e,t))},overwrite(e){return this.check(wt(e))},optional(){return qs(this)},exactOptional(){return fy(this)},nullable(){return Ws(this)},nullish(){return qs(Ws(this))},nonoptional(e){return wy(this,e)},array(){return K(this)},or(e){return xt([this,e])},and(e){return cy(this,e)},transform(e){return Zs(this,dy(e))},default(e){return my(this,e)},prefault(e){return yy(this,e)},catch(e){return by(this,e)},pipe(e){return Zs(this,e)},readonly(){return Sy(this)},describe(e){let t=this.clone();return At.add(t,{description:e}),t},meta(...e){if(e.length===0)return At.get(this);let t=this.clone();return At.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return Ko(this,"~standard",{...Xo(this),jsonSchema:{input:ln(this,"input"),output:ln(this,"output")}})},set "~standard"(e){qe(this,"~standard",e)},parse:function e(t,n){return yg(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await wg(this,t,n,{callee:e})},safeParse(e,t){return vg(this,e,t)},async safeParseAsync(e,t){return bg(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){qe(this,"spa",e)},validate(e,t){return Df(this,e,t)},validateAsync(e,t){return Uf(this,e,t)},encode:function e(t,n){return _g(this,t,n,{callee:e})},decode:function e(t,n){return kg(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Sg(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await $g(this,t,n,{callee:e})},safeEncode(e,t){return Tg(this,e,t)},safeDecode(e,t){return Eg(this,e,t)},async safeEncodeAsync(e,t){return Ag(this,e,t)},async safeDecodeAsync(e,t){return Og(this,e,t)},toJSONSchema(e){return Km(this,{})(e)},get description(){return At.get(this)?.description},get _def(){return this._zod.def}}),Aa=E("_ZodString",(e,t)=>{Yr.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Jm(e,n,r,i)},qo({format:(e)=>Ne(e).format??null,minLength:(e)=>Ne(e).minimum??null,maxLength:(e)=>Ne(e).maximum??null},{regex(...e){return this.check(Am(...e))},includes(...e){return this.check(Im(...e))},startsWith(...e){return this.check(Cm(...e))},endsWith(...e){return this.check(Pm(...e))},min(...e){return this.check(cn(...e))},max(...e){return this.check(ha(...e))},length(...e){return this.check(pa(...e))},nonempty(...e){return this.check(cn(1,...e))},lowercase(e){return this.check(Om(e))},uppercase(e){return this.check(Nm(e))},trim(){return this.check(Mm())},normalize(...e){return this.check(Rm(...e))},toLowerCase(){return this.check(Lm())},toUpperCase(){return this.check(xm())},slugify(){return this.check(Dm())}})),Ig=E("ZodString",(e,t)=>{Yr.init(e,t),Aa.init(e,t)},{email(e){return this.check(Gp(Lg,e))},url(e){return this.check(nm(Dg,e))},jwt(e){return this.check(ym(Xg,e))},emoji(e){return this.check(rm(jg,e))},guid(e){return this.check(Yp(xg,e))},uuid(e){return this.check(Xp(Gt,e))},uuidv4(e){return this.check(Qp(Gt,e))},uuidv6(e){return this.check(em(Gt,e))},uuidv7(e){return this.check(tm(Gt,e))},nanoid(e){return this.check(im(Ug,e))},cuid(e){return this.check(sm(zg,e))},cuid2(e){return this.check(om(Fg,e))},ulid(e){return this.check(am(Bg,e))},base64(e){return this.check(pm(Vg,e))},base64url(e){return this.check(mm(Gg,e))},xid(e){return this.check(cm(Kg,e))},ksuid(e){return this.check(lm(qg,e))},ipv4(e){return this.check(um(Wg,e))},ipv6(e){return this.check(dm(Zg,e))},cidrv4(e){return this.check(fm(Jg,e))},cidrv6(e){return this.check(hm(Hg,e))},e164(e){return this.check(gm(Yg,e))},datetime(e){return this.check(wm(Cg,e))},date(e){return this.check(vm(Pg,e))},time(e){return this.check(bm(Rg,e))},duration(e){return this.check(_m(Mg,e))}});function P(e){return Vp(Ig,e)}var G=E("ZodStringFormat",(e,t)=>{W.init(e,t),Aa.init(e,t)}),Cg=E("ZodISODateTime",(e,t)=>{Qh.init(e,t),G.init(e,t)}),Pg=E("ZodISODate",(e,t)=>{ep.init(e,t),G.init(e,t)}),Rg=E("ZodISOTime",(e,t)=>{tp.init(e,t),G.init(e,t)}),Mg=E("ZodISODuration",(e,t)=>{np.init(e,t),G.init(e,t)}),Lg=E("ZodEmail",(e,t)=>{Uh.init(e,t),G.init(e,t)}),xg=E("ZodGUID",(e,t)=>{Dh.init(e,t),G.init(e,t)}),Gt=E("ZodUUID",(e,t)=>{jh.init(e,t),G.init(e,t)}),Dg=E("ZodURL",(e,t)=>{Wh.init(e,t),G.init(e,t)}),jg=E("ZodEmoji",(e,t)=>{Zh.init(e,t),G.init(e,t)}),Ug=E("ZodNanoID",(e,t)=>{Jh.init(e,t),G.init(e,t)}),zg=E("ZodCUID",(e,t)=>{Hh.init(e,t),G.init(e,t)}),Fg=E("ZodCUID2",(e,t)=>{Vh.init(e,t),G.init(e,t)}),Bg=E("ZodULID",(e,t)=>{Gh.init(e,t),G.init(e,t)}),Kg=E("ZodXID",(e,t)=>{Yh.init(e,t),G.init(e,t)}),qg=E("ZodKSUID",(e,t)=>{Xh.init(e,t),G.init(e,t)}),Wg=E("ZodIPv4",(e,t)=>{rp.init(e,t),G.init(e,t)}),Zg=E("ZodIPv6",(e,t)=>{sp.init(e,t),G.init(e,t)}),Jg=E("ZodCIDRv4",(e,t)=>{op.init(e,t),G.init(e,t)}),Hg=E("ZodCIDRv6",(e,t)=>{cp.init(e,t),G.init(e,t)}),Vg=E("ZodBase64",(e,t)=>{lp.init(e,t),G.init(e,t)}),Gg=E("ZodBase64URL",(e,t)=>{dp.init(e,t),G.init(e,t)}),Yg=E("ZodE164",(e,t)=>{fp.init(e,t),G.init(e,t)}),Xg=E("ZodJWT",(e,t)=>{pp.init(e,t),G.init(e,t)}),Oa=E("ZodNumber",(e,t)=>{ia.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Hm(e,n,r,i),e.isFinite=!0},qo({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=Ne(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=Ne(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=Ne(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>Ne(e).format??null},{gt(e,t){return this.check(Cs(e,t))},gte(e,t){return this.check(lr(e,t))},min(e,t){return this.check(lr(e,t))},lt(e,t){return this.check(Is(e,t))},lte(e,t){return this.check(cr(e,t))},max(e,t){return this.check(cr(e,t))},int(e){return this.check(Bs(e))},safe(e){return this.check(Bs(e))},positive(e){return this.check(Cs(0,e))},nonnegative(e){return this.check(lr(0,e))},negative(e){return this.check(Is(0,e))},nonpositive(e){return this.check(cr(0,e))},multipleOf(e,t){return this.check(Ps(e,t))},step(e,t){return this.check(Ps(e,t))},finite(){return this}}));function L(e){return km(Oa,e)}var Qg=E("ZodNumberFormat",(e,t)=>{mp.init(e,t),Oa.init(e,t)});function Bs(e){return Sm(Qg,e)}var ey=E("ZodBoolean",(e,t)=>{gp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Vm(e,n,r,i)});function oe(e){return $m(ey,e)}var ty=E("ZodUnknown",(e,t)=>{yp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ym(e,n,r,i)});function et(){return Tm(ty)}var ny=E("ZodNever",(e,t)=>{wp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Gm(e,n,r,i)});function ry(e){return Em(ny,e)}var iy=E("ZodArray",(e,t)=>{Nn(),_p.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ng(e,n,r,i),e.element=t.element},{min(e,t){return this.check(cn(e,t))},nonempty(e){return this.check(cn(1,e))},max(e,t){return this.check(ha(e,t))},length(e,t){return this.check(pa(e,t))},unwrap(){return this.element}});function K(e,t){return jm(iy,e,t)}var sy=E("ZodObject",(e,t)=>{Nn(),$p.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>rg(e,n,r,i),$f(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return Q(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(we(this._zod.def,{catchall:e}))},passthrough(){return this.clone(we(this._zod.def,{catchall:et()}))},loose(){return this.clone(we(this._zod.def,{catchall:et()}))},strict(){return this.clone(we(this._zod.def,{catchall:ry()}))},strip(){return this.clone(we(this._zod.def,{catchall:void 0}))},extend(e){return hf(this,e)},safeExtend(e){return pf(this,e)},merge(e){return mf(this,e)},pick(e){return df(this,e)},omit(e){return ff(this,e)},partial(...e){return ls(Na,this,e[0])},exactPartial(...e){return ls(Ia,this,e[0],"exactPartial")},required(...e){return gf(Ca,this,e[0])}});function D(e,t){let n={type:"object",shape:e??{},...M(t)};return new sy(n)}var oy=E("ZodUnion",(e,t)=>{Tp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ig(e,n,r,i),e.options=t.options});function xt(e,t){return new oy({type:"union",options:e,...M(t)})}var ay=E("ZodIntersection",(e,t)=>{Ep.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>sg(e,n,r,i)});function cy(e,t){return new ay({type:"intersection",left:e,right:t})}var Ks=E("ZodRecord",(e,t)=>{Nn(),Ap.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ag(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function Se(e,t,n){if(!t||!t._zod)return new Ks({type:"record",keyType:P(),valueType:e,...M(t)});return new Ks({type:"record",keyType:e,valueType:t,...M(n)})}var Er=E("ZodEnum",(e,t)=>{Op.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,i,s)=>Xm(e,r,i,s),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{let s={};for(let o of r)if(n.has(o))s[o]=t.entries[o];else throw Error(`Key ${o} not found in enum`);return new Er({...t,checks:[],...M(i),entries:s})},e.exclude=(r,i)=>{let s={...t.entries};for(let o of r)if(n.has(o))delete s[o];else throw Error(`Key ${o} not found in enum`);return new Er({...t,checks:[],...M(i),entries:s})}});function Q(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new Er({type:"enum",entries:n,...M(t)})}var ly=E("ZodLiteral",(e,t)=>{Np.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Qm(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 dn(e,t){return new ly({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}var uy=E("ZodTransform",(e,t)=>{Nn(),Ip.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>tg(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Kr(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(Ct(s,n.value,t));else{let o=s;if(o.fatal)o.continue=!1;if(o.code??(o.code="custom"),!("input"in o))o.input=n.value;o.inst??(o.inst=e),n.issues.push(Ct(o))}};let i=t.transform(n.value,n);if(i instanceof Promise)return i.then((s)=>(n.value=s,n));return n.value=i,n}});function dy(e){return new uy({type:"transform",transform:e})}var Na=E("ZodOptional",(e,t)=>{aa.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ea(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function qs(e){return new Na({type:"optional",innerType:e})}var Ia=E("ZodExactOptional",(e,t)=>{Cp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ea(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function fy(e){return new Ia({type:"optional",innerType:e})}var hy=E("ZodNullable",(e,t)=>{Pp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>cg(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Ws(e){return new hy({type:"nullable",innerType:e})}var py=E("ZodDefault",(e,t)=>{Rp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ug(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function my(e,t){return new py({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Uo(t)}})}var gy=E("ZodPrefault",(e,t)=>{Mp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>dg(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function yy(e,t){return new gy({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Uo(t)}})}var Ca=E("ZodNonOptional",(e,t)=>{Lp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>lg(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function wy(e,t){return new Ca({type:"nonoptional",innerType:e,...M(t)})}var vy=E("ZodCatch",(e,t)=>{xp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>fg(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function by(e,t){return new vy({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Ef(t)})}var _y=E("ZodPipe",(e,t)=>{Dp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hg(e,n,r,i),e.in=t.in,e.out=t.out});function Zs(e,t){return new _y({type:"pipe",in:e,out:t})}var ky=E("ZodReadonly",(e,t)=>{jp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pg(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Sy(e){return new ky({type:"readonly",innerType:e})}var $y=E("ZodLazy",(e,t)=>{Up.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mg(e,n,r,i),e.unwrap=()=>e._zod.def.getter()});function Ty(e){return new $y({type:"lazy",getter:e})}var Ey=E("ZodCustom",(e,t)=>{zp.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>eg(e,n,r,i)});function Ay(e,t={}){return Um(Ey,e,t)}function Oy(e,t){return zm(e,t)}var Ny=Oo(),Iy=Sn(),Cy=So(),ti=$n(),Py=yn(),He=z(),Ry=nt(),My=se(),Ly=rt(),xy=it(),l$=Lr(),Dy=No(),jy=Io(),Uy=Co(),In=Rd(),Pa=gn(),u$=Ny.Composer,d$=Iy.Document,f$=Cy.Schema,{YAMLError:h$,YAMLParseError:p$,YAMLWarning:m$}=ti,g$=Py.Alias,{isAlias:y$,isCollection:w$,isDocument:v$,isMap:b$,isNode:_$,isPair:k$,isScalar:S$,isSeq:$$}=He,T$=Ry.Pair,E$=My.Scalar,A$=Ly.YAMLMap,O$=xy.YAMLSeq,N$=Dy.Lexer,I$=jy.LineCounter,C$=Uy.Parser,{parse:P$,parseAllDocuments:R$,parseDocument:M$,stringify:L$}=In,{visit:x$,visitAsync:D$}=Pa,B$=`${xr.slug}_`,K$=new RegExp("[\\u0000-\\u001f\\u007f]");function Zy(e,t=""){let n="",r=0;for(;;){let i=e.indexOf("<!--",r);if(i===-1)break;let s=e.indexOf("-->",i+4);if(s===-1)break;n+=e.slice(r,i)+t,r=s+3}return n+e.slice(r)}var Jy=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,Hy=/\n{3,}/g;function Vy(e){let t=Jy.exec(e);return t===null||t===void 0?e:e.slice(t[0].length)}function Gy(e){return Zy(e).replace(Hy,`
|
|
226
|
+
|
|
227
|
+
`).trim()}var Yt={static:2000,volatile:3500,reminder:500,total:6000},ve=P().min(1),Yy=D({delimiters:Q(["xml","markdown","plain"]).optional(),intensity:Q(["emphatic","neutral","soft"]).optional(),examplesIn:Q(["system","user"]).optional(),skillsIn:Q(["system","user"]).optional()}).strict(),Xy=D({nativeTools:oe().optional(),strictSchema:oe().optional(),thinking:Q(["none","anthropic","openai","deepseek"]).optional(),promptCache:Q(["none","anthropic","openai","bedrock"]).optional(),parallelToolCalls:oe().optional(),contextWindow:L().int().positive().optional(),maxOutput:L().int().positive().optional(),vision:oe().optional(),promptStyle:Yy.optional()}).strict(),Vs="chat-completions",Ma=D({id:P().min(1),api:P().min(1).optional(),options:Se(P(),et()).optional(),baseUrl:P().min(1).optional(),apiKeyEnv:P().min(1).optional(),temperature:L().min(0).max(2).optional(),topP:L().min(0).max(1).optional(),maxTokens:L().int().positive().optional(),reasoningEffort:Q(["none","minimal","low","medium","high","xhigh","max"]).optional(),headers:Se(P(),P()).optional(),streamUsage:oe().optional(),capabilities:Xy.optional()}).strict();function La(e,t){if((e.api??Vs)===Vs&&e.baseUrl===void 0)t.addIssue({code:"custom",path:["baseUrl"],message:"baseUrl is required for the chat-completions transport"})}var Qy=Ma.superRefine(La),Xt=Ma.extend({fallbacks:K(Qy).min(1).optional()}).superRefine(La),ew=D({main:Xt,selector:Xt.optional(),compactor:Xt.optional()}).catchall(Xt),tw=D({snip:L().default(0.6),micro:L().default(0.7),collapse:L().default(0.8),reset:L().default(0.88),trim:L().default(0.95)}).strict(),nw=D({static:L().int().positive().default(Yt.static),volatile:L().int().positive().default(Yt.volatile),reminder:L().int().positive().default(Yt.reminder),total:L().int().positive().default(Yt.total)}).strict(),rw=D({perRuleSuccess:L().gt(0).lte(1).default(0.9),reliabilityTarget:L().gt(0).lt(1).default(0.8),onExceed:Q(["fail","warn"]).default("fail")}).strict(),iw=D({file:P().min(1),requires:D({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(),sw=D({dir:P().min(1),maxActive:L().int().nonnegative().default(2),budget:L().int().positive().default(600)}).strict(),ow=D({window:L().int().positive().optional(),reserveOutput:L().int().positive().default(4096),observationMaxTokens:L().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:nw.prefault({}),rules:rw.prefault({}),soul:iw.optional(),compactionNotice:oe().optional(),thresholds:tw.prefault({})}).strict(),aw=D({max:L().int().positive().default(24),reserveWrite:L().int().nonnegative().default(6)}).strict(),cw=D({onMutate:Q(["refuse","confirm","allow"]).default("refuse")}).strict(),lw=D({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(),uw=D({dialect:Q(["nlt","native"]).default("nlt"),providers:Se(ve,Se(P(),et())).default({}),provider:ve.optional(),providerConfig:Se(P(),et()).default({}),budget:aw.prefault({}),pinned:K(P().min(1)).default([]),search:D({enabled:oe().default(!1)}).strict().prefault({}),local:K(P().min(1)).default([]),untrusted:cw.prefault({}),policy:lw.prefault({}),eventDetail:Q(["none","redacted"]).default("none")}).strict(),dw=D({allow:K(P().min(1)),entry:oe().optional()}).strict(),fw=D({dir:P().min(1).default("./skills"),maxActive:L().int().nonnegative().default(1),threshold:L().default(0.35),trusted:K(P().min(1)).optional()}).strict(),hw=D({retriever:P().min(1).default("fts5"),dir:P().min(1).default("./memory"),maxActive:L().int().nonnegative().default(5),threshold:L().default(0.2),budget:L().int().positive().default(2000),includeHistory:oe().default(!0),shared:oe().default(!0)}).strict(),pw=["owner","peer","channel-peer"],mw=D({scope:Q(pw).default("channel-peer")}).strict(),gw=D({type:ve,id:ve,allowFrom:K(P().min(1)).optional(),enabled:oe().default(!0),role:ve.optional()}).passthrough(),xa=D({channel:ve,to:P().min(1)}).strict(),yw=D({default:ve.optional(),reply:Q(["all","final"]).default("all"),targets:Se(P(),xa).default({})}).strict(),fn=Ty(()=>D({type:Q(["string","number","integer","boolean","array","object"]),description:P().optional(),enum:K(xt([P(),L(),oe()])).optional(),items:fn.optional(),properties:Se(P(),fn).optional(),required:K(P()).optional()})),Da=D({id:ve,manifest:P().min(1),task:P().min(1),artifact:D({type:dn("object"),properties:Se(P(),fn),required:K(P()).optional()}).strict()}).strict(),ww=D({members:K(Da).min(1)}).strict(),vw=D({name:ve,task:P().min(1),tools:K(P().min(1)).min(1),route:D({tools:K(P().min(1)).min(1)}).strict().optional(),spawn:oe().default(!1),artifact:Da.shape.artifact.optional(),model:P().min(1).optional(),maxSteps:L().int().positive().optional(),timeoutMs:L().int().positive().optional()}).strict(),ur={provider:P().min(1),model:P().min(1).optional(),baseUrl:P().min(1).optional(),apiKeyEnv:P().min(1).optional(),options:Se(P(),et()).optional()},bw=D({transcription:D({...ur,timeoutMs:L().int().positive().default(60000),maxBytes:L().int().positive().default(26214400)}).strict().optional(),speech:D({...ur,timeoutMs:L().int().positive().default(60000),maxCharacters:L().int().positive().default(3000)}).strict().optional(),image:D({...ur,timeoutMs:L().int().positive().default(120000),size:P().regex(/^[0-9]+x[0-9]+$/).default("1024x1024")}).strict().optional()}).strict(),_w=D({enabled:oe().default(!1),escalateAfterMs:L().int().nonnegative().default(0)}).strict(),kw=D({offer:D({task:P().min(1),artifact:D({type:dn("object"),properties:Se(P(),fn),required:K(P()).optional()}).strict()}).strict().optional(),to:xt([dn("*"),K(ve).min(1)]).optional(),ask:oe().default(!1)}).strict(),Sw=D({id:ve,kind:Q(["cron","every","at"]),expr:P().min(1),task:P().min(1),deliver:xt([dn("none"),xa]),session:P().min(1).default("isolated"),role:ve.optional(),tools:D({allow:K(P().min(1)).min(1)}).strict().optional(),timeoutMs:L().int().positive().optional(),maxSteps:L().int().positive().optional(),enabled:oe().default(!0),timezone:P().min(1).optional()}).strict(),$w=xt([P().min(1),D({spec:P().min(1),config:Se(P(),et()).default({})}).strict()]),Tw=D({identicalCalls:L().int().min(2).default(3),sameTool:L().int().min(2).optional()}).strict(),Ew=D({maxSteps:L().int().positive().default(40),noProgress:Tw.prefault({}),turnTimeoutMs:L().int().positive().default(1800000),toolTimeoutMs:L().int().positive().default(120000),maxParallelTools:L().int().positive().default(4),maxConcurrentTurns:L().int().positive().optional(),reloadHoldMs:L().int().nonnegative().default(30000),maxHops:L().int().nonnegative().default(4),tokens:D({max:L().int().positive(),windowMs:L().int().positive()}).strict().optional()}).strict(),Aw=D({enabled:oe().default(!1),port:L().int().min(1).max(65535).default(7420),host:P().min(1).default("127.0.0.1"),tokenEnv:P().min(1).default(`${xr.envPrefix}API_TOKEN`),allowedOrigins:K(P().min(1)).default([]),allowedHosts:K(P().min(1)).default([])}).strict(),q$=D({apiVersion:P().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:P().min(1).optional(),description:P().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:P().min(1).optional(),model:ew,context:ow.prefault({}),tools:uw.prefault({}),phases:Se(P(),dw).optional(),skills:fw.optional(),knowledge:sw.optional(),memory:hw.optional(),sessions:mw.optional(),channels:K(gw).default([]),delivery:yw.optional(),schedules:K(Sw).default([]),team:ww.optional(),subagents:K(vw).optional(),media:bw.optional(),standIn:_w.optional(),delegation:kw.optional(),plugins:K($w).default([]),limits:Ew.prefault({}),server:Aw.prefault({})}).strict(),Ow={nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096},dr={nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,maxOutput:5000},fr={vision:!0,nativeTools:!0,strictSchema:!1,thinking:"anthropic",promptCache:"none",parallelToolCalls:!0},hr="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`).",W$=[{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:{...fr,contextWindow:1e6,maxOutput:128000},note:hr})),{pattern:"claude-haiku-*",family:!0,capabilities:{...fr,contextWindow:200000,maxOutput:64000},note:hr},{pattern:"claude-*",family:!0,capabilities:{...fr,contextWindow:200000,maxOutput:8192},note:hr},{pattern:"nova-micro*",capabilities:{...dr,contextWindow:128000}},{pattern:"nova-lite*",capabilities:{...dr,contextWindow:300000,vision:!0}},{pattern:"nova-pro*",capabilities:{...dr,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:Ow}];var Nw=/^(?:[-*+]|\d+[.)])[ \t]+\S/,Iw=/\*\*(\d{4})-(\d{2})-\d{2}T/;function Cw(e){let t=[],n=-1,r=(i)=>{if(n===-1)return;t.push({start:n,end:i,text:e.slice(n,i).join(`
|
|
228
|
+
`).trimEnd()}),n=-1};for(let i=0;i<e.length;i+=1){let s=e[i]??"";if(Nw.test(s)){r(i),n=i;continue}if(n===-1)continue;if(s.trim()===""||/^[ \t]/.test(s))continue;r(i)}return r(e.length),t}function Ar(e){return Yd(Gy(Vy(e)))}function Pw(e,t){let n=Iw.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 Rw(e,t){let n=e.split(/\r?\n/),r=Cw(n),i=[],s=r,o=e,c=Ar(o);while(c>t&&s.length>1){let l=s[0];if(l===void 0)break;i.push(l),s=s.slice(1),o=Mw(n,i),c=Ar(o)}if(c<=t)return{evict:i,remaining:o,tokens:c};return{evict:i,remaining:o,tokens:c,shortfall:s.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 Mw(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(`
|
|
229
|
+
`).replace(/\n{3,}/g,`
|
|
230
|
+
|
|
231
|
+
`)}async function Lw(e){let t=e.tags.length===0?"":` _(${e.tags.join(", ")})_`,n=`
|
|
232
|
+
- **${e.now.toISOString()}**${t} ${e.text}
|
|
233
|
+
`;return await Ra(e.path,n,"utf8"),await xw(e)}async function xw(e){let t=await Ky(e.path,"utf8"),n=Rw(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 s=Pw(i.text,e.now);r.set(s,[...r.get(s)??[],i.text])}await By(e.archiveDir,{recursive:!0});for(let[i,s]of r)await Ra(Wy(e.archiveDir,i),`${s.join(`
|
|
234
|
+
`)}
|
|
235
|
+
`,"utf8");return await qy(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",Gs="memory",Ys="notes.md",Dw={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`${jw(n,r)} (${r})`}};function jw(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=(s)=>n.find((o)=>o.type===s)?.value??"",i=r("timeZoneName").replace("GMT","");return`${r("year")}-${r("month")}-${r("day")}T${r("hour")}:${r("minute")}:${r("second")}${i===""?"Z":i}`}var Uw={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(),s=r.length===0?"":` _(${r.join(", ")})_`,o=`
|
|
236
|
+
- **${i}**${s} ${n}
|
|
237
|
+
`;if(t.writeNote!==void 0)return await t.writeNote(r.length===0?n:`${n} (${r.join(", ")})`);let c=await zw(n,r,o,t);if(t.shareNote===void 0)return c;return`${c} ${await t.shareNote(r.length===0?n:`${n} (${r.join(", ")})`)}`}};async function zw(e,t,n,r){let i=r.writeTarget;if(i?.mode==="refused")throw Kd(i.name,i.reason??"none");if(i?.path!==void 0){if(i.budget!==void 0&&r.memoryDir!==void 0&&i.eviction==="oldest"){let o=await Lw({path:i.path,name:i.name,budget:i.budget,archiveDir:r.memoryDir,text:e,tags:t,now:r.now()});if(o.shortfall!==void 0)return`Saved to ${o.file}, but it is still over budget: ${o.shortfall}. Ask the person to raise the budget or shorten the file — the agent will not load until they do.`;if(o.evicted===0)return`Saved to ${o.file}.`;return`Saved to ${o.file}. Moved ${o.evicted} older ${o.evicted===1?"note":"notes"} into ${o.archives.join(", ")}, still searchable.`}if(await Js(i.path,n,"utf8"),i.budget!==void 0){let o=Ar(await Fy(i.path,"utf8"))-i.budget;if(o>0)return`Saved to ${i.name}, which is now ${o} 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 s=Hs(r.dir,Gs);return await zy(s,{recursive:!0}),await Js(Hs(s,Ys),n,"utf8"),`Saved to ${Gs}/${Ys}.`}var Fw=1200,Bw=Fw*3,Kw={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 Zd();let i=await t.readArtifact(n);if(i===void 0)throw Jd(n);let s=i.slug===void 0?"observation":`${i.slug} observation`,o=i.content.slice(r,r+Bw),c=r+o.length,l=`Compacted ${s}, ${i.tokens} tokens${r===0?"":`, from character ${r}`}:`;if(c>=i.content.length)return`${l}
|
|
238
|
+
${o}`;return`${l}
|
|
239
|
+
${o}
|
|
240
|
+
|
|
241
|
+
[cut here — ${i.content.length-c} characters remain; continue with artifact_read(id, from: ${c})]`},trustOf:(e)=>Vd(typeof e.id==="string"?e.id.trim():"")},qw=30,Ww={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 qd();if(t.forgetMemory===void 0)throw Wd();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,qw),d=l.notes.length>a.length?`
|
|
242
|
+
${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(`
|
|
243
|
+
`)+d}let s=await t.forgetMemory({ids:r}),o=s.notes.length===0?`Nothing was deleted from ${i(s.scope)}.`:`Deleted ${s.notes.length} ${s.notes.length===1?"note":"notes"} from ${i(s.scope)}; they will not be recalled again.`,c=s.missing.length===0?"":` No note has ${s.missing.length===1?"the id":"the ids"} ${s.missing.join(", ")}: already gone, or not yours to delete here.`;return o+c}},Zw=[Dw,Uw,Ww,Kw],Z$=Zw.map((e)=>e.spec.slug);var ja=[{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}],J$=ja.filter((e)=>e.agentListed).map((e)=>e.path),H$=ja.filter((e)=>e.via===void 0&&!e.path.includes("<")&&!e.path.includes("[")).map((e)=>e.path);var V$=["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(`
|
|
244
|
+
`);var G$=(()=>{let e=Symbol.for(`${xr.slug}.liveRuntimes`),t=globalThis;return t[e]??=new Set,t[e]})();var Jw="id, session_key, turn_id, role, content, tool_calls, tool_call_id, origin, tainted, created_at",Y$=Jw.split(", ").map((e)=>`m.${e}`).join(", ");var X$=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(" ")),Qw=65536,ev=1000,eo=[1000,2000,5000,15000,30000,60000],tv=3,nv=512,Ua="3EB0A6E7C0DE";function rv(){return`${Ua}${Hw(14).toString("hex").toUpperCase()}`}function iv(e){return e.startsWith(Ua)}var to=60000,sv=180000,ov=3000,av=401,cv=515,lv={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 no(e){let t=e.authState?.creds;if(t===void 0)return!0;return t.registered===!0||t.account!==void 0&&t.account!==null}function so(){return typeof globalThis.Bun<"u"}class za{id;type="whatsapp";limits={maxMessageChars:Qw,idempotentSend:!1,attachments:!0,voiceNotes:!0,minSendIntervalMs:ev};alwaysAllow;#e;#n;#t;#r;#o;#s;#a;#i;#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??ov,this.#o=e.api}async start(e){if(this.#c)return;if(this.#c=!0,this.#a=e,so())e.error(lv);this.#w=this.#v(e)}async stop(){if(!this.#c)return;this.#c=!1;try{this.#i?.end()}catch{}this.#i=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.#i;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(oo(e.recipient),n===void 0?{text:e.text}:n.mimeType.startsWith("audio/")?{audio:await Qs(n.path),mimetype:"audio/ogg; codecs=opus",ptt:!0}:{image:await Qs(n.path),mimetype:n.mimeType,...e.text===""?{}:{caption:e.text}},{messageId:rv()}))?.key?.id;if(i!==void 0&&i!==null){if(this.#m.push(i),this.#m.length>nv)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.#i?.end()}catch{}this.#i=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.#i?.sendPresenceUpdate("composing",oo(e))}async#v(e){while(this.#c&&!this.#p){try{let n=this.#o??await pv();this.#s=n,Vw(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.#$(e,i),onCreds:()=>this.#A(),onMessages:(i)=>this.#T(e,i)});this.#i=r,this.#d=no(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 co(this.#E())}}async#k(e,t){let n=this.#n;if(n===void 0||n==="")return;if(no(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()+to).toISOString()});return}try{if(await co(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()+sv).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;#$(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()+to).toISOString()});return}if(t.connection==="open"){this.#f=0,this.#l=0;let n=this.#i?.user;if(this.#h.clear(),n?.id!==void 0)this.#h.add(pn(n.id));if(n?.lid!==void 0)this.#h.add(pn(n.lid));e.status("connected","paired");return}if(t.connection==="close"){let n=t.lastDisconnect?.error?.output?.statusCode;if(n===av)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>=tv)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:so()?"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===cv)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.#i=void 0,this.#y?.(),this.#y=void 0}}#T(e,t){if(t.type!=="notify")return;for(let n of t.messages){let r=dv(n,{ownJids:this.#h,sentIds:this.#m});if(r===void 0)continue;let i=fv(n),s=Fa(n),o=this.#s,c=async()=>{if(o?.download===void 0)throw Error("this Baileys build cannot download media");return o.download(n)};e.receive({...r,...i===void 0?{}:{audio:{...i,fetch:c}},...s===void 0?{}:{images:[{...s,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,eo.length-1);return eo[e]??1000}#_(){Yw(this.#e,{recursive:!0,force:!0})}#A(){try{Xs(this.#e,448);for(let e of Gw(this.#e))Xs(Xw(this.#e,e),384)}catch{}}}var uv={ownJids:new Set,sentIds:[]};function dv(e,t=uv){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)||iv(r)))return;let d=pn(n),f=e.key?.remoteJidAlt,h=f===null||f===void 0?void 0:pn(f);if(!(t.ownJids.has(d)||h!==void 0&&t.ownJids.has(h)))return}if(n.endsWith("@g.us")||n==="status@broadcast")return;let i=e.message,s=i?.conversation??i?.extendedTextMessage?.text??i?.imageMessage?.caption??i?.videoMessage?.caption??i?.documentMessage?.caption??"";if(s.trim()===""&&(i?.audioMessage??void 0)===void 0&&Fa(e)===void 0)return;let o=e.messageTimestamp,c=typeof o==="number"?o:typeof o?.toNumber==="function"?o.toNumber():void 0,l=hv(n,e.key?.remoteJidAlt),a=e.pushName;return{...r===null||r===void 0?{}:{providerMessageId:r},peerId:l,senderHandle:Ka(l),...a===null||a===void 0||a===""?{}:{senderName:a},text:s,receivedAt:new Date(c===void 0?Date.now():c*1000).toISOString()}}function fv(e){let t=e.message?.audioMessage;if(t===null||t===void 0)return;let n=Ba(t.fileLength);return{mimeType:t.mimetype??"audio/ogg",...typeof t.seconds==="number"?{durationS:t.seconds}:{},...n===void 0?{}:{sizeBytes:n}}}function Fa(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=Ba(r.fileLength);return i===void 0?{}:{sizeBytes:i}}function Ba(e){return typeof e==="number"?e:typeof e?.toNumber==="function"?e.toNumber():void 0}function hv(e,t){if(e.endsWith("@s.whatsapp.net"))return e;if(t?.endsWith("@s.whatsapp.net")===!0)return t;return e}function pn(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 Ka(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 oo(e){return e.includes("@")?e:`${Ka(e)}@s.whatsapp.net`}async function pv(){let e=await import("./index-abm0zyc0.js"),t=e.default,n=typeof t==="function"?t.default:void 0,r=typeof t==="function"?n??t:e.makeWASocket,i=e.useMultiFileAuthState??(typeof t==="function"?t.useMultiFileAuthState:void 0),s=e.downloadMediaMessage??(typeof t==="function"?t.downloadMediaMessage:void 0);if(typeof r!=="function"||typeof i!=="function")throw Error("the installed baileys package does not export makeWASocket and useMultiFileAuthState");return{...s===void 0?{}:{download:(o)=>s(o,"buffer",{})},connect:async({authDir:o,deviceName:c,onUpdate:l,onCreds:a,onMessages:d})=>{let{state:f,saveCreds:h}=await i(o),u=r({auth:f,printQRInTerminal:!1,browser:[c??"Ubuntu","Chrome","22.04.4"],logger:mv(),markOnlineOnConnect:!1});return u.ev.on("connection.update",l),u.ev.on("creds.update",async()=>{await h(),await a()}),u.ev.on("messages.upsert",d),u}}}function mv(){let e=()=>{},t={level:"silent",trace:e,debug:e,info:e,warn:e,error:e,fatal:e};return t.child=()=>t,t}function co(e){return new Promise((t)=>setTimeout(t,e))}var gv="./.whatsapp",ni=(e)=>{let t=pr(e.config,"authDir")??gv,n=Md(t)?t:Ld(e.dir,t),r=e.config.api,i=pr(e.config,"pairWith"),s=i===void 0?void 0:i.replace(/[^0-9]/g,"");if(i!==void 0&&!/^[0-9]{6,20}$/.test(s??""))throw new mr({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 o=pr(e.config,"deviceName");if(o!==void 0&&!/^[\x20-\x7e]{1,32}$/.test(o))throw new mr({code:"whatsapp_device_name_invalid",message:`Channel "${e.id}" has a deviceName outside 1-32 printable ASCII characters: "${o}".`,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 za({id:e.id,authDir:n,...s===void 0?{}:{pairWith:s},...o===void 0?{}:{deviceName:o},...typeof c==="number"?{pairingDelayMs:c}:{},...r===void 0?{}:{api:r}})};var yv="0.1.0",qa={name:"whatsapp",version:yv,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["web.whatsapp.com","*.whatsapp.net"]},{kind:"fs",paths:["<agent>/.whatsapp"],mode:"write"}],setup(e){e.defineChannel("whatsapp",ni)}};function pr(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}import{spawn as Hv}from"node:child_process";import{readFile as wv}from"node:fs/promises";class Pn 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 vv=new Set(["127.0.0.1","localhost","[::1]","169.254.170.2","169.254.170.23","[fd00:ec2::23]"]),bv=300000;function ii(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:"&&vv.has(r.hostname)))return;let i;return async()=>{if(i?.expiration!==void 0&&i.expiration.getTime()-Date.now()>bv)return i;let s=e.AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE,o=s!==void 0&&s!==""?(await wv(s,"utf8")).trim():e.AWS_CONTAINER_AUTHORIZATION_TOKEN,c=await t(r,{headers:o===void 0||o===""?{}:{authorization:o},signal:AbortSignal.timeout(5000)}),l=await c.text(),a={};try{let m=JSON.parse(l);if(typeof m==="object"&&m!==null)a=m}catch{}let d=(...m)=>{for(let g of m)if(typeof a[g]==="string")return a[g];return};if(c.status>=400)throw new Pn(c.status,d("code","Code"),d("message","Message"));let f=d("AccessKeyId"),h=d("SecretAccessKey");if(!c.ok||f===void 0||h===void 0)throw Error(`The credentials endpoint answered ${c.status} without AccessKeyId and SecretAccessKey.`);let u=d("Token"),p=d("Expiration");return i={accessKeyId:f,secretAccessKey:h,...u===void 0?{}:{sessionToken:u},...p===void 0?{}:{expiration:new Date(p)}},i}}var _v={ThrottlingException:429,ServiceUnavailableException:503,InternalServerException:500,ModelNotReadyException:503,ModelStreamErrorException:500,ModelTimeoutException:408},kv=/ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|socket hang up|TimeoutError/;function Sv(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 $v(e,t,n,r){let{name:i,message:s,status:o}=Sv(e),c=_v[i];if(c!==void 0){let d=o??c;return{retryable:!0,status:d,error:new gt({code:"model_http_error",message:`Bedrock ${i} for ${t} in ${n}.`,detail:s,hint:i==="ThrottlingException"?"Bedrock is throttling this account or model. Retries were spent; raise the model's quota in Service Quotas, spread load across a cross-region inference profile (eu., us., global.), or add a fallback.":"Bedrock reported a service-side failure and retries were spent. It is usually transient; a fallback under model.<role>.fallbacks covers it.",field:r,status:d,cause:e})}}if(i==="CredentialsRefusedError"){let d=e,f=typeof d.status==="number"?d.status:403,h=typeof d.code==="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(d.code)?d.code:void 0;if(f>=500)return{retryable:!0,status:f,error:new gt({code:h??"bedrock_credentials_unavailable",message:`The AWS credentials endpoint could not issue credentials for Bedrock (${t} in ${n}): status ${f}${h===void 0?"":`, ${h}`}${typeof d.detail==="string"?` — ${d.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 gt({code:h??"bedrock_credentials_refused",message:`The AWS credentials endpoint refused to issue credentials for Bedrock (${t} in ${n}): status ${f}${h===void 0?"":`, ${h}`}${typeof d.detail==="string"?` — ${d.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(s);if(i==="CredentialsProviderError"&&l!==null)return{retryable:!1,status:Number(l[1]),error:new gt({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(s))return{retryable:!1,status:void 0,error:new gt({code:"bedrock_credentials_missing",message:`No AWS credentials were found for Bedrock (${t} in ${n}).`,hint:"Credentials come from the default AWS chain: AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY in the process environment, a container-credentials endpoint (AWS_CONTAINER_CREDENTIALS_FULL_URI), EKS Pod Identity, or the instance role. Never a manifest field. For a named profile, set options.profile.",field:r,cause:e})};if(i==="AccessDeniedException"||o===403)return{retryable:!1,status:403,error:new gt({code:"model_access_denied",message:`Bedrock refused ${t} in ${n}: these credentials may not invoke it.`,detail:s,hint:/being verified/i.test(s)?"The AWS account is new and AWS is still verifying it, which it says takes under two hours. Nothing in the manifest or the IAM policy changes this; retry once the account is verified.":'Either the credential is invalid or expired (Bedrock says "security token … invalid"), or it is not allowed to invoke this model. For the second, check the IAM policy grants bedrock:InvokeModelWithResponseStream on the model or inference profile, and that model access is enabled in the Bedrock console for this region. An embedder that revokes credentials as a budget stop lands here on purpose, which is why this never falls back.',field:r,status:403,cause:e})};if(i==="ResourceNotFoundException"||o===404)return{retryable:!1,status:404,error:new gt({code:"model_not_found",message:`Bedrock has no model ${t} in ${n}.`,detail:s,hint:/use case details/i.test(s)?"Anthropic models on Bedrock need a one-time use-case form per AWS account: Bedrock console → Model catalog → an Anthropic model → submit the use case details. It applies about 15 minutes after submission.":"Check the model id and region together: a cross-region profile id starts with its geography (eu., us., apac., global.), and a base model id needs on-demand access in that exact region.",field:r,status:404,cause:e})};if(kv.test(`${i} ${s}`))return{retryable:!0,status:void 0,error:new gt({code:"model_unreachable",message:`Cannot reach Bedrock in ${n}.`,detail:s,hint:"Check outbound HTTPS to bedrock-runtime.<region>.amazonaws.com from this host; a default-deny network policy needs that endpoint listed.",field:r,cause:e})};let a=o??400;return{retryable:!1,status:a,error:new gt({code:"model_http_error",message:`Bedrock ${i} for ${t}.`,detail:s,hint:i==="ValidationException"?"Bedrock refused the request as malformed. Its own words, in `detail`, name the field; a model that does not support a feature asked for (tools, thinking, prompt caching) is the usual cause.":"Bedrock refused the request. Its own words are in `detail`.",field:r,status:a,cause:e})}}var ri={cachePoint:{type:"default"}},Tv={"image/png":"png","image/jpeg":"jpeg","image/gif":"gif","image/webp":"webp"};function Wa(e){return/(^|[./])anthropic\.claude|(^|[./])amazon\.nova/.test(e)}function Za(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 Rn(e){if(/(^|[./])openai\./.test(e))return"openai";let t=Za(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 Ja(e){let t=Za(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 Ha(e){return Rn(e)==="adaptive"||/(^|[./])openai\.gpt-6/.test(e)}function Ev(e,t){let n=[];if(Rn(e.id)==="adaptive"&&e.reasoningEffort==="none"&&Ja(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(Ha(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 Av=32768,Ov=16384,Nv={minimal:1024,low:2048,medium:8192,high:16384};function Iv(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 Cv(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:Iv(n.arguments)}});return t}function Pv(e){if(e.role==="assistant")return{role:"assistant",content:Cv(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!==""?`<runtime_context>
|
|
245
|
+
${e.content}
|
|
246
|
+
</runtime_context>`:e.content,n=t===""?[]:[{text:t}];for(let r of e.images??[])n.push({image:{format:Tv[r.mediaType],source:{bytes:Uint8Array.from(Buffer.from(r.data,"base64"))}}});return{role:"user",content:n}}function Rv(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 Mv(e,t){let n=Wa(e.model)&&t.capabilities?.promptCache!=="none",r=[],i=[],s=!0;for(let g of Rv(e.messages)){if(s&&g.role==="system"){if(g.content!=="")r.push({text:g.content});if(n&&g.cacheBreakpoint===!0)r.push(ri);continue}s=!1;let{role:y,content:w}=Pv(g);if(n&&g.cacheBreakpoint===!0&&w.length>0)w.push(ri);if(w.length===0)continue;let v=i.at(-1);if(v!==void 0&&v.role===y)v.content=[...v.content??[],...w];else i.push({role:y,content:w})}let o=i.at(-1),c=/(^|[./])amazon\.nova/.test(e.model)&&(o?.content??[]).some((g)=>g.toolResult!==void 0);if(n&&o!==void 0&&!c&&o.content?.at(-1)?.cachePoint===void 0)o.content=[...o.content??[],ri];let l=Rn(e.model),a=e.reasoningEffort,d=l==="budget"&&a!==void 0?Nv[a==="xhigh"||a==="max"?"high":a]:void 0,f=l==="adaptive"?Lv(e.model,a):void 0,h=d===void 0&&!Ha(e.model),u=d!==void 0?Math.max(e.maxTokens??0,d+Ov):f?.thinking===!0?e.maxTokens??Av:e.maxTokens,p={...u===void 0?{}:{maxTokens:u},...!h||e.temperature===void 0?{}:{temperature:e.temperature},...!h||e.topP===void 0?{}:{topP:e.topP}},m=d!==void 0?{thinking:{type:"enabled",budget_tokens:d}}: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(p).length===0?{}:{inferenceConfig:p},...e.tools===void 0||e.tools.length===0?{}:{toolConfig:{tools:e.tools.map((g)=>({toolSpec:{name:g.name,description:g.description,inputSchema:{json:g.parameters}}}))}},...m===void 0?{}:{additionalModelRequestFields:m}}}function Lv(e,t){if(t===void 0)return;if(t==="none"){let n=Ja(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 xv={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"},Dv="<thinking>",jv="</thinking>";function Uv(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 Va{#e="";#n=!1;#t=!1;push(e){let t=[],n=this.#e+e;this.#e="";for(;;){let r=this.#n?jv:Dv,i=n.indexOf(r);if(i===-1){let s=Uv(n,r);return this.#e=n.slice(n.length-s),t.push(...this.#r(n.slice(0,n.length-s))),t}if(t.push(...this.#r(n.slice(0,i))),this.#n=!this.#n,!this.#n)this.#t=!0;n=n.slice(i+r.length)}}flush(){let e=this.#e;return this.#e="",this.#r(e)}#r(e){if(this.#n)return e===""?[]:[{type:"reasoning",delta:e}];let t=this.#t?e.trimStart():e;if(t==="")return[];return this.#t=!1,[{type:"text",delta:t}]}}async function*zv(e,t={}){let n=new Map,r=t.thinkingTags===!0?new Va: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 d=l.reasoningContent;if(d.text!==void 0&&d.text!=="")a.text+=d.text,yield{type:"reasoning",delta:d.text};if(d.signature!==void 0)a.signature=d.signature;if(d.redactedContent!==void 0)a.redacted=Buffer.from(d.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:xv[c]??c};continue}let s=i.metadata?.usage;if(s!==void 0){let{cacheReadInputTokens:c,cacheWriteInputTokens:l}=s;yield{type:"usage",promptTokens:(s.inputTokens??0)+(c??0)+(l??0),completionTokens:s.outputTokens??0,...c===void 0?{}:{cachedPromptTokens:c,cacheSource:"metadata.usage.cacheReadInputTokens"},...l===void 0?{}:{cacheWriteTokens:l}};continue}let o=i.throttlingException??i.serviceUnavailableException??i.internalServerException??i.modelStreamErrorException??i.validationException;if(o!==void 0)throw o}}var Fv=async(e)=>{let t=await import("./index-hcpvk5de.js"),n=e.profile===void 0?ii(process.env):void 0,r=new t.BedrockRuntimeClient({region:e.region,maxAttempts:1,...e.profile===void 0?{}:{profile:e.profile},...n===void 0?{}:{credentials:n}});return async(i,s)=>{let o=await r.send(new t.ConverseStreamCommand(i),{abortSignal:s});if(o.stream===void 0)throw Error("Bedrock returned a ConverseStream response with no stream.");return o.stream}};function Bv(e){return e instanceof Error&&/bound to a different conversation/i.test(e.message)}function Kv(e){let t=!1,n=(e.messages??[]).map((r)=>{let i=(r.content??[]).filter((s)=>{let o=s.reasoningContent!==void 0;return t||=o,!o});return{...r,content:i}}).filter((r)=>r.content.length>0);return t?{...e,messages:n}:void 0}var qv=/(^|[./])amazon\.nova/,Wv={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 Zv(e,t){let n=Math.min(e.baseDelayMs*2**(t-1),e.maxDelayMs);return Math.round(n*(0.5+Math.random()/2))}function Jv(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 si(e=Fv){return{optionsSchema:Wv,capabilities:(t,n)=>{let r=n.capabilities?.promptCache===void 0&&Wa(n.id)?{...t,promptCache:"bedrock"}:t;return Rn(n.id)==="openai"?{...r,traceAfterInput:!0}:r},warnings:(t,n)=>Ev(t,n),create(t){let n=t.options;if(n===void 0)throw new B({code:"model_transport_options_invalid",message:`${t.field}.options are required for the bedrock-converse transport.`,hint:"Set options.region to the Bedrock region, e.g. eu-west-1, and options.profile for a named AWS profile.",field:`${t.field}.options`});let r=t.retry??Os,i;return{id:t.id,async*chat(s,o){i??=e(n);let c=await i,l=Mv(s,t.config),a=!1;for(let d=1;;d+=1){let f=!1;try{for await(let h of zv(await c(l,o),{thinkingTags:qv.test(t.config.id)}))f=!0,yield h;return}catch(h){if(o.aborted)return;if(!f&&!a&&Bv(h)){let m=Kv(l);if(m!==void 0){l=m,a=!0,t.onRetry?.({status:400,attempt:d,delayMs:0});continue}}let u=$v(h,s.model,n.region,t.field);if(f||!u.retryable||d>=r.attempts)throw u.error;let p=Zv(r,d);if(t.onRetry?.({status:u.status??0,attempt:d,delayMs:p}),await Jv(p,o),o.aborted)return}}}}}}}var Ga={name:"model-bedrock",version:Ye,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",si())}};var Qa=16000,Vv=(e,t)=>new Promise((n,r)=>{let i=Hv("ffmpeg",["-hide_banner","-loglevel","error","-i","pipe:0"].concat(["-f","s16le","-ac","1","-ar",String(Qa),"pipe:1"]),{stdio:["pipe","pipe","pipe"]}),s=[],o=[],c=()=>i.kill("SIGKILL");t.addEventListener("abort",c,{once:!0}),i.stdout.on("data",(l)=>s.push(l)),i.stderr.on("data",(l)=>o.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(s)));else r(Error(Buffer.concat(o).toString("utf8").trim()||`ffmpeg exited ${l}`))}),i.stdin.on("error",()=>{}),i.stdin.end(Buffer.from(e))});function oi(e){if(e.profile!==void 0)return{profile:e.profile};let t=ii(process.env);return t===void 0?{}:{credentials:t}}var Gv={async transcribe(e){let t=await import("./index-p86w0qjw.js"),n=new t.TranscribeStreamingClient({region:e.region,...oi(e)});return async(r,i)=>{let s=await n.send(new t.StartStreamTranscriptionCommand(r),{abortSignal:i});if(s.TranscriptResultStream===void 0)throw Error("Transcribe returned no result stream.");return s.TranscriptResultStream}},async invoke(e){let t=await import("./index-hcpvk5de.js"),n=new t.BedrockRuntimeClient({region:e.region,...oi(e)});return async(r,i)=>{let s=await n.send(new t.InvokeModelCommand({modelId:r.modelId,contentType:"application/json",accept:"application/json",body:r.body}),{abortSignal:i});return new TextDecoder().decode(s.body)}},async speak(e){let t=await import("./index-gpq4agva.js"),n=new t.PollyClient({region:e.region,...oi(e)});return async(r,i)=>{let s=await n.send(new t.SynthesizeSpeechCommand({Text:r.text,OutputFormat:"ogg_opus",VoiceId:r.voiceId,Engine:r.engine,...r.languageCode===void 0?{}:{LanguageCode:r.languageCode}}),{abortSignal:i});if(s.AudioStream===void 0)throw Error("Polly returned no audio.");return{bytes:await s.AudioStream.transformToByteArray(),...s.RequestCharacters===void 0?{}:{characters:s.RequestCharacters}}}},decode:Vv},Ya=new Set(["region","profile","languageCode","sampleRate","voiceId","engine"]),Yv={safeParse(e){let t=typeof e==="object"&&e!==null?e:{},n=(i)=>({success:!1,error:{issues:[{message:i}]}}),r=Object.keys(t).find((i)=>!Ya.has(i));if(r!==void 0)return n(`unknown option "${r}" (takes ${[...Ya].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 Xv(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 Xa=8192;async function*Qv(e){for(let t=0;t<e.byteLength;t+=Xa)yield{AudioEvent:{AudioChunk:e.subarray(t,t+Xa)}}}function eb(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 ai(e,t){if(e instanceof Pn){let i=e.code!==void 0&&/^[a-z][a-z0-9_]{1,63}$/.test(e.code)?e.code:void 0;return new Vt({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 Vt({code:"media_provider_refused",message:`AWS refused the request (${n||"error"}): ${r}`,hint:n==="AccessDeniedException"||n==="UnrecognizedClientException"?eb(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 ci(e=Gv){return{optionsSchema:Yv,create(t){if(t.options===void 0)throw new B({code:"media_aws_region_missing",message:`${t.field}.options.region is required for the aws provider.`,hint:"Name the region, e.g. options: { region: eu-west-2 }. Nova Canvas is in us-east-1, eu-west-1 and ap-northeast-1.",field:`${t.field}.options`});let n=t.options,r,i,s;return{async transcribe(c,l){let a=Xv(c.mimeType),d=c.bytes;if(a===void 0)try{d=await e.decode(c.bytes,l)}catch(f){let h=f.code==="ENOENT";throw new Vt({code:"media_audio_unsupported",message:h?`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:h?"Install ffmpeg on the PATH (the container image carries it), or use the openai provider in media.transcription.":"The file is probably not audio, or is damaged. Ogg/Opus and FLAC are sent as they are.",field:`${t.field}.provider`})}r??=e.transcribe(n);try{let h=await(await r)({LanguageCode:n.languageCode??"en-US",MediaEncoding:a??"pcm",MediaSampleRateHertz:a===void 0?Qa:n.sampleRate??48000,AudioStream:Qv(d)},l),u=[],p;for await(let m of h)for(let g of m.TranscriptEvent?.Transcript?.Results??[]){if(g.IsPartial===!0)continue;let y=g.Alternatives?.[0]?.Transcript;if(y!==void 0&&y!=="")u.push(y);if(g.EndTime!==void 0)p=g.EndTime}return{text:u.join(" "),...p===void 0?{}:{durationS:p}}}catch(f){if(f instanceof Vt)throw f;throw ai(f,t.field)}},async synthesize(c,l){s??=e.speak(n);try{let d=await(await s)({text:c.text,voiceId:n.voiceId??"Joanna",engine:n.engine??"neural",...n.languageCode===void 0?{}:{languageCode:n.languageCode}},l);return{bytes:d.bytes,mimeType:"audio/ogg; codecs=opus",...d.characters===void 0?{}:{characters:d.characters}}}catch(a){throw ai(a,t.field)}},async generateImage(c,l){let[a,d]=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:d}})},l)}catch(p){throw ai(p,t.field)}let h=JSON.parse(f),u=h.images?.[0];if(u===void 0)throw new Vt({code:"media_provider_empty",message:`Nova Canvas returned no image${h.error===void 0?"":`: ${h.error}`}.`,hint:"A prompt its content filter refused comes back this way. Rephrasing it is usually what works.",field:t.field});return{bytes:Buffer.from(u,"base64"),mimeType:"image/png"}}}}}}var tb="0.1.0",ec={name:"media-aws",version:tb,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["transcribestreaming.*.amazonaws.com","bedrock-runtime.*.amazonaws.com","polly.*.amazonaws.com"]}],setup(e){e.defineMediaProvider("aws",ci())}};import{mkdirSync as nb,readFileSync as rb,renameSync as ib,writeFileSync as sb}from"node:fs";import{dirname as ob,isAbsolute as ab,join as tc,resolve as cb}from"node:path";import{createHash as yb}from"node:crypto";import{existsSync as wb}from"node:fs";import{readFile as vb,realpath as cc,stat as bb}from"node:fs/promises";import{basename as _b,extname as kb,isAbsolute as yc,join as lc,relative as Sb,resolve as uc,sep as $b}from"node:path";import{mkdirSync as Vb,readFileSync as kc,renameSync as Gb,writeFileSync as Yb}from"node:fs";import{dirname as Xb,isAbsolute as Qb,join as hc,resolve as e_}from"node:path";var Mn=1,nc="tools.cache.json";function Ln(e){return ab(e)?tc(e,V.stateDir,nc):tc(cb(e),V.stateDir,nc)}function lb(e){return typeof e==="object"&&e!==null&&typeof e.slug==="string"}function rc(e){let t={version:Mn,provider:"composio",fetchedAt:"",baseUrl:"",tools:{}},n;try{n=rb(Ln(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!==Mn)return t;let s={};for(let[o,c]of Object.entries(i.tools??{}))if(lb(c))s[o]=c;return{version:Mn,provider:"composio",fetchedAt:typeof i.fetchedAt==="string"?i.fetchedAt:"",baseUrl:typeof i.baseUrl==="string"?i.baseUrl:"",tools:s}}catch{return t}}function ub(e,t,n,r){let i=Ln(e);nb(ob(i),{recursive:!0});let s={version:Mn,provider:"composio",fetchedAt:r().toISOString(),baseUrl:n,tools:t},o=`${i}.${process.pid}.tmp`;return sb(o,`${JSON.stringify(s,null,2)}
|
|
247
|
+
`,"utf8"),ib(o,i),i}function ic(e){return new B({code:"composio_key_missing",message:`The Composio provider needs an API key, and ${e} is not set.`,hint:`Set ${e} in the environment, or in a .env beside the manifest. Change which variable is read with tools.providers.composio.apiKeyEnv — the manifest holds the variable's name, never the key itself.`,field:"tools.providers.composio.apiKeyEnv"})}function db(e,t,n){return new B({code:"composio_schema_unsupported",message:`The Composio tool "${e}" declares "${n}" at ${t}, which this runtime's schema subset cannot express.`,hint:"Refused rather than dropped: that keyword decides which argument documents are valid, so ignoring it would hand the model a schema the endpoint disagrees with. Unpin this tool, or pin a sibling action with a flatter schema. Value constraints such as minimum and format are not affected — those are carried in the field's description.",field:"tools.pinned"})}function fb(e,t){return new B({code:"composio_cache_miss",message:`${e.length===1?"A pinned Composio tool is":`${e.length} pinned Composio tools are`} not in the resolution cache: ${e.join(", ")}.`,hint:`Boot resolves tools from ${t} and makes no network call, because nothing may touch the network before runtime.ready. Run \`${V.slug} tools <manifest> --warm\` once to populate it, then start again.`,field:"tools.pinned"})}function Ue(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 hb(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 pb(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 sc(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 oc(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 mb="https://backend.composio.dev/api/v3";function ac(e){return/\/v3$/.test(e)?e.replace(/\/v3$/,"/v3.1"):e}var gb=100;function st(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=st(st(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 gc{#e;#n;#t;constructor(e){this.#e=e.apiKey,this.#n=ao(e.baseUrl??mb),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 Ue(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 Ue(n.status,await vt(n));let r=st(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(gb)});if(n!==void 0)i.set("cursor",n);let s=await this.#o(`/tools?${i.toString()}`,e);for(let c of s.items??[])if(typeof c.slug==="string")t.push(c.slug);let o=s.next_cursor;if(o===null||o===void 0||o===""||o===n)break;n=o}return t}async execute(e,t,n,r){let i=await this.#s(`${this.#n}/tools/execute/${encodeURIComponent(e)}`,{user_id:n,arguments:t},r);if(!i.ok)throw Ue(i.status,await vt(i));let s=st(await i.json())??{},o=s.successful!==!1,c=typeof s.error==="string"&&s.error!==""?s.error:void 0;return{ok:o,data:s.data??s,...c===void 0?{}:{error:c}}}async uploadFile(e,t,n){let r=await this.#s(`${this.#n}/files/upload/request`,{filename:e.name,mimetype:e.mimetype,md5:e.md5,tool_slug:t.slug,toolkit_slug:t.toolkit},n);if(!r.ok)throw Ue(r.status,await vt(r));let i=st(await r.json())??{},s=i.key,o=i.new_presigned_url??i.newPresignedUrl;if(typeof s!=="string"||typeof o!=="string")throw Ue(r.status,"the upload answer had no key or URL");let c=await this.#t(o,{method:"PUT",headers:{"content-type":e.mimetype,"content-length":String(e.bytes.byteLength)},body:e.bytes,...n===void 0?{}:{signal:n}});if(!c.ok)throw Ue(c.status,"the file upload to storage failed");return{name:e.name,mimetype:e.mimetype,s3key:s}}#s(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.#s(`${ac(this.#n)}/tool_router/session`,{user_id:e},t);if(!n.ok)throw Ue(n.status,await vt(n));let r=st(await n.json())??{},i=r.session_id;if(typeof i!=="string"||i==="")throw Ue(n.status,"no session_id in the response body");return r}async executeMeta(e,t,n,r){let i=await this.#s(`${ac(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 Ue(i.status,await vt(i));let s=st(await i.json())??{},o=typeof s.error==="string"&&s.error!==""?s.error:void 0;return{ok:s.successful===void 0?o===void 0:s.successful!==!1,data:s.data??s,...o===void 0?{}:{error:o}}}}var dc=26214400,Tb="A file from your workspace, written as its path (for example reports/q3.pdf); it is uploaded for you.";function ze(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ui(e){return e.file_uploadable===!0}function Eb(e){if(e===void 0)return;let t=(r,i)=>{if(Array.isArray(r))return r.map((o)=>t(o,i));let s=ze(r);if(s===void 0)return r;if(ui(s))return{type:"string",description:`${typeof s.description==="string"?`${s.description.trim()} `:""}${Tb}`};if(typeof s.$ref==="string"&&!i.has(s.$ref)){let o=di(e,s.$ref);if(o!==void 0&&n(o,new Set([s.$ref]))){let{$ref:c,...l}=s;return t({...o,...l},new Set([...i,s.$ref]))}}return Object.fromEntries(Object.entries(s).map(([o,c])=>[o,t(c,i)]))},n=(r,i)=>{if(Array.isArray(r))return r.some((o)=>n(o,i));let s=ze(r);if(s===void 0)return!1;if(ui(s))return!0;if(typeof s.$ref==="string"&&!i.has(s.$ref)){let o=di(e,s.$ref);return o!==void 0&&n(o,new Set([...i,s.$ref]))}return Object.values(s).some((o)=>n(o,i))};return t(e,new Set)}function di(e,t){if(!t.startsWith("#/"))return;let n=e;for(let r of t.slice(2).split("/"))n=ze(n)?.[r];return ze(n)}function Ab(e){if(e===void 0)return[];let t=new Map,n=(r,i,s)=>{if(ui(r)){let c=i.filter((l)=>l!=="[]");t.set(c.join("."),c);return}if(typeof r.$ref==="string"&&!s.has(r.$ref)){let c=di(e,r.$ref);if(c!==void 0)n(c,i,new Set([...s,r.$ref]))}for(let c of["anyOf","oneOf","allOf"]){let l=r[c];if(Array.isArray(l))for(let a of l){let d=ze(a);if(d!==void 0)n(d,i,s)}}let o=ze(r.items);if(o!==void 0)n(o,[...i,"[]"],s);for(let[c,l]of Object.entries(ze(r.properties)??{})){let a=ze(l);if(a!==void 0)n(a,[...i,c],s)}};return n(e,[],new Set),[...t.values()]}var Ob={".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".html":"text/html",".htm":"text/html",".json":"application/json",".xml":"application/xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".zip":"application/zip",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".ics":"text/calendar",".mp3":"audio/mpeg",".mp4":"video/mp4"};function bt(e,t,n){return new S({code:"composio_file_refused",message:`The file "${e}" cannot be attached: ${t}`,hint:n})}var Nb=(e,t)=>{let n=Sb(e,t);return n===""?!1:!n.startsWith("..")&&!yc(n)&&!n.startsWith($b)};async function Ib(e,t){let n=wb(lc(e,"workspace"))?lc(e,"workspace"):e,r=await cc(n),i=t.trim().replace(/^workspace\//,""),s="Attach a file from your own workspace, by its path, e.g. reports/q3.pdf.";if(i==="")throw bt(t,"no path was given.","Attach a file from your own workspace, by its path, e.g. reports/q3.pdf.");let o=yc(i)?uc(i):uc(r,i),c;try{c=await cc(o)}catch{throw bt(t,"there is no such file in your workspace.","Attach a file from your own workspace, by its path, e.g. reports/q3.pdf.")}if(!Nb(r,c))throw bt(t,"it is outside your workspace.","Attach a file from your own workspace, by its path, e.g. reports/q3.pdf.");let l=_b(c);if(/^\.env/i.test(l))throw bt(t,"it holds secrets.","Attach a file from your own workspace, by its path, e.g. reports/q3.pdf.");let a=await bb(c);if(!a.isFile())throw bt(t,"it is not a file.","Attach a file from your own workspace, by its path, e.g. reports/q3.pdf.");if(a.size>dc)throw bt(t,`it is ${Math.ceil(a.size/1048576)} MB, over the ${dc/1048576} MB limit.`,"Share a link to it instead, or send a smaller file.");let d=new Uint8Array(await vb(c));return{name:l,mimetype:Ob[kb(l).toLowerCase()]??"application/octet-stream",bytes:d,md5:yb("md5").update(d).digest("hex")}}async function Cb(e,t,n){let r=async(s,o)=>{if(Array.isArray(s))return Promise.all(s.map((d)=>r(d,o)));if(o.length===0)return typeof s==="string"?n(s):s;let c=ze(s),[l,...a]=o;if(c===void 0||l===void 0||!(l in c))return s;return{...c,[l]:await r(c[l],a)}},i=e;for(let s of t)i=await r(i,s);return i}function Pb(e){return ro(Eb(e.input_parameters),{unsupported:(t,n)=>db(e.slug,t,n),rootPath:"input_parameters"})}function fi(e){let t=new Set(e.tags??[]);if(t.has("destructiveHint"))return!0;return!t.has("readOnlyHint")}function wc(e){let t=new Set(e.tags??[]);return!t.has("readOnlyHint")&&!t.has("destructiveHint")}function Rb(e){let t=e.replace(/\s+/g," ").trim(),n=t.search(/\.\s|\.$/);return n===-1?t:t.slice(0,n+1)}function vc(e){let t=(e.description??e.human_description??"").trim(),n=t===""?`The ${e.slug} tool.`:Rb(t),r=e.toolkit?.slug;return{slug:e.slug,provider:"composio",summary:n,whenToUse:t===""?`the task needs ${e.slug}`:t,mutating:fi(e),tags:[...r===void 0?[]:[r],...fi(e)?["write"]:["read"]],parameters:Pb(e)}}var Mb=8,fc=100,xn="composio_search",Dn="composio_connect",mi="composio_workbench",Lb=[xn,Dn,mi];function Ge(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function hi(e){return Array.isArray(e)?e:[]}function Ve(e){return typeof e==="string"&&e!==""?e:void 0}function xb(e){let t=e.replace(/\s+/g," ").trim();return t.length<=fc?t:`${t.slice(0,fc-1)}…`}var bc={slug:xn,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 Db(e){let t=[];for(let n of hi(e.results)){let r=Ge(n);if(r===void 0)continue;for(let i of[r.primary_tool_slugs,r.related_tool_slugs])for(let s of hi(i))if(typeof s==="string"&&!t.includes(s))t.push(s)}return t.slice(0,Mb)}function jb(e,t){let n=[];for(let r of e){let i=t[r];if(i===void 0)continue;let s=i.description??i.human_description??"",o;try{vc(i)}catch(c){if(!_(c))throw c;o=c.message}n.push({...o===void 0?{}:{unavailable:o},slug:r,summary:s===""?"no description supplied":xb(s),toolkit:i.toolkit?.slug??"",mutating:fi(i),assumed:wc(i)})}return n}function Ub(e){let t=[];for(let n of hi(e.toolkit_connection_statuses)){let r=Ge(n),i=Ve(r?.toolkit);if(i===void 0)continue;t.push({toolkit:i,connected:r?.has_active_connection===!0})}return t}function zb(e,t,n){let r=[`Tools that can "${e}":`,""];for(let o of t){if(o.unavailable!==void 0){r.push(` n/a ${o.slug}`),r.push(` unavailable — do not pin it: ${o.unavailable}`);continue}r.push(` ${o.mutating?"write":"read "} ${o.slug}`),r.push(` ${o.summary}`)}if(t.some((o)=>o.assumed))r.push(""),r.push("Some of those are marked write because they say nothing either way, not because they are known to change things. Composio leaves a third of its catalogue unannotated and the safe reading is the one taken here.");let i=n.filter((o)=>!o.connected).map((o)=>o.toolkit),s=n.filter((o)=>o.connected).map((o)=>o.toolkit);if(r.push(""),s.length>0)r.push(`Already connected: ${s.join(", ")}.`);if(i.length>0)r.push(`Not connected yet: ${i.join(", ")}. Call composio_connect for each before these tools can run.`);if(r.push(""),r.push("These are not enabled yet. To enable them, add the slugs you need to tools.pinned with "+"config_set — their definitions are already saved, so no other setup is needed. "+"config_set says which become usable in this conversation; the rest work from the person's next message, with no restart. Pin only what the task needs."),t.some((o)=>o.unavailable!==void 0))r.push("Those marked n/a cannot be loaded by this runtime as Composio describes them today; a pinned one is left out with a warning. Choose another tool, or tell the person it is unavailable.");return r.join(`
|
|
248
|
+
`)}function Fb(e){return{spec:bc,handler:async(t,n)=>{let r=String(t.use_case??"").trim(),i=await e.call("COMPOSIO_SEARCH_TOOLS",{queries:[{use_case:r}],session:{generate_id:!0}},n.signal);if(!i.ok)return`The search failed: ${i.error??"no detail supplied"}`;let s=Ge(i.data)??{},o=Db(s);if(o.length===0)throw oc(r);let c=await e.fetchSchemas(o,n.signal),l=jb(o,c);if(l.length===0)throw oc(r);return zb(r,l,Ub(s))}}}var _c={slug:Dn,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 pi(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(Ge(e)??{})){let r=pi(n,t+1);if(r!==void 0)return r}return}function Bb(e,t){let n=Ge(Ge(t.results)?.[e]),r=Ve(n?.status)?.toLowerCase(),i=Ve(n?.redirect_url)??pi(t.results)??pi(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})`}. ${Ve(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(`
|
|
249
|
+
`)}function Kb(e){return{spec:_c,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 Bb(r,Ge(i.data)??{})}}}var qb={slug:mi,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"]}},Wb="code_to_execute";function Zb(e){let t=Ge(e);if(t===void 0)return typeof e==="string"?e:JSON.stringify(e,null,2);let n=[],r=Ve(t.stdout),i=Ve(t.stderr),s=Ve(t.error),o=Ve(t.results);if(r!==void 0)n.push(r.trimEnd());if(o!==void 0)n.push(o.trimEnd());if(i!==void 0)n.push(`stderr:
|
|
250
|
+
${i.trimEnd()}`);if(s!==void 0)n.push(`error:
|
|
251
|
+
${s.trimEnd()}`);return n.length===0?"The code ran and printed nothing.":n.join(`
|
|
252
|
+
`)}function Jb(e){return{spec:qb,handler:async(t,n)=>{let r=await e.call("COMPOSIO_REMOTE_WORKBENCH",{[Wb]:String(t.code??"")},n.signal);if(!r.ok)return`The workbench failed: ${r.error??"no detail supplied"}`;return Zb(r.data)}}}function Hb(e){return{[xn]:Fb(e),[Dn]:Kb(e),[mi]:Jb(e)}}var pc="composio.session.json";function Sc(e){return Qb(e)?hc(e,V.stateDir,pc):hc(e_(e),V.stateDir,pc)}function t_(e,t){let n;try{n=kc(Sc(e),"utf8")}catch{return}try{let i=JSON.parse(n)?.sessions;if(typeof i!=="object"||i===null)return;let s=i[t];return typeof s==="string"&&s!==""?s:void 0}catch{return}}function n_(e,t,n){let r=Sc(e);Vb(Xb(r),{recursive:!0});let i={};try{let l=JSON.parse(kc(r,"utf8"))?.sessions;if(typeof l==="object"&&l!==null){for(let[a,d]of Object.entries(l))if(typeof d==="string")i[a]=d}}catch{i={}}let s={sessions:{...i,[t]:n}},o=`${r}.${process.pid}.tmp`;return Yb(o,`${JSON.stringify(s,null,2)}
|
|
253
|
+
`,"utf8"),Gb(o,r),r}var r_="COMPOSIO_API_KEY";class $c{id="composio";#e;#n;#t;#r;#o;#s;#a;#i;#c;#l=[];#u=[];#d;constructor(e){this.#e=e.dir,this.#n=e.userId??"default",this.#t=e.now??(()=>new Date),this.#s=e.apiKeyEnv??r_,this.#a=e.personal??!0;let t=e.env[this.#s];this.#r=e.baseUrl??"https://backend.composio.dev/api/v3",this.#o=t===void 0||t===""?void 0:new gc({apiKey:t,baseUrl:this.#r,...e.fetch===void 0?{}:{fetch:e.fetch}});let n=rc(this.#e);this.#i=n.tools,this.#c=n.fetchedAt}async resolve(e){let t=[],n=[],r=[],i=Hb(this.#p());for(let s of e){let o=i[s];if(o!==void 0){t.push(o);continue}let c=this.#i[s];if(c===void 0)continue;let l;try{l=vc(c)}catch(a){if(!_(a))throw a;r.push({slug:s,detail:a.toDetail()});continue}if(wc(c))n.push(s);t.push(this.#h(l))}if(this.#l=n,this.#u=r,!this.#a)return t;return t.map((s)=>({...s,spec:{...s.spec,personal:!0}}))}refused(){return this.#u}async list(){return[...Lb,...Object.keys(this.#i)]}async available(){return[{slug:xn,summary:bc.summary},{slug:Dn,summary:_c.summary}]}uncached(e){return e.filter((t)=>this.#i[t]===void 0)}explainUnresolved(e){if(Object.keys(this.#i).length>0||e.length===0)return;return fb(e,Ln(this.#e))}describe(){return{cached:Object.keys(this.#i).length,fetchedAt:this.#c,cachePath:Ln(this.#e),assumedMutating:this.#l}}async refresh(e,t){let n=this.#o;if(n===void 0)throw ic(this.#s);let r={},i=[],s=[];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.#i[c];if(a===void 0||JSON.stringify(a)!==JSON.stringify(l))s.push(c)}this.#i={...this.#i,...r};let o=ub(this.#e,this.#i,this.#r,this.#t);return this.#c=rc(this.#e).fetchedAt,{fetched:Object.keys(r).length,missing:i,changed:s,cachePath:o}}async#f(e,t=!1){let n=this.#o;if(n===void 0)throw sc(this.#s);if(!t){let i=this.#d??t_(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,n_(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 sc(this.#s);let i=await this.#f(n),s=await r.executeMeta(i,e,t,n);if("notFound"in s){i=await this.#f(n,!0);let o=await r.executeMeta(i,e,t,n);if("notFound"in o)return{ok:!1,data:{},error:"the session could not be opened"};s=o}return s},fetchSchemas:async(e,t)=>{await this.refresh(e,t);let n={};for(let r of e){let i=this.#i[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 ic(this.#s);let i=Ab(this.#i[e.slug]?.input_parameters),s=i.length===0?t:await Cb(t,i,async(c)=>r.uploadFile(await Ib(n.dir,c),{slug:e.slug,toolkit:this.#i[e.slug]?.toolkit?.slug??e.tags[0]??""},n.signal)),o=await r.execute(e.slug,s,this.#n,n.signal);if(!o.ok){let c=o.error??"no detail supplied";if(/connected account|not connected|no connection/i.test(c)){let l=e.tags[0]??"the toolkit";throw pb(e.slug,l)}throw hb(e.slug,200,c)}return typeof o.data==="string"?o.data:JSON.stringify(o.data,null,2)}}}}var mc=["apiKeyEnv","userId","baseUrl","personal"];function li(e,t){let n=e[t];if(n===void 0)return;if(typeof n!=="string"||n==="")throw new B({code:"composio_config_invalid",message:`tools.providers.composio.${t} must be a non-empty string.`,hint:`Got ${n===null?"null":typeof n}. ${t==="apiKeyEnv"?"This is the *name* of an environment variable, never the key itself — a manifest holding a literal key fails validation.":"Remove the key to use the default."}`,field:`tools.providers.composio.${t}`});return n}function gi(e){let t=Object.keys(e.config).filter((o)=>!mc.includes(o));if(t.length>0)throw new B({code:"composio_config_unknown",message:`tools.providers.composio has ${t.length===1?"a key":"keys"} the Composio provider does not read: ${t.join(", ")}.`,hint:`Accepted keys are ${mc.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=li(e.config,"apiKeyEnv"),r=li(e.config,"userId"),i=li(e.config,"baseUrl"),s=e.config.personal;if(s!==void 0&&typeof s!=="boolean")throw new B({code:"composio_config_invalid",message:"tools.providers.composio.personal must be true or false.",hint:"Leave it out to keep the default, true: every tool acts as the agent's owner. Write false only for a Composio entity a whole team shares on purpose.",field:"tools.providers.composio.personal"});return new $c({dir:e.dir,env:e.env,...n===void 0?{}:{apiKeyEnv:n},...r===void 0?{}:{userId:r},...i===void 0?{}:{baseUrl:i},...s===void 0?{}:{personal:s}})}var i_="0.1.0",Tc={name:"composio",version:i_,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",gi)}};import{mkdirSync as s_,readFileSync as o_,renameSync as a_,writeFileSync as c_}from"node:fs";import{dirname as l_,join as u_,resolve as d_}from"node:path";var Cc=1;function wi(e){return u_(d_(e),V.stateDir,"mcp.cache.json")}function f_(e){try{let t=JSON.parse(o_(wi(e),"utf8"));if(t.version!==Cc||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 h_(e,t){let n=wi(e);s_(l_(n),{recursive:!0});let r=`${n}.partial`;return c_(r,`${JSON.stringify({version:Cc,servers:t},null,2)}
|
|
254
|
+
`),a_(r,n),n}var Pc="tools.providers.mcp";function _e(e,t,n=Pc){return new B({code:"mcp_config_invalid",message:e,hint:t,field:n})}function p_(e,t,n){return new B({code:"mcp_cache_miss",message:`${t.length===1?"A pinned MCP tool is":`${t.length} pinned MCP tools are`} not in the cache: ${t.join(", ")}. Nothing is cached yet for ${e.join(", ")}.`,hint:`Boot resolves MCP tools from ${n} and contacts no server, because nothing may touch the network before runtime.ready, and a server that is down must not stop an agent booting. Run \`${V.slug} tools <manifest> --warm\` once with the server running to fill it, then start again.`,field:"tools.pinned"})}function m_(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 (${Pc}.servers.${e}.headersEnv), never the value.`})}function Rc(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 g_(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 Ec="2025-06-18";class Mc{#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.#s("tools/list",n===void 0?{}:{cursor:n},{},e);for(let s of i.tools??[])if(typeof s?.name==="string")t.push(s);if(n=i.nextCursor,n===void 0||n==="")return t}return t}async callTool(e,t,n,r){return await this.#s("tools/call",{name:e,arguments:t},n,r)}async#s(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.#i(e).finally(()=>{this.#r=void 0}),this.#r}async#i(e){let t=await this.#c("initialize",{protocolVersion:Ec,capabilities:{},clientInfo:{name:V.slug,version:Ye}},{},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":Ec,...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")?y_(n):[n];for(let s of i){let o;try{o=JSON.parse(s)}catch{continue}if(o.error!==void 0)throw this.#d(`${t} failed (${o.error.code??"?"}): ${o.error.message??"no message"}`);if(o.result!==void 0)return o.result}throw this.#d(`${t} returned no JSON-RPC result`)}#d(e){return Rc(this.#e.server,this.#e.url,e)}}function y_(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(`
|
|
255
|
+
`))}return t}var jn="__";function Dt(e,t){return`${e}${jn}${t.replace(/[^A-Za-z0-9_-]/g,"_")}`}function w_(e){let t=e.annotations;return t?.readOnlyHint!==!0||t.destructiveHint===!0}function v_(e){let t=e.replace(/\s+/g," ").trim(),n=t.search(/\.\s|\.$/);return n===-1?t:t.slice(0,n+1)}function Lc(e,t){let n=(t.description??t.title??"").trim();return n===""?`The ${t.name} tool on ${e}.`:v_(n)}function b_(e,t,n){let r=Dt(e,t.name),i=(t.description??t.title??"").trim(),s=w_(t);return{slug:r,provider:"mcp",summary:Lc(e,t),whenToUse:i===""?`the task needs ${t.name} from ${e}`:i,mutating:s,tags:[e,s?"write":"read"],...n===void 0?{}:{policyArg:n},parameters:ro(t.inputSchema,{untyped:"object",rootPath:"inputSchema",unsupported:(o,c)=>_e(`The MCP tool "${r}" declares "${c}" at ${o}, which this runtime's schema subset cannot express.`,"Refused rather than dropped: that keyword decides which arguments are valid, so ignoring it would hand the model a schema the server disagrees with. Unpin this tool, or ask the server for a flatter one.","tools.pinned")})}}var Ac=["url","headersEnv","participantHeader","turnHeader","policyArgs","timeoutMs","personal"],Oc=30000,__=40;function yi(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Nc(e,t,n){if(e===void 0)return{};let r=yi(e),i=r===void 0?void 0:Object.entries(r),s=i?.every(([,o])=>typeof o==="string"&&(n===void 0||n.test(o)));if(i===void 0||s!==!0)throw _e(`${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 k_(e){let t=Object.keys(e).filter((r)=>r!=="servers");if(t.length>0)throw _e(`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=yi(e.servers);if(n===void 0||Object.keys(n).length===0)throw _e("tools.providers.mcp names no servers.","Add servers.<name>.url, e.g. servers: { tracker: { url: http://127.0.0.1:3000/mcp } }.","tools.providers.mcp.servers");return Object.entries(n).map(([r,i])=>{let s=`tools.providers.mcp.servers.${r}`;if(!/^[a-z][a-z0-9-]{0,23}$/.test(r))throw _e(`The MCP server name "${r}" is not usable in a tool slug.`,"Use lowercase letters, digits and hyphens, starting with a letter, at most 24 characters. It prefixes every tool: tracker → tracker__search_tools.",s);let o=yi(i)??{},c=Object.keys(o).filter((h)=>!Ac.includes(h));if(c.length>0)throw _e(`${s} has keys the MCP provider does not read: ${c.join(", ")}.`,`Accepted keys are ${Ac.join(", ")}.`,s);let l;try{l=new URL(String(o.url))}catch{throw _e(`${s}.url is not a URL.`,"Give the server's Streamable HTTP endpoint, e.g. http://127.0.0.1:3000/mcp.",`${s}.url`)}if(l.protocol!=="http:"&&l.protocol!=="https:")throw _e(`${s}.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).",`${s}.url`);if(l.username!==""||l.password!=="")throw _e(`${s}.url carries a credential.`,"A manifest never holds a secret. Put it in an env var and name it in headersEnv, e.g. { Authorization: TRACKER_MCP_TOKEN }.",`${s}.url`);let a=o.timeoutMs===void 0?Oc:o.timeoutMs;if(typeof a!=="number"||!Number.isInteger(a)||a<=0)throw _e(`${s}.timeoutMs must be a positive whole number of milliseconds.`,`Omit it for ${Oc} ms.`,`${s}.timeoutMs`);let d=o.participantHeader;if(d!==void 0&&typeof d!=="string")throw _e(`${s}.participantHeader must be a header name.`,"e.g. X-Acting-Participant. Each call then carries the id of the person the turn acts for, and none on a schedule or peer-agent turn.",`${s}.participantHeader`);let f=o.turnHeader;if(f!==void 0&&(typeof f!=="string"||!/^[A-Za-z0-9-]+$/.test(f)))throw _e(`${s}.turnHeader must be a header name.`,"e.g. X-Dispach-Turn. Each call then carries the turn id there, and the call id in <name>-Call.",`${s}.turnHeader`);if(o.personal!==void 0&&typeof o.personal!=="boolean")throw _e(`${s}.personal must be true or false.`,"true when the server acts as the agent's owner (their mailbox, their account), so only the owner's turns get its tools.",`${s}.personal`);return{name:r,url:l.toString(),...o.personal===!0?{personal:!0}:{},...f===void 0?{}:{turnHeader:f},headersEnv:Nc(o.headersEnv,`${s}.headersEnv`,/^[A-Za-z_][A-Za-z0-9_]*$/),...d===void 0?{}:{participantHeader:d},policyArgs:Nc(o.policyArgs,`${s}.policyArgs`),timeoutMs:a}})}function Ic(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(`
|
|
256
|
+
`);return e.structuredContent===void 0?"(no content)":JSON.stringify(e.structuredContent,null,2)}class xc{id="mcp";#e;#n;#t;#r;#o=new Map;#s;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.#s=f_(e.dir)}#a(e){let t=this.#s[e.name];return t===void 0||t.url!==e.url?void 0:t.tools}async resolve(e){let t=[],n=[];for(let r of this.#t.values())for(let i of this.#a(r)??[]){let s=Dt(r.name,i.name);if(!e.includes(s))continue;try{t.push(this.#l(r,i))}catch(o){if(!_(o))throw o;n.push({slug:s,detail:o.toDetail()})}}return this.#i=n,t}refused(){return this.#i}#i=[];async list(){return[...this.#t.values()].flatMap((e)=>(this.#a(e)??[]).map((t)=>Dt(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>=__)return e;e.push({slug:Dt(t.name,n.name),summary:Lc(t.name,n)})}return e}explainUnresolved(e){let t=new Set,n=[];for(let r of e){let i=this.#t.get(r.split(jn)[0]??"");if(i===void 0||!r.includes(jn))continue;if(this.#a(i)!==void 0)continue;t.add(i.name),n.push(r)}return n.length===0?void 0:p_([...t],n,wi(this.#e))}async refresh(e,t){let n={...this.#s},r=[],i=[],s=0;for(let l of this.#t.values())try{let a=await this.#c(l).listTools(t),d=new Map((this.#a(l)??[]).map((f)=>[f.name,JSON.stringify(f)]));for(let f of a){let h=Dt(l.name,f.name);if(!e.includes(h))continue;if(s+=1,d.get(f.name)!==JSON.stringify(f))i.push(h)}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.#s=n,h_(this.#e,n),r.length>0)throw Rc(r.map((l)=>l.server.name).join(", "),r.map((l)=>l.server.url).join(", "),r.map((l)=>l.detail).join("; "));let o=new Set(await this.list()),c=e.filter((l)=>this.#t.has(l.split(jn)[0]??"")&&!o.has(l));return{fetched:s,missing:c,changed:i}}#c(e){let t=this.#o.get(e.name);if(t===void 0)t=new Mc({server:e.name,url:e.url,timeoutMs:e.timeoutMs,...this.#r===void 0?{}:{fetch:this.#r},headers:()=>{let n={};for(let[r,i]of Object.entries(e.headersEnv)){let s=this.#n[i];if(s===void 0||s==="")throw m_(e.name,r,i);n[r]=s}return n}}),this.#o.set(e.name,t);return t}#l(e,t){return{spec:{...b_(e.name,t,e.policyArgs[t.name]),...e.personal===!0?{personal:!0}:{}},handler:async(n,r)=>{let i=r.actingParticipant,s={...e.participantHeader===void 0||i==null?{}:{[e.participantHeader]:i.id},...e.turnHeader===void 0?{}:{[e.turnHeader]:r.turnId,...r.callId===void 0?{}:{[`${e.turnHeader}-Call`]:r.callId}}},o=await this.#c(e).callTool(t.name,n,s,r.signal);if(o.isError===!0)throw g_(e.name,t.name,Ic(o));return Ic(o)}}}}function vi(e,t){return new xc({dir:e.dir,env:e.env,servers:k_(e.config),...t===void 0?{}:{fetch:t}})}var S_="0.1.0",Dc={name:"mcp",version:S_,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)=>vi(t))}};import{mkdirSync as $_}from"node:fs";import{join as jc,resolve as T_}from"node:path";import{readFile as E_}from"node:fs/promises";import{join as A_}from"node:path";import{tmpdir as q_}from"node:os";import{join as W_}from"node:path";import{spawnSync as tk}from"node:child_process";import{join as nk}from"node:path";import{mkdir as ck,realpath as lk,rm as Wc,stat as uk}from"node:fs/promises";import{dirname as dk,isAbsolute as fk,join as hk,resolve as Si}from"node:path";import{open as pl}from"node:fs/promises";import{existsSync as vk,realpathSync as bk}from"node:fs";import{homedir as Jc}from"node:os";import{isAbsolute as gl,relative as _k,resolve as Ut,sep as kk}from"node:path";import{spawn as Ak}from"node:child_process";import{mkdir as Ok,open as Nk,readFile as Ik}from"node:fs/promises";import{mkdir as Yk,readFile as Sl,realpath as Xk,stat as $l,writeFile as Tl}from"node:fs/promises";import{dirname as Qk,isAbsolute as e0,resolve as Yc}from"node:path";import{isAbsolute as t0,relative as n0,resolve as r0,sep as El}from"node:path";import{readFile as p0}from"node:fs/promises";import{readdir as m0}from"node:fs/promises";import{join as g0,relative as y0,sep as el}from"node:path";import{statSync as E0}from"node:fs";import{mkdir as A0,rm as sl}from"node:fs/promises";import{delimiter as O0,join as zn}from"node:path";function O_(){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 N_(e,t){return new B({code:"exec_workdir_missing",message:`The directory to run in does not exist: ${e}`,hint:t?"This is where a previous exec call left the shell, and it has since been removed or renamed. The remembered directory has been cleared, so the next call starts from the agent's own directory; pass workdir to choose a different one.":"workdir must name a directory that already exists. A relative path is resolved against the directory the last exec call ended in, the way a shell would.",field:"workdir"})}function I_(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 Uc(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 C_(){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 ol(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 P_(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 R_(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 M_(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 L_(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 x_(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 D_(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 j_(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 U_(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 z_(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 al(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 F_(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 B_(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 zc(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 Fc(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 K_(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.`})}function cl(e){return new S({code:"exec_confine_unavailable",message:`Commands cannot run here: this agent is confined to its own directory, and ${e}.`,hint:"Use the file tools instead, which are confined without the kernel's help. Whoever runs this agent needs Linux with Landlock (5.13 or later) and python3, or to remove tools.providers.system.confine."})}var Le="system";function ll(){return W_(q_(),`${V.slug}-${Le}`)}var Bc=sA.filter((e)=>e.agentListed),Kc="(hidden by the operator)",Z_=new Set(["id","api","baseurl","options","apikeyenv"]),J_=new Set(["model","provider","baseurl","options","apikeyenv"]);function bi(e){return e.getIn(["context","modelIdentity"])==="hidden"}function Fn(e,t){let n=e.map((r)=>r.toLowerCase());if(n[0]==="model"&&n.slice(2).some((r)=>Z_.has(r)))return Kc;if(n[0]==="media"&&n[2]!==void 0&&J_.has(n[2]))return Kc;if(Array.isArray(t))return t.map((r,i)=>Fn([...e,String(i)],r));if(typeof t==="object"&&t!==null)return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,Fn([...e,r],i)]));return t}function qc(e,t){let n=e.toLowerCase(),r="who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line",i="where the API listens, and what authenticates it, is not yours to decide — the same reason writeRoots is refused. Enabling it on 127.0.0.1 is settable; binding anywhere reachable is a person's call",s="widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(n.split(".").includes("writeroots"))return"widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(n.startsWith("tools.providers")&&me(t,"writeroots"))return"widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";let o="what your commands can see of the environment is not yours to widen. The scrub keeps the runtime's credentials out of anything you run; a person lists a variable your commands need",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")&&me(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"&&me(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")&&me(t,"confinereads"))return a;let d="where your commands may reach is not yours to widen. A person sets tools.providers.system.confine";if(n.startsWith("tools.providers")&&n.split(".").includes("confine"))return d;if(n.startsWith("tools.providers")&&me(t,"confine"))return d;let f="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 f;if(n.startsWith("tools.providers")&&me(t,"personal"))return f;if(n.startsWith("tools.providers")&&n.split(".").includes("env"))return o;if(n.startsWith("tools.providers")&&me(t,"env"))return o;if(n.split(".").includes("allowfrom"))return"who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line";if(n==="channels"&&me(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"&&(me(t,"host")||me(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 me(e,t){if(Array.isArray(e))return e.some((n)=>me(n,t));if(typeof e!=="object"||e===null)return!1;return Object.entries(e).some(([n,r])=>n.toLowerCase()===t||me(r,t))}function ul(e){return e.file??A_(e.agentDir,"agent.yaml")}var H_={slug:"config_read",provider:Le,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."}}}},dl={slug:"config_set",provider:Le,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 V_(e){try{return go(e)}catch(t){throw B_(e,t instanceof Error?t.message:String(t))}}function G_(e){return async(t)=>{let n=ul(e),r;try{r=await E_(n,"utf8")}catch(d){throw al(n,String(d))}let i=typeof t.path==="string"?t.path.trim():"";if(i!==""){let d=X(r),f=d.getIn(i.split("."),!1);if(f===void 0)return`${i} is not set in this configuration. It can be — see config_read with no path for the full list.`;let h=ht(f)||Ot(f)?f.toJS(d):f,u=bi(d)?Fn(i.split("."),h):h;return`${i}:
|
|
257
|
+
${hn(u).trimEnd()}`}let s=X(r),o=s.getIn(["tools","policy"],!1),c={...Ns,...ht(o)?o.toJS(s):{}},l=Bc.filter((d)=>Ms(c,{slug:dl.slug,match:d.path}).effect==="deny"),a=Bc.filter((d)=>!l.includes(d)).map((d)=>{let f=s.getIn(d.path.split("."),!1),h=ht(f)||Ot(f)?f.toJS(s):f,u=bi(s)?Fn(d.path.split("."),h):h,p=u===void 0||u===null?"(not set)":Array.isArray(u)?`[${u.map((g)=>typeof g==="object"&&g!==null?JSON.stringify(g):String(g)).join(", ")}]`:hn(u).trim(),m=d.toAgent===void 0?d.means:`${d.means}. ${d.toAgent}`;return`- ${d.path} = ${p}
|
|
258
|
+
${m}`}).join(`
|
|
259
|
+
`);return[`This agent is ${s.get("name")??s.get("id")}, configured at ${n}.`,"","Settings config_set can change, with their current values:",a===""?"(none: whoever runs you keeps every setting)":a,"",...l.length===0?[]:[`Kept by whoever runs you, so not settable from a conversation: ${l.map((d)=>d.path).join(", ")}. If one needs changing, say what and why, and they change it.`,""],...Y_(s),"Anything not on this list is not settable from a conversation. A change takes effect when the agent next starts, not in the current conversation.","","Some edits are refused whatever the rules say. Removing a check: replacing tools.policy.deny, or setting tools.untrusted.onMutate to allow. Deciding reach: a writeRoots list anywhere, the system provider's env, confineReads or confine, 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.","",...bi(s)?[]:[`The whole file, comments and all, is at ${n} — read it with file_read if that tool is enabled, or ask the person to open it.`]].join(`
|
|
260
|
+
`)}}function Y_(e){let t=(r)=>{let i=e.getIn(r,!1),s=ht(i)||Ot(i)?i.toJS(e):i;if(Array.isArray(s))return s.map(String);return typeof s==="string"&&s!==""?[s]:[]},n=[["context.soul.file",t(["context","soul","file"])],["context.static",t(["context","static"])],["context.files",t(["context","files"])],["context.volatile",t(["context","volatile"])],["context.reminder",t(["context","reminder"])]].filter(([,r])=>r.length>0).map(([r,i])=>`- ${r} = [${i.join(", ")}]`);if(n.length===0)return[];return["Context files (read-only here). These files are loaded into my instructions every turn, under their names, so I never need to read them; volatile ones only in private conversations:",...n,""]}function X_(e){return async(t,n)=>{let r=ul(e),i=typeof t.path==="string"?t.path.trim():"",s=typeof t.value==="string"?t.value:String(t.value??""),o=qc(i);if(o!==void 0)throw Fc(i,o);if(!Ai.includes(i))throw F_(i,Ai);let c=V_(s),l=qc(i,c);if(l!==void 0)throw Fc(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(_(u)&&u.code==="manifest_edit_unreadable")throw al(r,String(u.cause??u.message));if(_(u)&&u.code==="manifest_edit_invalid"){let p=u.message.slice(u.message.indexOf(": ")+2);throw zc(i,s,p)}if(_(u))throw zc(i,s,`${u.message} ${u.hint??""}`.trim());throw u}let d=a.before!==void 0,f=i==="tools.pinned"&&Array.isArray(c)&&n.pinTools!==void 0?await n.pinTools(c.map(String)):void 0,h=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}.`,d?`It was: ${hn(a.before).trim()}`:"It was not set before.",`It is now: ${hn(c).trim()}`,"",h,...Q_(a.manifest,c)].join(`
|
|
261
|
+
`)}}function Q_(e,t){if(!me(t,"tokenenv")&&!me(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 ek(e){return[{spec:H_,handler:G_(e)},{spec:dl,handler:X_(e)}]}var rk=String.raw`
|
|
262
|
+
import ctypes, os, sys
|
|
263
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
264
|
+
def die(why):
|
|
265
|
+
sys.stderr.write("dispach-confine: " + why + "\n"); sys.exit(125)
|
|
266
|
+
abi = libc.syscall(444, None, 0, 1)
|
|
267
|
+
if abi < 1: die("Landlock is not available: " + os.strerror(ctypes.get_errno()))
|
|
268
|
+
FS = (1 << 13) - 1
|
|
269
|
+
if abi >= 2: FS |= 1 << 13
|
|
270
|
+
if abi >= 3: FS |= 1 << 14
|
|
271
|
+
FILE = (1 << 0) | (1 << 1) | (1 << 2) | (FS & (1 << 14))
|
|
272
|
+
READ = (1 << 0) | (1 << 2) | (1 << 3)
|
|
273
|
+
class Attr(ctypes.Structure): _fields_ = [("fs", ctypes.c_uint64)]
|
|
274
|
+
class Rule(ctypes.Structure):
|
|
275
|
+
_pack_ = 1
|
|
276
|
+
_fields_ = [("allowed", ctypes.c_uint64), ("fd", ctypes.c_int32)]
|
|
277
|
+
attr = Attr(FS)
|
|
278
|
+
rs = libc.syscall(444, ctypes.byref(attr), ctypes.sizeof(attr), 0)
|
|
279
|
+
if rs < 0: die("could not create a ruleset: " + os.strerror(ctypes.get_errno()))
|
|
280
|
+
def allow(path, rights):
|
|
281
|
+
try: fd = os.open(path, os.O_PATH | os.O_CLOEXEC)
|
|
282
|
+
except OSError: return
|
|
283
|
+
if not os.path.isdir(path): rights &= FILE
|
|
284
|
+
rule = Rule(rights, fd)
|
|
285
|
+
ok = libc.syscall(445, rs, 1, ctypes.byref(rule), 0)
|
|
286
|
+
os.close(fd)
|
|
287
|
+
if ok != 0: die("could not allow " + path + ": " + os.strerror(ctypes.get_errno()))
|
|
288
|
+
split = sys.argv.index("--")
|
|
289
|
+
for path in ["/usr", "/bin", "/sbin", "/lib", "/lib64", "/etc", "/opt", "/proc", "/sys"]:
|
|
290
|
+
allow(path, READ)
|
|
291
|
+
for path in ["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom", "/dev/tty", "/dev/ptmx", "/dev/pts"]:
|
|
292
|
+
allow(path, FS)
|
|
293
|
+
for path in sys.argv[1:split]: allow(path[2:], READ) if path.startswith("r:") else allow(path, FS)
|
|
294
|
+
if libc.prctl(38, 1, 0, 0, 0) != 0: die("could not set no_new_privs")
|
|
295
|
+
if libc.syscall(446, rs, 0) != 0: die("could not restrict: " + os.strerror(ctypes.get_errno()))
|
|
296
|
+
os.execvp(sys.argv[split + 1], sys.argv[split + 1:])
|
|
297
|
+
`;function Kn(e){return nk(e,".tmp")}function ik(e,t,n){return{file:"python3",args:["-I","-c",rk,...e.writable,...(e.readable??[]).map((r)=>`r:${r}`),"--",t,...n]}}var _t=null;function fl(){if(_t!==null)return _t;if(process.platform!=="linux")return _t=`this runs on ${process.platform}, and Landlock is Linux's`,_t;let e=tk("python3",["-I","-c","import ctypes;l=ctypes.CDLL(None);print(l.syscall(444,None,0,1))"],{encoding:"utf8",timeout:5000}),t=Number(e.stdout?.trim());return _t=e.error!==void 0?`python3 could not be started (${e.error.message})`:Number.isInteger(t)&&t>=1?void 0:"the kernel has no Landlock, or it is switched off",_t}var sk=["PATH","HOME","USER","LOGNAME","SHELL","LANG","LANGUAGE","TZ","TERM","TMPDIR"],ok=/^[A-Za-z_][A-Za-z0-9_]*$/;function ak(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"&&ok.test(t)))return{scrub:!0,pass:e};throw new B({code:"system_env_invalid",message:`tools.providers.system.env is ${JSON.stringify(e)}, which is none of inherit, scrub or a list of variable names.`,hint:"Write `env: scrub` to give commands only PATH, HOME, the locale and the like, or `env: [GITHUB_TOKEN]` to scrub and pass those names too. Omit it (or `inherit`) to keep handing commands the whole environment.",field:"tools.providers.system.env"})}function hl(e,t){if(t==="inherit")return e;let n=new Set([...sk,...t.pass]);return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)||r.startsWith("LC_")))}var pk=6000,mk=3000,Zc=1500,gk=new TextDecoder("utf-8");async function _i(e,t,n){let r=await pl(e,"r");try{let i=new Uint8Array(n),{bytesRead:s}=await r.read(i,0,n,t);return gk.decode(i.subarray(0,s))}finally{await r.close()}}async function ml(e){let t=await pl(e,"r"),n;try{n=(await t.stat()).size}finally{await t.close()}if(n<=pk)return{head:jt(await _i(e,0,n)),tail:"",bytes:n,spilled:!1};return{head:jt(await _i(e,0,mk)),tail:jt(await _i(e,n-Zc,Zc)),bytes:n,spilled:!0}}function yk(e){return e.replace(/^(?:\^[A-Z?]\s*)+/,"")}function wk(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Sk(e){if(e==="~")return Jc();return e.startsWith("~/")?Ut(Jc(),e.slice(2)):e}var $k="workspace";function yl(e,t=[],n=!1){let r=Ut(e),i=Ut(r,$k);return{primary:vk(i)?i:r,extra:t.map((s)=>gl(s)?Ut(s):Ut(r,s)),confineReads:n}}function Hc(e){try{return bk(e)}catch{return e}}function wl(e,t){if(!t.confineReads)return;let n=Hc(e);if(zt(t).some((r)=>vl(n,Hc(r))))return;throw z_(e,zt(t))}function vl(e,t){if(e===t)return!0;let n=_k(t,e);return n!==""&&!n.startsWith(`..${kk}`)&&n!==".."&&!gl(n)}function zt(e){return[e.primary,...e.extra]}function Tk(e,t){return zt(t).some((n)=>vl(e,n))}function Ek(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 ${zt(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 Ei(e,t,n,r=e.mutating?"write":"read"){let i={...e.parameters.properties};for(let s of n){let o=i[s];if(o===void 0)continue;i[s]={...o,description:`${o.description??""}${Ek(t,r)}`}}return{...e,parameters:{...e.parameters,properties:i}}}var ot=new Map,Ck=8;function Pk(){return[...ot.entries()].map(([e,t])=>({pid:e,...t})).sort((e,t)=>t.since-e.since)}function Rk(){let e=[];for(let[t,n]of ot)try{process.kill(-t,"SIGTERM"),e.push(`${t} (${n.command})`)}catch{}return ot.clear(),e}function Mk(){for(let e of[...ot.keys()])try{process.kill(e,0)}catch{ot.delete(e)}}var Lk=250,Vc=2000,xk=new Set(["sleep","git","ssh","scp","sudo","su","doas"]);function Dk(e){for(let t of e.split(/\s+/)){if(/^[A-Za-z_]\w*=/.test(t))continue;return t.replace(/^.*\//,"").toLowerCase()}return""}function jk(e){let t=$r(e);if(t.length===0)return!1;return t.every((n)=>!xk.has(Dk(n)))}function bl(e){return`'${e.replaceAll("'","'\\''")}'`}function Uk(e,t){return[e,"__code=$?",`{ printf '%s\\n' "$__code"; pwd; } > ${bl(t)} 2>/dev/null`,"exit $__code"].join(`
|
|
298
|
+
`)}function zk(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 ${bl(e)}`,"/dev/null"],env:{SHELL:"/bin/sh"}};return{file:"script",args:["-q","/dev/null","/bin/sh","-c",e],env:{SHELL:"/bin/sh"}}}function Un(e,t){let n=e.pid;if(n===void 0)return;try{process.kill(-n,t)}catch{}}async function Fk(e){try{let[t,n]=(await Ik(e,"utf8")).split(`
|
|
299
|
+
`),r=Number.parseInt(t??"",10),i=n?.trim();return{...Number.isNaN(r)?{}:{code:r},...i===void 0||i===""?{}:{cwd:i}}}catch{return{}}}async function _l(e){if(Mk(),ot.size>=Ck)throw K_(Pk().map((f)=>f.command));let t=Uk(e.command,e.statusPath),n=zk(t,e.pty),{file:r,args:i}=e.confine===void 0?n:ik(e.confine,n.file,n.args),s=e.confine===void 0?void 0:Kn(e.confine.agentDir);if(s!==void 0)await Ok(s,{recursive:!0});let o=s===void 0?n.env:{...n.env,TMPDIR:s,HOME:s},c=await Nk(e.outPath,"w"),l;try{l=Ak(r,i,{cwd:e.cwd,env:{...e.env,...o},stdio:["ignore",c.fd,c.fd],detached:!0})}catch(f){throw await c.close(),Uc(e.command,String(f))}let a=await new Promise((f,h)=>{let u=!1,p=!1,m=setTimeout(y,e.background?Lk:e.timeoutMs),g=(v)=>{if(u)return;u=!0,clearTimeout(m),e.signal.removeEventListener("abort",w),f(v)};function y(){if(e.background||jk(e.command)){if(l.unref(),l.pid!==void 0)ot.set(l.pid,{command:e.command,since:Date.now(),outPath:e.outPath});g({ending:"backgrounded",...l.pid===void 0?{}:{pid:l.pid}});return}p=!0,Un(l,"SIGTERM"),setTimeout(()=>Un(l,"SIGKILL"),Vc).unref?.()}function w(){Un(l,"SIGTERM"),setTimeout(()=>Un(l,"SIGKILL"),Vc).unref?.()}e.signal.addEventListener("abort",w,{once:!0}),l.on("error",(v)=>{if(u)return;u=!0,clearTimeout(m),e.signal.removeEventListener("abort",w),h(e.pty&&Bk(v)?I_(process.platform,String(v)):Uc(e.command,String(v)))}),l.on("exit",(v,T)=>{g({ending:p?"killed":"finished",...v===null?{}:{code:v},...T===null?{}:{killedBy:T},...l.pid===void 0?{}:{pid:l.pid}})})}).finally(()=>c.close()),d=await Fk(e.statusPath);return{...a,...d.code===void 0?{}:{code:d.code},...d.cwd===void 0?{}:{cwdAfter:d.cwd}}}function Bk(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}var Bn=120000,kl=600000,Kk=5000,qk={slug:"exec",provider:Le,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 ${Bn}, maximum ${kl}.`,default:Bn},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 Wk(e,t){let n=e===void 0||e<=0?Bn:e,r=Math.min(n,kl),i=t-Kk;return Math.max(1,Math.min(r,i>0?i:Math.floor(t*0.8)))}function Gc(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function Zk(e,t,n){let r=n===void 0?ll():hk(Kn(n.agentDir),"spill");return{out:Si(r,`${e.turnId}-${t}.log`),status:Si(r,`${e.turnId}-${t}.status`)}}function Jk(e){return async(t,n)=>{let r=typeof t.command==="string"?t.command.trim():"";if(e.confine!==void 0){let y=fl();if(y!==void 0)throw cl(y)}if(r==="")throw O_();let i=e.sessions.lastCwd(n.sessionKey),s=i??e.roots.primary,o=typeof t.workdir==="string"?t.workdir.trim():"",c=o===""?s:fk(o)?o:Si(s,o),l;try{if(l=await lk(c),!(await uk(l)).isDirectory())throw Error("not a directory")}catch{let y=o===""&&i!==void 0;if(y)e.sessions.forget(n.sessionKey);throw N_(c,y)}let a=Wk(Gc(t.timeoutMs),n.deadlineMs),d=Gc(t.timeoutMs),f=d!==void 0&&d!==Bn&&a<d,h=t.background===!0,u=Zk(n,Hk(r,n.turnId),e.confine);await ck(dk(u.out),{recursive:!0});let p=await _l({command:r,cwd:l,env:e.env,timeoutMs:a,pty:t.pty===!0,background:h,signal:n.signal,outPath:u.out,statusPath:u.status,...e.confine===void 0?{}:{confine:e.confine}});if(p.cwdAfter!==void 0)e.sessions.remember(n.sessionKey,p.cwdAfter);let m=await ml(u.out),g=t.pty===!0?{...m,head:yk(m.head)}:m;if(await Wc(u.status,{force:!0}),!g.spilled&&p.ending!=="backgrounded")await Wc(u.out,{force:!0});return Vk({command:r,cwd:l,run:p,observation:g,clamped:f,timeoutMs:a,path:u.out})}}function Hk(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 Vk(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,ki("Output so far",e.observation.head)].join(`
|
|
300
|
+
|
|
301
|
+
`);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 ${wk(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(ki("First part of the output",e.observation.head)),n)r.push(ki("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(`
|
|
302
|
+
|
|
303
|
+
`)}function ki(e,t){return`${e}:
|
|
304
|
+
${t.trimEnd()}`}function Gk(e){return{spec:Ei(qk,e.roots,["command","workdir"],"shell"),handler:Jk(e)}}var i0=["agent.yaml","agent.yml","SOUL.md","SOUL.compact.md","AGENTS.md","POLICY.md","REMINDER.md"],Al=[".ssh",".aws",".kube",".gnupg",".docker"],Ol=/^(?:\.env(\..+)?|\.netrc|\.npmrc|\.pypirc|id_[a-z0-9]+|.*\.pem|.*\.key)$/i;function Nl(e){return e.split(El).filter((t)=>t!=="")}function $i(e){let t=Nl(e),n=t[t.length-1]??"";for(let r of Al)if(t.includes(r))return`${r}/ holds credentials`;if(Ol.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 s0(e,t){let n=Nl(e),r=n[n.length-1]??"";for(let c of Al)if(n.includes(c))return`${c}/ holds credentials, and nothing under it is writable by an agent`;if(Ol.test(r))return`${r} holds secrets — the manifest names environment variables, and their values are not the agent's to edit`;let i=r0(t.agentDir),s=n0(i,e);if(s!==""&&!s.startsWith("..")&&!t0(s)){let c=s.split(El),l=c[c.length-1]??"";if(i0.includes(l))return`${s} is part of this agent's own definition — who it is, what it does, or what it is permitted to do — and it is not editable from inside a turn`;if(c[0]?.startsWith(".")===!0)return`${s} 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 Xc=2000000,Ti=400;function o0(e){return e.subarray(0,8000).includes(0)}var a0={slug:"file_read",provider:Le,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 ${Ti}.`,default:Ti}},required:["path"]}},c0={slug:"file_write",provider:Le,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"]}},l0={slug:"file_edit",provider:Le,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 qn(e,t,n,r){let i=Sk(typeof e==="string"?e.trim():"");if(i==="")throw C_();let s=t.lastCwd(n)??r;return e0(i)?Yc(i):Yc(s,i)}function Il(e,t){if(!Tk(e,t.roots))throw U_(e,zt(t.roots));let n=s0(e,{agentDir:t.agentDir,...t.protect===void 0?{}:{extra:t.protect}});if(n!==void 0)throw L_(e,n)}function Qc(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function u0(e){return async(t,n)=>{let r=qn(t.path,e.sessions,n.sessionKey,e.roots.primary);wl(r,e.roots);let i=$i(await Xk(r).catch(()=>r))??$i(r);if(i!==void 0)throw M_(r,i);let s;try{s=(await $l(r)).size}catch{throw ol(r)}if(s>Xc)throw P_(r,s,Xc);let o=await Sl(r);if(o0(o))throw R_(r,s);let l=jt(o.toString("utf8")).split(`
|
|
305
|
+
`),a=Math.max(1,Qc(t.offset)??1),d=Math.max(1,Qc(t.limit)??Ti),f=l.slice(a-1,a-1+d);if(f.length===0)return`${r} has ${l.length} lines, so there is nothing at line ${a}.`;let h=f.join(`
|
|
306
|
+
`),u=a-1+f.length;if(a===1&&u>=l.length)return h;return`Lines ${a}-${u} of ${l.length} in ${r}:
|
|
307
|
+
${h}`}}function d0(e){return async(t,n)=>{let r=qn(t.path,e.sessions,n.sessionKey,e.roots.primary);Il(r,e);let i=typeof t.content==="string"?t.content:String(t.content??""),s=await $l(r).then(()=>!0,()=>!1);await Yk(Qk(r),{recursive:!0}),await Tl(r,i,"utf8");let o=i===""?0:i.split(`
|
|
308
|
+
`).length;return`${s?"Replaced":"Created"} ${r} — ${o} line${o===1?"":"s"}, ${i.length} characters.`}}function f0(e){return async(t,n)=>{let r=qn(t.path,e.sessions,n.sessionKey,e.roots.primary);Il(r,e);let i=typeof t.find==="string"?t.find:"",s=typeof t.replace==="string"?t.replace:"",o;try{o=await Sl(r,"utf8")}catch{throw ol(r)}let c=i===""?0:o.split(i).length-1;if(c===0)throw x_(r,i);if(c>1&&t.all!==!0)throw D_(r,c);let l=t.all===!0?o.split(i).join(s):o.replace(i,s);await Tl(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(`
|
|
309
|
+
`).length} lines.`}}function h0(e){let t=(n)=>Ei(n,e.roots,["path"]);return[{spec:t(a0),handler:u0(e)},{spec:t(c0),handler:d0(e)},{spec:t(l0),handler:f0(e)}]}var w0=new Set(["node_modules",".git",".hg",".svn","dist","build","out",".next",".turbo",".cache","coverage","__pycache__",".venv","venv","target","vendor"]);function Cl(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 v0(e){return el==="/"?e:e.split(el).join("/")}async function Pl(e,t){let n=[],r=[e];while(r.length>0){let i=r.shift();if(i===void 0)break;let s;try{s=await m0(i,{withFileTypes:!0})}catch{continue}for(let o of s){let c=g0(i,o.name);if(o.isDirectory()){if(w0.has(o.name))continue;if(t.hidden!==!0&&o.name.startsWith("."))continue;r.push(c);continue}if(!o.isFile())continue;if(t.hidden!==!0&&o.name.startsWith("."))continue;let l=v0(y0(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 tl=200,nl=100,b0=1e6,_0={slug:"glob",provider:Le,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"]}},k0={slug:"grep",provider:Le,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 Rl(e,t,n){let r=typeof e.path==="string"&&e.path.trim()!==""?e.path:".",i=qn(r,t.sessions,n,t.roots.primary);return wl(i,t.roots),i}function S0(e){return async(t,n)=>{let r=typeof t.pattern==="string"?t.pattern.trim():"",i=Rl(t,e,n.sessionKey),s=Cl(r),o=await Pl(i,{limit:tl,...t.hidden===!0?{hidden:!0}:{},accept:(l)=>s.test(l)});if(o.files.length===0)return`No file under ${i} matches ${r}. Directories like node_modules, .git and dist are never searched${t.hidden===!0?"":", and dot-files are skipped unless hidden is true"}.`;return`${o.truncated?`The first ${o.files.length} of more than ${tl} matches for ${r} under ${i} — narrow the pattern to see the rest:`:`${o.files.length} match${o.files.length===1?"":"es"} for ${r} under ${i}:`}
|
|
310
|
+
${o.files.join(`
|
|
311
|
+
`)}`}}function $0(e){return async(t,n)=>{let r=typeof t.pattern==="string"?t.pattern:"",i=Rl(t,e,n.sessionKey),s;try{s=new RegExp(r,t.ignoreCase===!0?"i":"")}catch(h){throw j_(r,String(h))}let o=typeof t.glob==="string"&&t.glob.trim()!==""?Cl(t.glob.trim()):void 0,c=await Pl(i,{limit:5000,...o===void 0?{}:{accept:(h)=>o.test(h)}}),l=[],a=0,d=!1;for(let h of c.files){if(l.length>=nl){d=!0;break}if($i(`${i}/${h}`)!==void 0)continue;let u;try{let m=await p0(`${i}/${h}`);if(m.length>b0||m.subarray(0,8000).includes(0))continue;u=m.toString("utf8")}catch{continue}a+=1;let p=u.split(`
|
|
312
|
+
`);for(let m=0;m<p.length;m+=1){let g=p[m]??"";if(!s.test(g))continue;if(l.length>=nl){d=!0;break}let y=g.length>300?`${g.slice(0,300)}…`:g;l.push(`${h}:${m+1}: ${jt(y).trim()}`)}}if(l.length===0)return`Nothing under ${i} matches ${r}${o===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`${d?`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:`}
|
|
313
|
+
${l.join(`
|
|
314
|
+
`)}`}}function T0(e){let t=(n)=>Ei(n,e.roots,["path"]);return[{spec:t(_0),handler:S0(e)},{spec:t(k0),handler:$0(e)}]}class Ml{#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 rl(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}class Ll{id=Le;#e=new Ml;#n;constructor(e){let t=yl(e.dir,e.writeRoots??[],e.confineReads===!0||!!e.confine),n=e.confine?xl(e.dir,t,e.confine==="workspace"?"workspace":"agent"):void 0,r={sessions:this.#e,agentDir:e.dir,roots:t,...e.protect===void 0?{}:{protect:e.protect}};this.#n=[Gk({sessions:this.#e,env:e.env,roots:t,...n===void 0?{}:{confine:n}}),...h0(r),...T0({sessions:this.#e,roots:t}),...ek({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(rl));return Promise.resolve(this.#n.filter((n)=>t.has(rl(n.spec.slug))))}stop(){return Promise.resolve(Rk())}list(){return Promise.resolve(this.#n.map((e)=>e.spec.slug))}}var il=["protect","writeRoots","env","confineReads","confine"];function xl(e,t,n="agent"){let r=T_(e);if(n==="agent")return{agentDir:r,writable:[r,...t.extra]};let i=Kn(r);return $_(i,{recursive:!0}),{agentDir:r,writable:[jc(r,"workspace"),i,...t.extra],readable:[jc(r,"skills")]}}function Oi(e,t){let n=Object.keys(e.config).filter((d)=>!il.includes(d));if(n.length>0)throw new B({code:"system_config_unknown",message:`tools.providerConfig has ${n.length===1?"a key":"keys"} the system provider does not read: ${n.join(", ")}.`,hint:`Accepted keys are ${il.join(", ")} — extra paths the file tools refuse to write, and extra directories they may write. Refused rather than ignored, because a protection that looks applied and is not is worse than a rejected manifest.`,field:"tools.providerConfig"});let r=e.config.protect,i=e.config.writeRoots,s=e.config.confineReads;if(s!==void 0&&typeof s!=="boolean")throw new B({code:"system_config_invalid",message:"tools.providers.system.confineReads must be true or false.",hint:"true confines file_read, glob and grep to the agent's directory and its writeRoots; false, or leaving it out, keeps reads unconfined as before.",field:"tools.providers.system.confineReads"});let o=e.config.confine;if(o!==void 0&&o!=="agent"&&o!=="workspace")throw new B({code:"system_config_invalid",message:`tools.providers.system.confine is ${JSON.stringify(o)}; the values are agent and workspace.`,hint:"confine: agent runs every command inside the agent's own directory (Linux with Landlock), confines reads, and scrubs the environment; confine: workspace narrows that to the agent's workspace, so its .env and channel sessions are out of reach. Leave it out for an agent that may use the whole machine.",field:"tools.providers.system.confine"});let c=ak(e.config.env),l=o!==void 0&&c==="inherit"?{scrub:!0,pass:[]}:c,a=o==="agent"||o==="workspace"?xl(e.dir,yl(e.dir,Array.isArray(i)?i.map(String):[],!0),o):void 0;return t?.(l,a),new Ll({env:hl(e.env,l),dir:e.dir,...e.providers===void 0?{}:{providers:e.providers},...e.mediaProviders===void 0?{}:{mediaProviders:e.mediaProviders},...Array.isArray(r)?{protect:r.map((d)=>String(d))}:{},...Array.isArray(i)?{writeRoots:i.map((d)=>String(d))}:{},...s===!0?{confineReads:!0}:{},...o!==void 0?{confine:o}:{}})}function N0(e){return`'${e.replaceAll("'","'\\''")}'`}class Wn{#e;#n;#t;constructor(e){this.#e=e.env,this.#n=e.policy??(()=>"inherit"),this.#t=e.confine??(()=>{return})}has(e){let t=this.#e.PATH??process.env.PATH??"";for(let n of t.split(O0)){if(n==="")continue;try{let r=E0(zn(n,e));if(r.isFile()&&(r.mode&73)!==0)return!0}catch{}}return!1}async run(e){let t=this.#t();if(t!==void 0){let f=fl();if(f!==void 0)throw cl(f)}let n=t===void 0?ll():zn(Kn(t.agentDir),"spill");await A0(n,{recursive:!0});let r=I0([e.command,...e.args].join(" ")),i=zn(n,`skill-${r}.out`),s=zn(n,`skill-${r}.status`),o=[e.command,...e.args].map(N0).join(" "),c=await _l({command:o,cwd:e.cwd,env:hl(this.#e,this.#n()),timeoutMs:e.timeoutMs,pty:!1,background:!1,signal:e.signal,outPath:i,statusPath:s,...t===void 0?{}:{confine:t}}),l=await ml(i);if(await sl(s,{force:!0}),!l.spilled&&c.ending!=="backgrounded")await sl(i,{force:!0});let a=c.ending==="killed"||c.ending==="backgrounded",d=l.spilled?`${l.head}
|
|
315
|
+
|
|
316
|
+
… ${l.bytes} bytes in total; the rest is at ${i}
|
|
317
|
+
|
|
318
|
+
${l.tail}`:l.head;return{ok:c.ending==="finished"&&c.code===0,output:c.ending==="backgrounded"?`${d}
|
|
319
|
+
|
|
320
|
+
Still running past ${e.timeoutMs} ms, left going rather than discarded. Output continues to accumulate at ${i}.`:d,...c.code===void 0?{}:{code:c.code},timedOut:a}}}function I0(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 C0="0.1.0",Dl={name:"system",version:C0,dispachApi:"^0.2",permissions:[{kind:"exec",commands:["*"]},{kind:"fs",paths:["<workspace>"],mode:"write"}],setup(e){let t="inherit",n;e.defineToolProvider("system",(r)=>Oi(r,(i,s)=>{t=i,n=s})),e.defineScriptRunner(new Wn({env:e.env,policy:()=>t,confine:()=>n}))}};import{lookup as X0}from"node:dns/promises";function jl(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 P0(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 R0(){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 Ni(e,t,n,r,i){let s=t===e?t:`${e} → ${t}`;return new S({code:"web_address_refused",message:`${s} is ${n}${r===void 0?"":` (${r})`} and will not be fetched${i>0?`, reached by redirect ${i}`:""}.`,hint:"This is a standing rule with no setting that overrides it. Addresses off the public internet — loopback, link-local, private and carrier-grade NAT ranges — include the cloud metadata endpoint and every service on this machine, so a page that can make this tool fetch one is a page that can read them. Nothing was requested. If the page is genuinely public, check the hostname.",field:"url"})}function Zn(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 Ul(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 zl(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 Jl(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 Fl(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 M0(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 L0(e,t){return new B({code:"web_search_key_missing",message:`The ${e} search backend needs ${t} and it is not set.`,hint:`Set ${t} in the .env beside agent.yaml, or in the environment. The manifest names the variable and never holds the key — a manifest with a literal key fails validation.`,field:"tools.providers.web.apiKeyEnv"})}function x0(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 Pe(e,t){return new B({code:"web_config_invalid",message:`tools.providers.web.${e} ${t}`,hint:"Refused rather than defaulted around: a search backend silently different from the one configured returns different results with nothing reporting why.",field:`tools.providers.web.${e}`})}function D0(e){return new B({code:"web_firecrawl_key_missing",message:`Firecrawl needs ${e} and it is not set.`,hint:`Set ${e} in the .env beside agent.yaml, or in the environment (or ${e}_FILE naming a file that holds it). tools.providers.web.firecrawl.apiKeyEnv names a different variable if you need one.`,field:"tools.providers.web.firecrawl.apiKeyEnv"})}function j0(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 Bl=["tavily","brave","exa","firecrawl"];function te(e,t){return typeof e==="object"&&e!==null?e[t]:void 0}function ke(e){return typeof e==="string"?e:""}function Hn(e){return Array.isArray(e)?e:[]}var U0={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 Hn(te(e,"results")).map((t)=>({title:ke(te(t,"title")),url:ke(te(t,"url")),snippet:ke(te(t,"content"))}))}},z0={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 Hn(te(te(e,"web"),"results")).map((t)=>({title:ke(te(t,"title")),url:ke(te(t,"url")),snippet:ke(te(t,"description"))}))}},F0={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 Hn(te(e,"results")).map((t)=>({title:ke(te(t,"title")),url:ke(te(t,"url")),snippet:ke(te(t,"text"))||ke(te(t,"snippet"))}))}},B0={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 Hn(te(te(e,"data"),"web")).map((t)=>({title:ke(te(t,"title")),url:ke(te(t,"url")),snippet:ke(te(t,"description"))}))},units(e){let t=te(e,"creditsUsed");return typeof t==="number"&&Number.isFinite(t)?t:1}},K0={tavily:U0,brave:z0,exa:F0,firecrawl:B0};function Hl(e){return K0[e]}async function q0(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 x0(e,t.status,n)}var W0=["script","style","noscript","template","svg","canvas","iframe","head"],Z0=/<\/?(?: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,J0={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 Vl(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 J0[n.toLowerCase()]??t})}function H0(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(e);if(t===null)return;let n=Gl(Vl(t[1]??""));return n===""?void 0:n}function V0(e){let t=e;for(let n of W0)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(Z0,`
|
|
321
|
+
`),t=t.replace(/<[^>]*>/g," "),t=Vl(t),t.split(`
|
|
322
|
+
`).map((n)=>Gl(n)).filter((n,r,i)=>n!==""||(i[r-1]??"")!=="").join(`
|
|
323
|
+
`).trim()}function Gl(e){return e.replace(/\s+/g," ").trim()}function G0(e,t){let n=t.split(";")[0]?.trim().toLowerCase()??"";if(n.includes("html")||n.includes("xml")){let r=H0(e);return{text:V0(e),...r===void 0?{}:{title:r}}}return{text:e.trim()}}function Y0(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 Q0=new Set(["http:","https:"]),eS=[".local",".localhost",".internal",".intranet",".lan",".home.arpa"];function Yl(e){let t=e.trim();if(t==="")throw jl(e,"the value is empty");try{return new URL(t)}catch(n){throw jl(e,n instanceof Error?n.message:String(n))}}function tS(e){if(!Q0.has(e.protocol))throw P0(e.protocol.replace(":",""));if(e.username!==""||e.password!=="")throw R0();let t=e.hostname.toLowerCase();if(t==="")throw Zn(e.href,"there is no host in the URL");if(t==="localhost")throw Zn(t,"it is this machine by definition");for(let r of eS)if(t.endsWith(r))throw Zn(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 Zn(t,"a name with no dot in it is completed by the local search domain")}async function Xl(e,t,n=0){tS(e);let r=e.hostname.toLowerCase(),i=Qr(r);if(i!==void 0){if(i.kind!=="public")throw Ni(r,r,i.kind,i.range,n);return}let s;try{s=await t(r)}catch(o){throw Ul(r,o instanceof Error?o.message:String(o))}if(s.length===0)throw Ul(r,"it has no addresses");for(let{address:o}of s){let c=Qr(o);if(c===void 0)throw Ni(r,o,"an address this cannot classify",void 0,n);if(c.kind!=="public")throw Ni(r,o,c.kind,c.range,n)}}var nS=async(e)=>(await X0(e,{all:!0,verbatim:!0})).map((n)=>({address:n.address})),Bt="web",Ql=2000000,Ii=6000,Jn=5,rS=3000,iS=20000,eu={slug:"web_fetch",provider:Bt,summary:"Reads one web page and returns its text.",whenToUse:"you have a specific URL — from the person, from a search result, from a document — and need what is actually on that page rather than what you remember about it",whenNotToUse:"you do not have a URL yet, which is web_search; the address is on this machine or this network, which is refused; or you want a file from disk, which is file_read",mutating:!1,trust:"untrusted",policyArg:"url",tags:["read","web"],parameters:{type:"object",properties:{url:{type:"string",description:"The complete address of one page, including https://. Public internet only — addresses on this machine or this network are refused."}},required:["url"]}};function sS(e){return{spec:eu,handler:aS(e)}}function oS(e){let t=Math.max(1000,e-rS);return Math.min(iS,t)}function aS(e){let t=e.maxBytes??Ql;return async(n,r)=>{let i=String(n.url??""),s=Yl(i),o=new AbortController,c=()=>{o.abort()};r.signal.addEventListener("abort",c,{once:!0});let l=setTimeout(c,oS(r.deadlineMs));try{for(let a=0;a<=Jn;a+=1){await Xl(s,e.lookup,a);let d;try{d=await e.fetch(s.href,{method:"GET",redirect:"manual",signal:o.signal,headers:{"user-agent":e.userAgent,accept:"text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5","accept-language":"en"}})}catch(w){throw zl(s.href,w instanceof Error?w.message:String(w))}let f=d.headers.get("location");if(cS(d.status)&&f!==null){if(await d.body?.cancel().catch(()=>{return}),a===Jn)throw Fl(i,Jn);try{s=new URL(f,s)}catch{throw zl(s.href,`it redirected to an unusable address: ${f}`)}continue}if(!d.ok)throw await d.body?.cancel().catch(()=>{return}),Jl(s.href,d.status,d.statusText);let h=d.headers.get("content-type")??"";if(!Y0(h))throw await d.body?.cancel().catch(()=>{return}),M0(s.href,h.split(";")[0]?.trim()??"binary");let{text:u,read:p,capped:m}=await lS(d,t),{title:g,text:y}=G0(u,h);return tu({url:s.href,requested:i,...g===void 0?{}:{title:g},text:y,read:p,capped:m,hops:a})}throw Fl(i,Jn)}finally{clearTimeout(l),r.signal.removeEventListener("abort",c)}}}function cS(e){return e===301||e===302||e===303||e===307||e===308}async function lS(e,t){let n=e.body;if(n===null)return{text:"",read:0,capped:!1};let r=n.getReader(),i=new TextDecoder("utf-8"),s=[],o=0,c=!1;try{for(;;){let{done:l,value:a}=await r.read();if(l)break;if(a===void 0)continue;if(o+=a.byteLength,o>=t){let d=a.byteLength-(o-t);s.push(i.decode(a.subarray(0,Math.max(0,d)),{stream:!0})),c=!0;break}s.push(i.decode(a,{stream:!0}))}}finally{await r.cancel().catch(()=>{return})}return s.push(i.decode()),{text:s.join(""),read:Math.min(o,t),capped:c}}function tu(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>Ii)n=n.slice(0,Ii),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 ${Ii.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(`
|
|
324
|
+
`)}var uS="https://api.firecrawl.dev/v2",Ci=3000,nu=60000,dS=2000,fS=12000,hS=6000,ru=5,iu=20,su=100,ou=500;function J(e,t){return typeof e==="object"&&e!==null?e[t]:void 0}function ge(e){if(typeof e==="string")return e;if(Array.isArray(e)&&typeof e[0]==="string")return e[0];return""}function Pi(e,t){let n=J(e,"creditsUsed");return typeof n==="number"&&Number.isFinite(n)?n:t}async function Ft(e,t,n,r,i){let s=e.env[e.config.apiKeyEnv]??"";if(s==="")throw D0(e.config.apiKeyEnv);let o=await e.fetch(`${e.config.baseUrl??uS}${n}`,{method:r.method,headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},...r.body===void 0?{}:{body:JSON.stringify(r.body)},signal:i});if(!o.ok){let c=o.statusText;try{let l=await o.text(),a=ge(J(pS(l),"error"));c=a!==""?a:l.length>300?`${l.slice(0,300)}…`:l}catch{}throw j0(t,o.status,c)}return await o.json()}function pS(e){try{return JSON.parse(e)}catch{return}}function Ri(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-Ci)));return{signal:n.signal,done:()=>{clearTimeout(i),e.signal.removeEventListener("abort",r)}}}async function Mi(e,t){let n=Yl(e);return await Xl(n,t.lookup),n}function mS(e){return{spec:eu,handler:async(n,r)=>{let i=String(n.url??""),s=await Mi(i,e),o=Math.max(1000,Math.min(e.config.timeoutMs??nu,r.deadlineMs-2*Ci)),{signal:c,done:l}=Ri(r,o+Ci);try{let a=await Ft(e,"scrape","/scrape",{method:"POST",body:{url:s.href,formats:["markdown"],onlyMainContent:e.config.onlyMainContent,timeout:o,...e.config.maxAgeMs===void 0?{}:{maxAge:e.config.maxAgeMs}}},c);r.meter?.({provider:"firecrawl",operation:"scrape",unit:"credits",units:Pi(a,1)});let d=J(a,"data"),f=J(d,"metadata"),h=J(f,"statusCode"),u=ge(J(f,"url"))||ge(J(f,"sourceURL"))||s.href;if(typeof h==="number"&&h>=400)throw Jl(u,h,ge(J(f,"error")));let p=ge(J(f,"title")),m=ge(J(d,"markdown"));return tu({url:u,requested:i,...p===""?{}:{title:p},text:m,read:m.length,capped:!1,hops:u===s.href?0:1})}finally{l()}}}}var gS={slug:"web_map",provider:Bt,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 ${ou}.`,default:su}},required:["url"]}};function yS(e){return{spec:gS,handler:async(n,r)=>{let i=await Mi(String(n.url??""),e),s=String(n.search??"").trim(),o=au(n.limit,su,ou),{signal:c,done:l}=Ri(r,nu);try{let a=await Ft(e,"map","/map",{method:"POST",body:{url:i.href,limit:o,...s===""?{}:{search:s}}},c);r.meter?.({provider:"firecrawl",operation:"map",unit:"credits",units:Pi(a,1)});let d=(Array.isArray(J(a,"links"))?J(a,"links"):[]).map((m)=>typeof m==="string"?{url:m,title:""}:{url:ge(J(m,"url")),title:ge(J(m,"title"))}).filter((m)=>m.url!=="").slice(0,o);if(d.length===0)return`No addresses found on ${i.host}${s===""?"":` for ${JSON.stringify(s)}`}. The site may block crawlers or publish no sitemap; web_fetch on its home page is the other way in.`;let f=[],h=0;for(let m of d){let g=m.title===""?m.url:`${m.url} — ${m.title}`;if(h+g.length>hS)break;f.push(g),h+=g.length+1}let u=`${d.length} address${d.length===1?"":"es"} on ${i.host}${s===""?"":` for ${JSON.stringify(s)}`}:`,p=f.length<d.length?[`incomplete: only the first ${f.length} are shown; narrow it with search`]:[];return[u,...p,"",...f].join(`
|
|
325
|
+
`)}finally{l()}}}}var wS={slug:"web_crawl",provider:Bt,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 ${iu}.`,default:ru},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 vS(e){return{spec:wS,handler:async(n,r)=>{let i=await Mi(String(n.url??""),e),s=au(n.limit,ru,iu),o=Array.isArray(n.includePaths)?n.includePaths.map((d)=>String(d)).filter((d)=>d!==""):[],{signal:c,done:l}=Ri(r,Number.POSITIVE_INFINITY),a="";try{let d=await Ft(e,"crawl","/crawl",{method:"POST",body:{url:i.href,limit:s,...o.length===0?{}:{includePaths:o},scrapeOptions:{formats:["markdown"],onlyMainContent:e.config.onlyMainContent,...e.config.maxAgeMs===void 0?{}:{maxAge:e.config.maxAgeMs}}}},c);a=ge(J(d,"id"));let f={};while(!c.aborted){if(await bS(dS,c),c.aborted)break;try{f=await Ft(e,"crawl",`/crawl/${encodeURIComponent(a)}`,{method:"GET"},c)}catch(w){if(c.aborted)break;throw w}let y=ge(J(f,"status"));if(y==="completed"||y==="failed")break}let h=ge(J(f,"status")),u=(Array.isArray(J(f,"data"))?J(f,"data"):[]).map((y)=>({url:ge(J(J(y,"metadata"),"sourceURL"))||ge(J(J(y,"metadata"),"url")),markdown:ge(J(y,"markdown"))})).filter((y)=>y.markdown!=="");if(r.meter?.({provider:"firecrawl",operation:"crawl",unit:"credits",units:Pi(f,u.length)}),h!=="completed"&&a!=="")await Ft(e,"crawl",`/crawl/${encodeURIComponent(a)}`,{method:"DELETE"},AbortSignal.timeout(5000)).catch(()=>{return});if(u.length===0)return h==="failed"?`The crawl of ${i.href} failed and read no pages. Try web_fetch on the page itself.`:`The crawl of ${i.href} read no pages in time. Try a smaller limit, or web_fetch on the page itself.`;let p=Math.floor(fS/u.length),m=u.map((y)=>{let w=y.markdown.length>p?`${y.markdown.slice(0,p).trimEnd()}
|
|
326
|
+
…(cut)`:y.markdown;return`## ${y.url}
|
|
327
|
+
|
|
328
|
+
${w}`}),g=[];if(h!=="completed")g.push("the crawl did not finish in time, so some pages are missing");if(u.some((y)=>y.markdown.length>p))g.push(`each page is cut to ${p.toLocaleString("en-US")} characters`);return[`${u.length} page${u.length===1?"":"s"} from ${i.host}:`,...g.length===0?[]:[`incomplete: ${g.join("; ")}`],"",m.join(`
|
|
329
|
+
|
|
330
|
+
`)].join(`
|
|
331
|
+
`)}finally{l()}}}}function au(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 bS(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 cu=5,lu=10,Kl=300,_S=3000,kS=15000,SS={slug:"web_search",provider:Bt,summary:"Searches the web and returns titles, addresses and short extracts.",whenToUse:"you need something current, something you are unsure about, or a page whose address you do not know — prices, news, documentation, whether a thing still exists",whenNotToUse:"you already have the URL, which is web_fetch; the answer is in a file or in this conversation; or you want to find a tool rather than a page, which this cannot do",mutating:!1,trust:"untrusted",policyArg:"query",tags:["read","web","search"],parameters:{type:"object",properties:{query:{type:"string",description:"What to search for, written the way you would type it into a search box. Keywords work better than a full sentence."},maxResults:{type:"integer",description:`How many results to return, 1 to ${lu}.`,default:cu}},required:["query"]}};function $S(e){return{spec:SS,handler:TS(e)}}function TS(e){let t=Hl(e.backend);return async(n,r)=>{let i=String(n.query??"").trim();if(i==="")return"No query was given, so nothing was searched for. Call this again with the words you want to look up.";let s=e.env[e.apiKeyEnv]??"";if(s==="")throw L0(t.id,e.apiKeyEnv);let o=ES(n.maxResults),{url:c,init:l}=t.request(i,o,s,e.baseUrl??t.defaultBase),a=new AbortController,d=()=>{a.abort()};r.signal.addEventListener("abort",d,{once:!0});let f=setTimeout(d,Math.min(kS,Math.max(1000,r.deadlineMs-_S)));try{let h=await e.fetch(c,{...l,signal:a.signal});if(!h.ok)await q0(t.id,h);let u=await h.json();return r.meter?.({provider:t.id,operation:"search",unit:t.unit,units:t.units?.(u)??1}),AS(i,t.read(u).slice(0,o))}finally{clearTimeout(f),r.signal.removeEventListener("abort",d)}}}function ES(e){let t=typeof e==="number"?e:Number(e);if(!Number.isFinite(t))return cu;return Math.min(lu,Math.max(1,Math.trunc(t)))}function AS(e,t){if(t.length===0)return`No results for ${JSON.stringify(e)}. The search ran and came back empty — a narrower or differently worded query may find something, but do not assume the subject does not exist.`;let n=t.map((r,i)=>{let s=r.snippet.length>Kl?`${r.snippet.slice(0,Kl).trimEnd()}…`:r.snippet;return[`${i+1}. ${r.title===""?"(untitled)":r.title}`,` ${r.url}`,...s===""?[]:[` ${s.replace(/\s+/g," ")}`]].join(`
|
|
332
|
+
`)});return[`${t.length} result${t.length===1?"":"s"} for ${JSON.stringify(e)}:`,"",...n].join(`
|
|
333
|
+
`)}var OS="dispach-agent/0.1 (+https://github.com/blivius/dispach)";function ql(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}class uu{id=Bt;#e;constructor(e){let t=e.backend??"tavily",n=Hl(t),r=e.fetch??((s,o)=>fetch(s,o)),i=e.lookup??nS;this.#e=[$S({backend:t,apiKeyEnv:e.apiKeyEnv??n.defaultKeyEnv,...e.baseUrl===void 0?{}:{baseUrl:e.baseUrl},env:e.env,fetch:r}),...e.firecrawl===void 0?[sS({lookup:i,fetch:r,maxBytes:e.maxBytes??Ql,userAgent:OS})]:(()=>{let s={config:e.firecrawl,env:e.env,fetch:r,lookup:i};return[mS(s),vS(s),yS(s)]})()]}available(){return Promise.resolve(this.#e.map((e)=>({slug:e.spec.slug,summary:e.spec.summary})))}resolve(e){let t=new Set(e.map(ql));return Promise.resolve(this.#e.filter((n)=>t.has(ql(n.spec.slug))))}list(){return Promise.resolve(this.#e.map((e)=>e.spec.slug))}}var Wl=["backend","apiKeyEnv","baseUrl","maxBytes","firecrawl"],Zl=["apiKeyEnv","baseUrl","onlyMainContent","maxAge","timeoutMs"];function Li(e){let t=Object.keys(e.config).filter((c)=>!Wl.includes(c));if(t.length>0)throw new B({code:"web_config_unknown",message:`The web provider's configuration has ${t.length===1?"a key":"keys"} it does not read: ${t.join(", ")}.`,hint:`Accepted keys are ${Wl.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&&!Bl.includes(String(n)))throw Pe("backend",`must be one of ${Bl.join(", ")} — got ${JSON.stringify(n)}.`);let r=e.config.apiKeyEnv;if(r!==void 0&&(typeof r!=="string"||r===""))throw Pe("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 Pe("maxBytes","must be a number of at least 1000.");let s=du(e.config.baseUrl,"baseUrl"),o=NS(e.config.firecrawl,n==="firecrawl",typeof r==="string"?r:void 0,s);return new uu({env:e.env,...s===void 0?{}:{baseUrl:s},...o===void 0?{}:{firecrawl:o},...n===void 0?{}:{backend:String(n)},...typeof r==="string"?{apiKeyEnv:r}:{},...typeof i==="number"?{maxBytes:i}:{}})}function NS(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 Pe("firecrawl","must be a map, e.g. `firecrawl: {}` for the defaults.");let s=Object.keys(i).find((u)=>!Zl.includes(u));if(s!==void 0)throw Pe(`firecrawl.${s}`,`is not a setting. Accepted: ${Zl.join(", ")}.`);let o=i.apiKeyEnv;if(o!==void 0&&(typeof o!=="string"||o===""))throw Pe("firecrawl.apiKeyEnv","must be the non-empty name of an environment variable.");let c=i.onlyMainContent;if(c!==void 0&&typeof c!=="boolean")throw Pe("firecrawl.onlyMainContent","must be true or false.");let l=(u,p,m)=>{let g=i[u];if(g===void 0)return;if(typeof g!=="number"||!Number.isFinite(g)||g<p||g>m)throw Pe(`firecrawl.${u}`,`must be a number of milliseconds from ${p} to ${m}.`);return g},d=du(i.baseUrl,"firecrawl.baseUrl")??(t?r:void 0),f=l("maxAge",0,2592000000),h=l("timeoutMs",1000,300000);return{apiKeyEnv:typeof o==="string"?o:t&&n!==void 0?n:"FIRECRAWL_API_KEY",onlyMainContent:c??!0,...d===void 0?{}:{baseUrl:d},...f===void 0?{}:{maxAgeMs:f},...h===void 0?{}:{timeoutMs:h}}}function du(e,t){if(e===void 0)return;let n;try{n=new URL(String(e))}catch{throw Pe(t,`is not a URL: ${JSON.stringify(e)}.`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw Pe(t,"must be an http or https address.");if(n.username!==""||n.password!=="")throw Pe(t,"must not carry credentials. The key travels in the request's own header, from apiKeyEnv.");return n.href.replace(/\/+$/,"")}var IS="0.1.0",fu={name:"web",version:IS,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["*"]}],setup(e){e.defineToolProvider("web",Li)}};var ae={composio:gi,mcp:(e)=>vi(e),system:Oi,web:Li},be={"bedrock-converse":si()},Ee={aws:ci()};function fe(){return new Wn({env:process.env})}var FE=Object.keys(ae),Ie={teams:er,slack:Yn,telegram:rr,whatsapp:ni},BE=Object.keys(Ie),Qe={"@dispach/channel-a2a":zi,"@dispach/channel-teams":es,"@dispach/channel-slack":Wi,"@dispach/channel-telegram":os,"@dispach/channel-whatsapp":qa,"@dispach/media-aws":ec,"@dispach/model-bedrock":Ga,"@dispach/tools-composio":Tc,"@dispach/tools-mcp":Dc,"@dispach/tools-system":Dl,"@dispach/tools-web":fu},Jr=Object.keys(Qe);
|
|
334
|
+
export{ae,be,Ee,fe,Ie,Qe,Jr};
|
|
335
|
+
|
|
336
|
+
//# debugId=D2AD763D864FDBB864756E2164756E21
|
|
337
|
+
//# sourceMappingURL=index-w8e8qxd4.js.map
|