dispach 0.2.4 → 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.
Files changed (187) hide show
  1. package/README.md +32 -33
  2. package/dist/APEv2Parser-rt8hyadd.js +5 -0
  3. package/dist/{FlacParser-8xprykrh.js.map → APEv2Parser-rt8hyadd.js.map} +1 -1
  4. package/dist/{AiffParser-ns1y9f0g.js → AiffParser-gvpmtb2e.js} +3 -3
  5. package/dist/{AiffParser-ns1y9f0g.js.map → AiffParser-gvpmtb2e.js.map} +1 -1
  6. package/dist/{App-wkpkwgjt.js → App-18dvbyev.js} +8 -8
  7. package/dist/{App-wkpkwgjt.js.map → App-18dvbyev.js.map} +1 -1
  8. package/dist/{AsfParser-bae2a1yf.js → AsfParser-h9zyh6cx.js} +3 -3
  9. package/dist/{AsfParser-bae2a1yf.js.map → AsfParser-h9zyh6cx.js.map} +1 -1
  10. package/dist/{ConfigEditor-hy9jtas3.js → ConfigEditor-444m13ta.js} +3 -3
  11. package/dist/{ConfigEditor-hy9jtas3.js.map → ConfigEditor-444m13ta.js.map} +1 -1
  12. package/dist/{DsdiffParser-s0zvxnfa.js → DsdiffParser-gxqv4gn1.js} +3 -3
  13. package/dist/{DsdiffParser-s0zvxnfa.js.map → DsdiffParser-gxqv4gn1.js.map} +1 -1
  14. package/dist/{DsfParser-90mvzt4v.js → DsfParser-sndt4jbk.js} +3 -3
  15. package/dist/{DsfParser-90mvzt4v.js.map → DsfParser-sndt4jbk.js.map} +1 -1
  16. package/dist/FlacParser-rmkpvf9e.js +5 -0
  17. package/dist/{APEv2Parser-x13n424p.js.map → FlacParser-rmkpvf9e.js.map} +1 -1
  18. package/dist/{KeyProbe-fk5krzks.js → KeyProbe-6t531sy6.js} +3 -3
  19. package/dist/{KeyProbe-fk5krzks.js.map → KeyProbe-6t531sy6.js.map} +1 -1
  20. package/dist/{MP4Parser-nmvbkq21.js → MP4Parser-87xfsck4.js} +3 -3
  21. package/dist/{MP4Parser-nmvbkq21.js.map → MP4Parser-87xfsck4.js.map} +1 -1
  22. package/dist/{MatroskaParser-tsmz2qfq.js → MatroskaParser-7krspfgx.js} +3 -3
  23. package/dist/{MatroskaParser-tsmz2qfq.js.map → MatroskaParser-7krspfgx.js.map} +1 -1
  24. package/dist/{MpegParser-y5fjpaz9.js → MpegParser-jcs35q0h.js} +3 -3
  25. package/dist/{MpegParser-y5fjpaz9.js.map → MpegParser-jcs35q0h.js.map} +1 -1
  26. package/dist/{MusepackParser-544q0byg.js → MusepackParser-d4zfnzk3.js} +3 -3
  27. package/dist/{MusepackParser-544q0byg.js.map → MusepackParser-d4zfnzk3.js.map} +1 -1
  28. package/dist/{OggParser-v77rbjnt.js → OggParser-fbspjs7v.js} +3 -3
  29. package/dist/{OggParser-v77rbjnt.js.map → OggParser-fbspjs7v.js.map} +1 -1
  30. package/dist/{Picker-32m79nmp.js → Picker-x6aj42tc.js} +3 -3
  31. package/dist/{Picker-32m79nmp.js.map → Picker-x6aj42tc.js.map} +1 -1
  32. package/dist/{SessionPicker-9p06npt5.js → SessionPicker-pngdv97x.js} +3 -3
  33. package/dist/{SessionPicker-9p06npt5.js.map → SessionPicker-pngdv97x.js.map} +1 -1
  34. package/dist/{SkillBrowser-ezdx3xsh.js → SkillBrowser-3mnzkakr.js} +3 -3
  35. package/dist/{SkillBrowser-ezdx3xsh.js.map → SkillBrowser-3mnzkakr.js.map} +1 -1
  36. package/dist/{WavPackParser-k623m0hk.js → WavPackParser-0x9z4466.js} +3 -3
  37. package/dist/{WavPackParser-k623m0hk.js.map → WavPackParser-0x9z4466.js.map} +1 -1
  38. package/dist/{WaveParser-nj4p1vx8.js → WaveParser-31b6qtef.js} +3 -3
  39. package/dist/{WaveParser-nj4p1vx8.js.map → WaveParser-31b6qtef.js.map} +1 -1
  40. package/dist/{WizardApp-p350qspw.js → WizardApp-c42wc116.js} +3 -3
  41. package/dist/{WizardApp-p350qspw.js.map → WizardApp-c42wc116.js.map} +1 -1
  42. package/dist/{channels-a9zx9yba.js → channels-nf6d8fvx.js} +14 -14
  43. package/dist/{channels-a9zx9yba.js.map → channels-nf6d8fvx.js.map} +1 -1
  44. package/dist/client.d.ts +1 -1
  45. package/dist/client.js +11 -11
  46. package/dist/client.js.map +4 -4
  47. package/dist/{config-3mz4zwsf.js → config-sx40rg8m.js} +21 -21
  48. package/dist/{config-3mz4zwsf.js.map → config-sx40rg8m.js.map} +1 -1
  49. package/dist/{credential-ja7zmd4c.js → credential-vdbkfk65.js} +5 -5
  50. package/dist/{credential-ja7zmd4c.js.map → credential-vdbkfk65.js.map} +1 -1
  51. package/dist/daemon.d.ts.map +1 -1
  52. package/dist/{index-dcy14zdn.js → index-0dcpsfet.js} +5 -5
  53. package/dist/{index-dcy14zdn.js.map → index-0dcpsfet.js.map} +1 -1
  54. package/dist/{index-a1axc952.js → index-1h8s50d9.js} +4 -4
  55. package/dist/{index-a1axc952.js.map → index-1h8s50d9.js.map} +1 -1
  56. package/dist/{index-ayhdn87b.js → index-1hbvhrsj.js} +4 -4
  57. package/dist/{index-ayhdn87b.js.map → index-1hbvhrsj.js.map} +1 -1
  58. package/dist/{index-5gn74n56.js → index-1hfece7s.js} +7 -7
  59. package/dist/{index-5gn74n56.js.map → index-1hfece7s.js.map} +1 -1
  60. package/dist/{index-0dvs3a06.js → index-2h566rtg.js} +4 -4
  61. package/dist/{index-0dvs3a06.js.map → index-2h566rtg.js.map} +1 -1
  62. package/dist/{index-zzpgsbn3.js → index-4fj1k64j.js} +4 -4
  63. package/dist/{index-zzpgsbn3.js.map → index-4fj1k64j.js.map} +1 -1
  64. package/dist/{index-gezqawvw.js → index-4g4smpkk.js} +5 -5
  65. package/dist/{index-gezqawvw.js.map → index-4g4smpkk.js.map} +1 -1
  66. package/dist/index-4gfsf9n8.js +6 -0
  67. package/dist/{index-tc054tcb.js.map → index-4gfsf9n8.js.map} +1 -1
  68. package/dist/{index-mgef1n4e.js → index-5ptbytze.js} +9 -9
  69. package/dist/{index-mgef1n4e.js.map → index-5ptbytze.js.map} +1 -1
  70. package/dist/{index-f6r3h2yh.js → index-5s1cq8np.js} +5 -5
  71. package/dist/{index-f6r3h2yh.js.map → index-5s1cq8np.js.map} +1 -1
  72. package/dist/{index-rqfwd7j5.js → index-659ggfbf.js} +4 -4
  73. package/dist/{index-rqfwd7j5.js.map → index-659ggfbf.js.map} +1 -1
  74. package/dist/index-6ebppx3t.js +6 -0
  75. package/dist/{index-x9nn57kk.js.map → index-6ebppx3t.js.map} +1 -1
  76. package/dist/{index-4j65jp20.js → index-6pym9p8h.js} +6 -6
  77. package/dist/{index-4j65jp20.js.map → index-6pym9p8h.js.map} +1 -1
  78. package/dist/index-9ejax6hp.js +6 -0
  79. package/dist/{index-s0t15ndj.js.map → index-9ejax6hp.js.map} +1 -1
  80. package/dist/{index-86rb86nr.js → index-9hw9j1qg.js} +4 -4
  81. package/dist/{index-86rb86nr.js.map → index-9hw9j1qg.js.map} +1 -1
  82. package/dist/{index-yz0fcxky.js → index-9xhresrg.js} +4 -4
  83. package/dist/{index-yz0fcxky.js.map → index-9xhresrg.js.map} +1 -1
  84. package/dist/{index-2td5h856.js → index-abm0zyc0.js} +6 -6
  85. package/dist/{index-2td5h856.js.map → index-abm0zyc0.js.map} +1 -1
  86. package/dist/{index-8k8y7edx.js → index-ar5c9d2f.js} +5 -5
  87. package/dist/{index-8k8y7edx.js.map → index-ar5c9d2f.js.map} +1 -1
  88. package/dist/index-bhj4pmrx.js +74 -0
  89. package/dist/index-bhj4pmrx.js.map +13 -0
  90. package/dist/{index-brh25jhq.js → index-brt17yfr.js} +3 -3
  91. package/dist/{index-brh25jhq.js.map → index-brt17yfr.js.map} +1 -1
  92. package/dist/index-bysnsdkd.js +6 -0
  93. package/dist/{index-c6qrcweh.js.map → index-bysnsdkd.js.map} +1 -1
  94. package/dist/{index-kz01jz58.js → index-c74wx9pv.js} +4 -4
  95. package/dist/{index-kz01jz58.js.map → index-c74wx9pv.js.map} +1 -1
  96. package/dist/{index-qj4adnfe.js → index-cm3g4t3r.js} +9 -9
  97. package/dist/{index-qj4adnfe.js.map → index-cm3g4t3r.js.map} +1 -1
  98. package/dist/{index-8mkatm20.js → index-dzp6mc5h.js} +4 -4
  99. package/dist/{index-8mkatm20.js.map → index-dzp6mc5h.js.map} +1 -1
  100. package/dist/{index-b8bfzbfe.js → index-fad09b8c.js} +4 -4
  101. package/dist/{index-b8bfzbfe.js.map → index-fad09b8c.js.map} +1 -1
  102. package/dist/{index-2fw9e5gg.js → index-fvb2dxzn.js} +4 -4
  103. package/dist/{index-2fw9e5gg.js.map → index-fvb2dxzn.js.map} +1 -1
  104. package/dist/index-gpq4agva.js +5 -0
  105. package/dist/{index-635wcsh1.js.map → index-gpq4agva.js.map} +1 -1
  106. package/dist/index-hcpvk5de.js +5 -0
  107. package/dist/{index-7zgjkbb0.js.map → index-hcpvk5de.js.map} +1 -1
  108. package/dist/{index-s0f0s6n5.js → index-jv5t63tp.js} +4 -4
  109. package/dist/{index-s0f0s6n5.js.map → index-jv5t63tp.js.map} +1 -1
  110. package/dist/{index-60h4knj6.js → index-kyz4t0j0.js} +59 -59
  111. package/dist/{index-60h4knj6.js.map → index-kyz4t0j0.js.map} +1 -1
  112. package/dist/{index-7p8d1gf0.js → index-m6r2sxcw.js} +23 -23
  113. package/dist/{index-7p8d1gf0.js.map → index-m6r2sxcw.js.map} +1 -1
  114. package/dist/{index-4fajxhdv.js → index-mhw3d7af.js} +4 -4
  115. package/dist/{index-4fajxhdv.js.map → index-mhw3d7af.js.map} +1 -1
  116. package/dist/{index-h787rq0h.js → index-mk7hrzq7.js} +10 -10
  117. package/dist/{index-h787rq0h.js.map → index-mk7hrzq7.js.map} +1 -1
  118. package/dist/{index-r83jpct7.js → index-n0hqgwad.js} +4 -4
  119. package/dist/{index-r83jpct7.js.map → index-n0hqgwad.js.map} +1 -1
  120. package/dist/{index-k6wq0j4q.js → index-ncb840sk.js} +4 -4
  121. package/dist/{index-k6wq0j4q.js.map → index-ncb840sk.js.map} +1 -1
  122. package/dist/{index-8jejze0z.js → index-ntczmwnf.js} +3 -3
  123. package/dist/{index-8jejze0z.js.map → index-ntczmwnf.js.map} +1 -1
  124. package/dist/{index-ts8a1sdn.js → index-p5gy5s7p.js} +6 -6
  125. package/dist/{index-ts8a1sdn.js.map → index-p5gy5s7p.js.map} +1 -1
  126. package/dist/index-p86w0qjw.js +5 -0
  127. package/dist/{index-pz92ksp8.js.map → index-p86w0qjw.js.map} +1 -1
  128. package/dist/{index-cb45233h.js → index-qhh30m9p.js} +4 -4
  129. package/dist/{index-cb45233h.js.map → index-qhh30m9p.js.map} +1 -1
  130. package/dist/{index-z4adxmzm.js → index-rerdsr3d.js} +5 -5
  131. package/dist/{index-z4adxmzm.js.map → index-rerdsr3d.js.map} +1 -1
  132. package/dist/{index-67sfck4d.js → index-s0mfq8t7.js} +18 -18
  133. package/dist/index-s0mfq8t7.js.map +11 -0
  134. package/dist/{index-9k6qa50r.js → index-s9ybp2r1.js} +6 -6
  135. package/dist/{index-9k6qa50r.js.map → index-s9ybp2r1.js.map} +1 -1
  136. package/dist/index-ss77hvwy.js +1246 -0
  137. package/dist/{index-tv52jhac.js.map → index-ss77hvwy.js.map} +32 -31
  138. package/dist/{index-yy4v9kca.js → index-t9bnt6a1.js} +4 -4
  139. package/dist/{index-yy4v9kca.js.map → index-t9bnt6a1.js.map} +1 -1
  140. package/dist/{index-5zpfz4kb.js → index-w2ss9hn5.js} +7 -7
  141. package/dist/{index-5zpfz4kb.js.map → index-w2ss9hn5.js.map} +1 -1
  142. package/dist/{index-1cagdzqe.js → index-w80shmpv.js} +2 -2
  143. package/dist/index-w8e8qxd4.js +337 -0
  144. package/dist/index-w8e8qxd4.js.map +21 -0
  145. package/dist/{index-xyh98x7p.js → index-z9r4e0yq.js} +4 -4
  146. package/dist/{index-xyh98x7p.js.map → index-z9r4e0yq.js.map} +1 -1
  147. package/dist/{index-039ew35r.js → index-zj87j4j2.js} +4 -4
  148. package/dist/{index-039ew35r.js.map → index-zj87j4j2.js.map} +1 -1
  149. package/dist/{index-446exxcb.js → index-zmerx9rc.js} +7 -7
  150. package/dist/{index-446exxcb.js.map → index-zmerx9rc.js.map} +1 -1
  151. package/dist/{index-nndwx2wp.js → index-zqjtjs7c.js} +39 -39
  152. package/dist/{index-nndwx2wp.js.map → index-zqjtjs7c.js.map} +1 -1
  153. package/dist/index.js +318 -305
  154. package/dist/index.js.map +6 -5
  155. package/dist/lib/launchd.d.ts.map +1 -1
  156. package/dist/lib/service-env.d.ts.map +1 -1
  157. package/dist/lib/templates.d.ts.map +1 -1
  158. package/dist/lib/theme.d.ts.map +1 -1
  159. package/dist/lib/watchdog.d.ts +20 -0
  160. package/dist/lib/watchdog.d.ts.map +1 -0
  161. package/dist/serve.d.ts.map +1 -1
  162. package/dist/skills.d.ts.map +1 -1
  163. package/dist/sources.d.ts.map +1 -1
  164. package/dist/{web-7mdrcb8a.js → web-zvf80ns1.js} +5 -5
  165. package/dist/{web-7mdrcb8a.js.map → web-zvf80ns1.js.map} +1 -1
  166. package/dist/wire.js +11 -11
  167. package/dist/wire.js.map +4 -4
  168. package/dist/wrapper-5zhcdmnk.js +5 -0
  169. package/dist/{wrapper-4hdmdwft.js.map → wrapper-5zhcdmnk.js.map} +1 -1
  170. package/package.json +4 -4
  171. package/dist/APEv2Parser-x13n424p.js +0 -5
  172. package/dist/FlacParser-8xprykrh.js +0 -5
  173. package/dist/index-635wcsh1.js +0 -5
  174. package/dist/index-67sfck4d.js.map +0 -13
  175. package/dist/index-7zgjkbb0.js +0 -5
  176. package/dist/index-c6qrcweh.js +0 -6
  177. package/dist/index-hd5nkwd7.js +0 -74
  178. package/dist/index-hd5nkwd7.js.map +0 -13
  179. package/dist/index-n197qdw1.js +0 -308
  180. package/dist/index-n197qdw1.js.map +0 -21
  181. package/dist/index-pz92ksp8.js +0 -5
  182. package/dist/index-s0t15ndj.js +0 -6
  183. package/dist/index-tc054tcb.js +0 -6
  184. package/dist/index-tv52jhac.js +0 -1252
  185. package/dist/index-x9nn57kk.js +0 -6
  186. package/dist/wrapper-4hdmdwft.js +0 -5
  187. /package/dist/{index-1cagdzqe.js.map → index-w80shmpv.js.map} +0 -0
@@ -1,308 +0,0 @@
1
- #!/usr/bin/env node
2
- import{V,_,ne,Q,ct,b,Ye,Jt,io,so,Zr,go,Ms,Ts,Wt,Rs,co,aA,Ai,mr}from"./index-hd5nkwd7.js";import{Ot,Nt,X,Bn}from"./index-tv52jhac.js";import{randomUUID as Hr}from"node:crypto";import{randomUUID as at}from"node:crypto";var $t="1.0",ge={parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,taskNotFound:-32001,taskNotCancelable:-32002,unsupportedOperation:-32004,contentTypeNotSupported:-32005,versionNotSupported:-32009},Ic=["TASK_STATE_COMPLETED","TASK_STATE_FAILED","TASK_STATE_CANCELED"],Cc=3600000,Pc=3000;class de extends Error{code;status;constructor(e,t,n=200){super(t);this.code=e,this.status=n}}class Gr{#e;#n;#t=new Map;#r=new Map;#o=new Map;#i=new Map;#a;constructor(e,t){this.#e=e,this.#n=t}transport(e){return{id:e,type:"a2a",limits:{maxMessageChars:1e6,idempotentSend:!0},alwaysAllow:this.#e.peers.flatMap((n)=>n.key===void 0?[]:[n.name]),start:async(n)=>{this.#a=n,n.status("connected",Lc(this.#e.peers))},stop:async()=>{this.#a=void 0},send:async(n)=>this.#w(n)}}observe(e){if(e.type!=="turn.end"||e.agentId!==this.#n)return;let t=e.sessionKey?.startsWith("a2a:")===!0?e.sessionKey.slice(4):void 0;if(t===void 0)return;let n=e.data.reason;if(n!=="final"&&n!=="stopped"){let o=this.#m(t);if(o!==void 0)this.#g(o,"TASK_STATE_FAILED",`The turn ended: ${n??"unknown"}.`);return}let r=this.#m(t);if(r===void 0)return;setTimeout(()=>{if(r.endedAt===void 0&&this.#m(t)===r)this.#g(r,"TASK_STATE_COMPLETED",void 0)},Pc).unref?.()}card(e){let t=this.#e.publicUrl??`${e.url.origin}/v1/agents/${encodeURIComponent(this.#n)}/plugins/a2a/`;return Response.json({name:this.#e.card.name,description:this.#e.card.description,version:$t,supportedInterfaces:[{url:t,protocolBinding:"JSONRPC",protocolVersion:$t}],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(ge.versionNotSupported,`A2A-Version ${n} is not supported; this agent speaks ${$t}.`);let r=this.#s(e.caller),i;try{i=await e.request.json()}catch{throw new de(ge.parse,"The body is not JSON.")}let o=typeof i==="object"&&i!==null?i:{};if(t=o.id??null,o.jsonrpc!=="2.0"||typeof o.method!=="string")throw new de(ge.invalidRequest,"Not a JSON-RPC 2.0 request.");this.#c(r);let s=typeof o.params==="object"&&o.params!==null?o.params:{};switch(o.method){case"SendMessage":return Vr(t,await this.#l(r,s));case"SendStreamingMessage":return this.#d(t,await this.#u(r,s));case"GetTask":return Vr(t,this.#p(r,s.id).task);case"CancelTask":{let c=this.#p(r,s.id);throw new de(ge.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(o.method.startsWith("SendMessage")||o.method.includes("PushNotification")?ge.unsupportedOperation:ge.methodNotFound,`${o.method} is not supported here.`)}}catch(n){if(n instanceof de)return Rc(t,n.code,n.message,n.status);throw n}}#s(e){let t=e.kind==="key"?this.#e.peers.find((n)=>n.key===e.label):void 0;if(t===void 0)throw new de(ge.invalidRequest,"This credential is not a peer of this agent. Each peer calls with the operator key its `key` names.",403);return t}#c(e){let t=Date.now(),n=(this.#i.get(e.name)??[]).filter((r)=>t-r<60000);if(n.length>=e.ratePerMinute)throw this.#i.set(e.name,n),new de(ge.invalidRequest,`Peer ${e.name} is over ${e.ratePerMinute} requests a minute.`,429);this.#i.set(e.name,[...n,t])}async#l(e,t){let n=await this.#u(e,t);if(t.configuration?.returnImmediately===!0||n.endedAt!==void 0)return this.#h(n);return{task:await this.#f(n,this.#e.waitMs)}}async#u(e,t){this.#v();let n=typeof t.message==="object"&&t.message!==null?t.message:{},r=Array.isArray(n.parts)?n.parts:[];if(r.length===0)throw new de(ge.invalidParams,"The message has no parts.");if(r.some((d)=>typeof d.text!=="string"))throw new de(ge.contentTypeNotSupported,"Only text parts are accepted.");let i=r.map((d)=>String(d.text)).join(`
3
- `);if(i.length>e.maxChars)throw new de(ge.invalidParams,`The message is ${i.length} characters; ${e.name} may send ${e.maxChars}.`);let o=typeof n.messageId==="string"&&n.messageId!==""?n.messageId:at(),s=this.#o.get(`${e.name}\x1F${o}`),c=s===void 0?void 0:this.#t.get(s);if(c!==void 0)return c;let l=this.#a;if(l===void 0)throw new de(ge.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:at(),h=`${e.name}:${a}`,f={task:{id:at(),contextId:a,status:{state:"TASK_STATE_WORKING",timestamp:new Date().toISOString()},artifacts:[]},peer:e.name,recipient:h,messageId:o,text:"",waiters:[]};return this.#t.set(f.task.id,f),this.#o.set(`${e.name}\x1F${o}`,f.task.id),this.#r.set(h,[...this.#r.get(h)??[],f.task.id]),l.receive({peerId:h,senderHandle:e.name,senderName:e.name,senderKind:"agent",providerMessageId:o,receivedAt:new Date().toISOString(),text:i}),f}#d(e,t){let n=new TextEncoder,r=(o)=>n.encode(`data: ${JSON.stringify({jsonrpc:"2.0",id:e,result:o})}
4
-
5
- `),i=new ReadableStream({start:async(o)=>{o.enqueue(r(this.#h(t)));let s=await this.#f(t,this.#e.waitMs);o.enqueue(r({statusUpdate:{taskId:s.id,contextId:s.contextId,status:s.status}})),o.close()}});return new Response(i,{headers:{"content-type":"text/event-stream","cache-control":"no-cache"}})}#f(e,t){if(e.endedAt!==void 0)return Promise.resolve(e.task);return new Promise((n)=>{let r=setTimeout(()=>n(e.task),t);r.unref?.(),e.waiters.push((i)=>{clearTimeout(r),n(i)})})}#p(e,t){this.#v();let n=typeof t==="string"?this.#t.get(t):void 0;if(n===void 0||n.peer!==e.name)throw new de(ge.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:at(),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:at(),parts:r.parts}]},e.endedAt=Date.now(),this.#r.set(e.recipient,(this.#r.get(e.recipient)??[]).filter((i)=>i!==e.task.id));for(let i of e.waiters.splice(0))i(e.task)}#v(){let e=Date.now()-Cc;for(let[t,n]of this.#t)if(n.endedAt!==void 0&&n.endedAt<e)this.#t.delete(t),this.#o.delete(`${n.peer}\x1F${n.messageId}`)}}function Mc(e){return Ic.includes(e)}function Vr(e,t){return Response.json({jsonrpc:"2.0",id:e,result:t})}function Rc(e,t,n,r){return Response.json({jsonrpc:"2.0",id:e,error:{code:t,message:n}},{status:r})}function Lc(e){if(e.length===0)return"no peers configured";return e.map((t)=>{let n=[...t.key===void 0?[]:["calls in"],...t.url===void 0?[]:["is called"]];return`${t.name} ${n.join(" and ")}`}).join(" · ")}function xc(e){let t=typeof e==="object"&&e!==null?e:{},n=(o)=>(o??[]).flatMap((s)=>typeof s.text==="string"?[s.text]:[]).join(`
6
- `);if(t.message!==void 0)return n(t.message.parts);let r=t.task;if(r===void 0)return"The peer answered with nothing readable.";if(!Mc(r.status.state))return`The peer is still working on it (task ${r.id}, ${r.status.state}). It has not answered yet.`;let i=n(r.status.message?.parts)||r.artifacts.map((o)=>n(o.parts)).join(`
7
- `);if(r.status.state!=="TASK_STATE_COMPLETED")return`The peer's task ended ${r.status.state}${i===""?"":`: ${i}`}.`;return i===""?"The peer finished without saying anything.":i}function Dc(e,t=fetch){let n=e.peers.filter((i)=>i.url!==void 0),r=new Map;return(i)=>{let o={spec:{slug:"a2a_send",provider:"a2a",summary:"Sends a message to another agent and returns its answer.",whenToUse:`a task needs another agent's help and that agent is one of: ${n.map((s)=>s.name).join(", ")||"(none configured)"}`,whenNotToUse:"for anything you can answer yourself, or to reach anyone not in the peer list",mutating:!0,trust:"untrusted",policyArg:"peer",tags:["a2a","agent"],parameters:{type:"object",properties:{peer:{type:"string",enum:n.map((s)=>s.name),description:"Which agent to ask, by the name the manifest gives it."},text:{type:"string",description:"The message, as you would write it to a colleague."}},required:["peer","text"]}},async handler(s,c){let l=n.find((m)=>m.name===s.peer);if(l?.url===void 0)throw new ne({code:"a2a_peer_unknown",message:`No peer "${String(s.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 h=`${c.sessionKey}\x1F${l.name}`,f=AbortSignal.timeout(Math.max(1000,Math.min(60000,c.deadlineMs-5000))),d;try{d=await t(l.url,{method:"POST",headers:{"content-type":"application/json","a2a-version":$t,...a===void 0?{}:{authorization:`Bearer ${a}`}},body:JSON.stringify({jsonrpc:"2.0",id:Hr(),method:"SendMessage",params:{message:{messageId:Hr(),role:"ROLE_USER",parts:[{text:String(s.text??"")}],...r.has(h)?{contextId:r.get(h)}:{}}}}),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 d.json().catch(()=>({}));if(u.error!==void 0||!d.ok)throw new ne({code:"a2a_peer_refused",message:`Peer ${l.name} refused: ${u.error?.message??`HTTP ${d.status}`}`,hint:"A 401 or 403 means the token in the peer's tokenEnv is wrong; anything else is the peer's own error, quoted."});let p=u.result?.task?.contextId??u.result?.message?.contextId;if(typeof p==="string")r.set(h,p);return xc(u.result)}};return{id:"a2a",resolve:async(s)=>s.includes("a2a_send")?[o]:[]}}}var Pe=(e)=>typeof e==="string"&&e.trim()!==""?e.trim():void 0,$n=(e,t,n)=>{if(e===void 0)return t;if(typeof e==="number"&&Number.isInteger(e)&&e>0)return e;throw Ve(`${n} must be a positive whole number.`,n)};function Ve(e,t){return new Q({code:"a2a_config_invalid",message:e,hint:"See @dispach/channel-a2a's config: `card` describes this agent, and `peers` maps each name to the key it calls with (`key`), the URL it is called at (`url` and `tokenEnv`), or both.",field:`plugins[channel-a2a].${t}`})}function jc(e){let t=typeof e==="object"&&e!==null?e:{},n=typeof t.card==="object"&&t.card!==null?t.card:{},r=typeof t.peers==="object"&&t.peers!==null?t.peers:{},i=Object.entries(r).map(([l,a])=>{if(!/^[a-z0-9][a-z0-9-]*$/.test(l))throw Ve(`Peer "${l}" needs a lowercase slug name; it becomes part of a session key.`,`peers.${l}`);let h=typeof a==="object"&&a!==null?a:{},f=Pe(h.key),d=Pe(h.url),u=Pe(h.tokenEnv);if(f===void 0&&d===void 0)throw Ve(`Peer "${l}" names neither a key (inbound) nor a url (outbound).`,`peers.${l}`);if(d!==void 0&&!/^https?:\/\//.test(d))throw Ve(`Peer "${l}"'s url must be absolute http(s).`,`peers.${l}.url`);return{name:l,...f===void 0?{}:{key:f},...d===void 0?{}:{url:d},...u===void 0?{}:{tokenEnv:u},ratePerMinute:$n(h.ratePerMinute,30,`peers.${l}.ratePerMinute`),maxChars:$n(h.maxChars,20000,`peers.${l}.maxChars`)}}),o=i.flatMap((l)=>l.key===void 0?[]:[l.key]);if(new Set(o).size!==o.length)throw Ve("Two peers name the same key; a key identifies exactly one peer.","peers");let s=Array.isArray(n.skills)?n.skills:[],c=Pe(t.publicUrl);return{card:{name:Pe(n.name)??"Agent",description:Pe(n.description)??"",skills:s.map((l,a)=>{let h=typeof l==="object"&&l!==null?l:{},f=Pe(h.id);if(f===void 0)throw Ve("A card skill needs an id.",`card.skills.${a}`);return{id:f,name:Pe(h.name)??f,description:Pe(h.description)??"",tags:Array.isArray(h.tags)?h.tags.map(String):[]}})},peers:i,...c===void 0?{}:{publicUrl:c},waitMs:$n(t.waitMs,60000,"waitMs")}}var Uc="0.1.0",Yr={name:"a2a",version:Uc,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["*"]}],setup(e){let t=jc(e.config),n=new Gr(t,e.agentId);e.defineChannel("a2a",(r)=>n.transport(r.id)),e.defineRoute({method:"POST",path:"/",capability:"peer",handler:(r)=>n.rpc(r)}),e.defineRoute({method:"GET",path:"/.well-known/agent-card.json",capability:"open",root:"/.well-known/agent-card.json",handler:async(r)=>n.card(r)}),e.defineToolProvider("a2a",Dc(t)),e.events.on("turn.end",(r)=>n.observe(r))}};import{readFile as zc}from"node:fs/promises";import{basename as Fc}from"node:path";function Qr(e){return e.files?.find((t)=>t.url_private_download!==void 0&&(t.subtype==="slack_audio"||t.mimetype?.startsWith("audio/")===!0))}function ei(e){return(e.files??[]).filter((t)=>t.url_private_download!==void 0&&t.mimetype?.startsWith("image/")===!0)}var Bc={"&amp;":"&","&lt;":"<","&gt;":">"};function Kc(e,t){return(t===void 0?e.replace(/^\s*<@[A-Z0-9]+>/,""):e.replaceAll(`<@${t}>`,"")).replace(/&(amp|lt|gt);/g,(r)=>Bc[r]??r).replace(/\s+/g," ").trim()}function qc(e,t){if(e.subtype!==void 0&&e.subtype!=="file_share")return;if(e.bot_id!==void 0)return;if(e.user===void 0||e.user===t)return;if(e.channel===void 0||e.ts===void 0)return;let n=e.type==="message"&&e.channel_type==="im";if(!n&&e.type!=="app_mention")return;let r=Kc(e.text??"",t);if(r===""&&Qr(e)===void 0&&ei(e).length===0)return;let i=n?e.thread_ts:e.thread_ts??e.ts;return{providerMessageId:`${e.channel}:${e.ts}`,peerId:e.channel,senderId:e.user,senderHandle:e.user,...i===void 0?{}:{thread:i},text:r,receivedAt:new Date(Number(e.ts)*1000).toISOString()}}var Zc="https://slack.com/api/",Wc="https://files.slack.com/",Jc=[1000,2000,5000,15000,30000];class Et extends Error{detail;constructor(e){super(e.message);this.detail=e}}class ti{id;type="slack";limits={maxMessageChars:12000,idempotentSend:!1,minSendIntervalMs:1000,attachments:!0,voiceNotes:!0};#e;#n;#t;#r;#o;#i;#a;#s;#c;constructor(e){this.id=e.id,this.#e=e.appToken,this.#n=e.botToken,this.#t=e.fetch??((t,n)=>fetch(t,n)),this.#r=e.socket??((t)=>new WebSocket(t)),this.#o=e.backoffMs??Jc,this.#i=e.apiBase??Zc}async start(e){if(this.#s!==void 0)return;this.#a=e,this.#s=new AbortController,this.#c=this.#l(e,this.#s.signal)}async stop(){this.#s?.abort(),await this.#c?.catch(()=>{}),this.#s=void 0,this.#c=void 0,this.#a?.status("disconnected"),this.#a=void 0}async#l(e,t){let n=0,r=!1;while(!t.aborted)try{let i=await this.#u(t),o=await this.#d(e,i,t,()=>{if(n=0,!r)e.status("connected","Socket Mode");r=!0});if(t.aborted)return;if(o)continue;throw new Et({code:"slack_socket_closed",message:"Slack closed the Socket Mode connection before it was established.",hint:"Usually transient and retried. If it persists, check that Socket Mode is enabled for the app (Settings → Socket Mode)."})}catch(i){if(t.aborted)return;if(n+=1,r=!1,n===1||n%8===0){let s=i instanceof Et?i.detail:{code:"slack_unreachable",message:`Cannot reach Slack: ${i instanceof Error?i.message:String(i)}`,hint:"Allow outbound HTTPS to slack.com and wss to *.slack.com. Retried with backoff."};e.status("error",s.message),e.error(s)}let o=this.#o[Math.min(n,this.#o.length)-1]??30000;await Yc(o,t)}}async#u(e){let t=await this.#t(`${this.#i}apps.connections.open`,{method:"POST",headers:{authorization:`Bearer ${this.#e}`},signal:e}),n=await t.json().catch(()=>({}));if(n.ok===!0&&typeof n.url==="string")return n.url;let r=n.error??`HTTP ${t.status}`;throw new Et({code:"slack_app_token_refused",message:`Slack would not open a Socket Mode connection: ${r}.`,hint:r==="not_allowed_token_type"?"That is not an app-level token. appTokenEnv must hold the xapp-… token from Basic Information → App-Level Tokens, with the connections:write scope.":"Check the app-level token (xapp-…, scope connections:write) and that Socket Mode is enabled for the app. Retried with backoff."})}#d(e,t,n,r){return new Promise((i)=>{let o=this.#r(t),s=!1,c=()=>o.close();n.addEventListener("abort",c,{once:!0}),o.addEventListener("message",(l)=>{let a;try{a=JSON.parse(String(l.data))}catch{return}if(a.envelope_id!==void 0)o.send(JSON.stringify({envelope_id:a.envelope_id}));if(a.type==="hello")s=!0,r();else if(a.type==="disconnect")o.close();else if(a.type==="events_api"&&a.payload?.event){let h=a.payload.event,f=a.payload.authorizations?.[0]?.user_id,d=qc(h,f),u=Qr(h),p=u?.url_private_download;if(d===void 0)return;let m=ei(h).map((g)=>({...g.size===void 0?{}:{sizeBytes:g.size},fetch:(y)=>this.#h(g.url_private_download??"",y)}));e.receive({...d,...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)}}})}}),o.addEventListener("close",()=>{n.removeEventListener("abort",c),i(s)})})}async send(e,t){try{if(e.attachment!==void 0)return await this.#f(e,t);let n=await this.#p("chat.postMessage",{channel:e.recipient,text:e.text,blocks:[{type:"markdown",text:e.text}],...e.thread===void 0?{}:{thread_ts:e.thread}},t);return{ok:!0,...typeof n.ts==="string"?{providerMessageId:n.ts}:{}}}catch(n){if(n instanceof lt)return n.result(e.recipient);return{ok:!1,retryable:!0,error:{code:"slack_unreachable",message:`Cannot reach Slack: ${n instanceof Error?n.message:String(n)}`,hint:"Allow outbound HTTPS to slack.com and files.slack.com. Retried."}}}}async#f(e,t){let n=e.attachment,r=await zc(n.path),i=Fc(n.path),o=await this.#p("files.getUploadURLExternal",new URLSearchParams({filename:i,length:String(r.byteLength)}),t),{upload_url:s,file_id:c}=o;if(typeof s!=="string"||typeof c!=="string")throw new lt(200,"no_upload_url",void 0);let l=await this.#t(s,{method:"POST",headers:{"content-type":n.mimeType},body:r,...t===void 0?{}:{signal:t}});if(!l.ok)throw new lt(l.status,`upload_${l.status}`,void 0);return await this.#p("files.completeUploadExternal",{files:[{id:c,title:i}],channel_id:e.recipient,...e.thread===void 0?{}:{thread_ts:e.thread},...e.text===""?{}:{initial_comment:e.text}},t),{ok:!0,providerMessageId:c}}async#p(e,t,n){let r=await this.#t(`${this.#i}${e}`,{method:"POST",headers:{authorization:`Bearer ${this.#n}`,...t instanceof URLSearchParams?{}:{"content-type":"application/json; charset=utf-8"}},body:t instanceof URLSearchParams?t:JSON.stringify(t),...n===void 0?{}:{signal:n}}),i=await r.json().catch(()=>({}));if(i.ok===!0)return i;let o=Number(r.headers.get("retry-after"));throw new lt(r.status,typeof i.error==="string"?i.error:`HTTP ${r.status}`,Number.isFinite(o)&&o>0?o*1000:void 0)}async#h(e,t){let n=Hc(e);if(n===void 0)throw Error(`refused to fetch ${e.slice(0,80)} with the bot token: not an https files.slack.com address. Slack serves private files only from there; an event naming anything else is not one to trust.`);let r=await this.#t(`https://files.slack.com/${n}`,{method:"GET",headers:{authorization:`Bearer ${this.#n}`},signal:t});if(!r.ok||r.headers.get("content-type")?.startsWith("text/html")===!0)throw Error(`Slack would not serve the file (${r.status}); the bot token needs the files:read scope`);return new Uint8Array(await r.arrayBuffer())}}function Hc(e){try{let t=new URL(e);if(`${t.protocol}//${t.host}/`!==Wc)return;let n=t.pathname.slice(1);if(!n.startsWith("files-pri/")||n.split("/").some((r)=>r===".."||r===""))return;return`${n}${t.search}`}catch{return}}class lt extends Error{status;code;retryAfterMs;constructor(e,t,n){super(t);this.status=e,this.code=t,this.retryAfterMs=n}result(e){return{ok:!1,retryable:this.status===429||this.status>=500||Vc.has(this.code),...this.retryAfterMs===void 0?{}:{retryAfterMs:this.retryAfterMs},error:{code:"slack_send_failed",message:`Slack refused the reply to ${e}: ${this.code}.`,hint:Gc[this.code]??"Slack's own error code is above. Rate limits and server errors are retried; anything else is not."}}}}var Vc=new Set(["ratelimited","internal_error","fatal_error","service_unavailable","request_timeout"]),Gc={not_in_channel:"The app is not a member of that channel. Invite it (/invite @<app>) and message it again.",channel_not_found:"No channel with that id is visible to the bot: it was deleted, or it is private and the app was never added.",is_archived:"The channel is archived. Unarchive it or deliver somewhere else.",missing_scope:"The bot token lacks chat:write. Add the scope under OAuth & Permissions and reinstall the app.",invalid_auth:"The bot token (xoxb-…) is wrong. Check the env var botTokenEnv names.",token_revoked:"The bot token was revoked, usually by uninstalling the app. Reinstall it and update the token.",account_inactive:"The bot token belongs to an app that was uninstalled. Reinstall it and update the token."};function Yc(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}function Xr(e,t,n,r,i){let o=e.config[t],s=typeof o==="string"&&o!==""?o:n,c=e.env[s],l=`channels[${e.id}].${t}`;if(c===void 0||c==="")throw new Q({code:"slack_token_missing",message:`Channel "${e.id}" needs ${s}, which is not set.`,hint:`Put the ${i} in ${s}, in the environment or the .env beside the manifest. The agent starts either way, with this channel reported broken.`,field:l});if(!c.startsWith(r))throw new Q({code:"slack_token_wrong_kind",message:`${s} does not hold a Slack ${i}; those start with ${r}.`,hint:"Slack issues two tokens and Socket Mode needs both: the app-level token (xapp-…, Basic Information → App-Level Tokens) opens the socket, the bot token (xoxb-…, OAuth & Permissions) sends replies. They are easy to swap.",field:l});return c}var En=(e)=>new ti({id:e.id,appToken:Xr(e,"appTokenEnv","SLACK_APP_TOKEN","xapp-","app-level token"),botToken:Xr(e,"botTokenEnv","SLACK_BOT_TOKEN","xoxb-","bot token")}),Xc="0.1.0",ni={name:"channel-slack",version:Xc,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["slack.com","*.slack.com"]},{kind:"env",vars:["SLACK_APP_TOKEN","SLACK_BOT_TOKEN"]}],setup(e){e.defineChannel("slack",En)}};import{createPublicKey as Qc,verify as el}from"node:crypto";import{mkdirSync as il,readFileSync as sl,renameSync as ol,writeFileSync as al}from"node:fs";import{dirname as cl,join as ll}from"node:path";var tl="https://login.botframework.com/v1/.well-known/openidconfiguration",nl="https://api.botframework.com",ri=300,rl=86400000;class fe extends Error{}function ii(e){return JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}class ai{#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 fe("no bearer token");let[r,i,o]=n.split(".");if(r===void 0||i===void 0||o===void 0)throw new fe("malformed token");let s,c;try{s=ii(r),c=ii(i)}catch{throw new fe("unreadable token")}if(s.alg!=="RS256")throw new fe(`unexpected algorithm ${String(s.alg)}`);let l=await this.#i(String(s.kid??""));if(l===void 0)throw new fe("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 fe(`key not endorsed for channel ${t.channelId}`);if(!el("RSA-SHA256",Buffer.from(`${r}.${i}`),Qc({key:{kty:l.kty??"RSA",n:l.n??"",e:l.e??""},format:"jwk"}),Buffer.from(o,"base64url")))throw new fe("bad signature");let h=this.#t()/1000;if(c.iss!==nl)throw new fe(`issuer ${String(c.iss)}`);if(c.aud!==this.#e.appId)throw new fe("token is for another bot");if(typeof c.exp!=="number"||c.exp<h-ri)throw new fe("token expired");if(typeof c.nbf==="number"&&c.nbf>h+ri)throw new fe("token not yet valid");if(typeof c.serviceUrl!=="string"||c.serviceUrl!==t.serviceUrl)throw new fe("serviceUrl is not the one the token was issued for")}async token(e){if(this.#o!==void 0&&this.#o.until>this.#t())return this.#o.value;let t=this.#e.tenantId??"botframework.com",n=await this.#n(`https://login.microsoftonline.com/${encodeURIComponent(t)}/oauth2/v2.0/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.#e.appId,client_secret:this.#e.password,scope:"https://api.botframework.com/.default"}).toString(),...e===void 0?{}:{signal:e}}),r=await n.json().catch(()=>({}));if(!n.ok||typeof r.access_token!=="string")throw new On(n.status,r.error_description??`status ${n.status}`);let i=(r.expires_in??3600)*1000;return this.#o={value:r.access_token,until:this.#t()+i-300000},r.access_token}async#i(e){let n=this.#r!==void 0&&this.#t()-this.#r.at<rl?this.#r?.keys.find((o)=>o.kid===e):void 0;if(n!==void 0)return n;let r=await(await this.#n(tl)).json();if(typeof r.jwks_uri!=="string")return;let i=await(await this.#n(r.jwks_uri)).json();return this.#r={at:this.#t(),keys:i.keys??[]},this.#r.keys.find((o)=>o.kid===e)}}class On extends Error{status;constructor(e,t){super(t);this.status=e}}var si={m4a:"audio/mp4",mp4:"audio/mp4",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"audio/webm",aac:"audio/aac"};function ci(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&&si[n]!==void 0)return{url:r,mimeType:si[n],signed:!0};if(t.contentType.startsWith("audio/")&&t.contentUrl!==void 0)return{url:t.contentUrl,mimeType:t.contentType,signed:!1}}return}var ul=new Set(["png","jpg","jpeg","gif","webp"]);function li(e){let t=[];for(let n of e.attachments??[]){let r=n.content?.fileType?.toLowerCase(),i=n.content?.downloadUrl;if(n.contentType==="application/vnd.microsoft.teams.file.download.info"&&i!==void 0&&r!==void 0&&ul.has(r))t.push({url:i,signed:!0});else if(n.contentType.startsWith("image/")&&n.contentUrl!==void 0)t.push({url:n.contentUrl,signed:!1})}return t}var dl={"&nbsp;":" ","&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"};function fl(e){let t=e.recipient?.id,n=e.text??"";for(let r of e.entities??[]){if(r.type!=="mention"||r.text===void 0)continue;n=n.replace(r.text,r.mentioned?.id===t?"":r.mentioned?.name??"")}return n.replace(/<[^<>]*>/g,"").replace(/&(nbsp|amp|lt|gt|quot|#39);/g,(r)=>dl[r]??r).replace(/\s+/g," ").trim()}function hl(e){let t=e.recipient?.id;return(e.entities??[]).some((n)=>n.type==="mention"&&n.mentioned?.id===t)}function pl(e){return e.channelData?.tenant?.id??e.conversation?.tenantId}function ml(e){if(e.type!=="message"||e.conversation===void 0)return;if(e.from===void 0||e.from.id===e.recipient?.id)return;if((e.conversation.conversationType??"personal")!=="personal"&&!hl(e))return;let n=fl(e);if(n===""&&ci(e)===void 0&&li(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 ui{id;type="teams";limits={maxMessageChars:4000,idempotentSend:!1};#e;#n;#t;#r;#o;#i;#a;constructor(e){this.id=e.id,this.#e=e.auth,this.#n=e.tenantId,this.#r=e.agentId,this.#t=e.fetch??((t,n)=>fetch(t,n)),this.#o=ll(e.dir,V.stateDir,`teams-${e.id}.json`),this.#a=gl(this.#o)}async start(e){this.#i=e,e.status("connected",`webhook — POST /v1/channels/${this.id}/webhook/${this.#r??"<agent>"}`)}async stop(){this.#i?.status("disconnected"),this.#i=void 0}async webhook(e){let t=e.body;if(t===void 0||typeof t!=="object"||typeof t.type!=="string")return{status:400,detail:"not an activity"};try{await this.#e.verify(e.headers.authorization,t)}catch(s){if(s instanceof fe)return{status:401,detail:s.message};return this.#i?.status("error",`cannot verify activities: ${String(s)}`),{status:503,detail:"cannot verify right now"}}let n=this.#i;if(n===void 0)return{status:503,detail:"channel not started"};if(this.#n!==void 0&&pl(t)!==this.#n)return{status:200,detail:"other tenant"};if(t.serviceUrl?.startsWith("https://")===!0&&t.conversation!==void 0)this.#l(t.conversation.id,t.serviceUrl);let r=ml(t);if(r===void 0)return{status:200};let i=ci(t),o=li(t).map((s)=>({fetch:(c)=>this.#c(s.url,s.signed,c)}));return n.receive({...r,...o.length===0?{}:{images:o},...i===void 0?{}:{audio:{mimeType:i.mimeType,fetch:(s)=>this.#c(i.url,i.signed,s)}}}),{status:200}}async send(e,t){return this.#s(e.recipient,{type:"message",text:e.text,textFormat:"markdown"},t)}async typing(e){await this.#s(e,{type:"typing"})}async#s(e,t,n){let r=this.#a[e];if(r===void 0)return{ok:!1,retryable:!1,error:{code:"teams_conversation_unknown",message:`No Teams message has arrived from conversation ${e}, so there is no service address to reply to.`,hint:"Teams gives a bot the address of a conversation only when a message arrives from it. Have someone message the bot in that chat once; a schedule can deliver there afterwards."}};let i;try{i=await this.#e.token(n)}catch(a){let h=a instanceof On?a.status:0;return{ok:!1,retryable:h===0||h>=500,error:{code:"teams_token_refused",message:`Entra ID did not issue the bot a token: ${a instanceof Error?a.message:String(a)}`,hint:"Check the app id, the password in the env var the channel names, and tenantId (the bot's own tenant for a single-tenant registration). A wrong secret is permanent; an outage is retried."}}}let o=`${r.replace(/\/?$/,"/")}v3/conversations/${encodeURIComponent(e)}/activities`,s;try{s=await this.#t(o,{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify(t),...n===void 0?{}:{signal:n}})}catch(a){return{ok:!1,retryable:!0,error:{code:"teams_unreachable",message:`Cannot reach ${r}: ${a instanceof Error?a.message:String(a)}`,hint:"Allow outbound HTTPS to smba.trafficmanager.net (the Teams service URLs) and login.microsoftonline.com. Retried."}}}if(s.ok){let a=await s.json().catch(()=>({}));return{ok:!0,...a.id===void 0?{}:{providerMessageId:a.id}}}let c=(await s.text().catch(()=>"")).slice(0,300),l=Number(s.headers.get("retry-after"));return{ok:!1,retryable:s.status===429||s.status>=500,...Number.isFinite(l)&&l>0?{retryAfterMs:l*1000}:{},error:{code:"teams_send_failed",message:`Teams refused the reply (${s.status}): ${c}`,hint:s.status===403?"The bot is not a member of that conversation any more (removed from the chat or team), or its registration does not allow this tenant.":"Teams' own words are above. 429 and 5xx are retried; anything else is not."}}}async#c(e,t,n){let r=t?{}:{authorization:`Bearer ${await this.#e.token(n)}`},i=await this.#t(e,{method:"GET",headers:r,signal:n});if(!i.ok)throw Error(`Teams would not serve the file (${i.status})`);return new Uint8Array(await i.arrayBuffer())}#l(e,t){if(this.#a[e]===t)return;this.#a={...this.#a,[e]:t},il(cl(this.#o),{recursive:!0});let n=`${this.#o}.partial`;al(n,`${JSON.stringify(this.#a,null,2)}
8
- `),ol(n,this.#o)}}function gl(e){try{let t=JSON.parse(sl(e,"utf8"));if(typeof t!=="object"||t===null)return{};return Object.fromEntries(Object.entries(t).filter((n)=>typeof n[1]==="string"))}catch{return{}}}var oi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function An(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var Nn=(e)=>{let t=(s)=>`channels[${e.id}].${s}`,n=An(e.config,"appId");if(n===void 0||!oi.test(n))throw new Q({code:"teams_app_id_invalid",message:`Channel "${e.id}" needs appId, the bot's Entra application id.`,hint:"It is the GUID on the Azure Bot resource (Configuration → Microsoft App ID). Not a secret, so it is written here; the password goes in an env var named by passwordEnv. The agent starts either way, with this channel reported broken.",field:t("appId")});let r=An(e.config,"passwordEnv")??"TEAMS_APP_PASSWORD",i=e.env[r];if(i===void 0||i==="")throw new Q({code:"teams_password_missing",message:`Channel "${e.id}" needs ${r}, which is not set.`,hint:`Put the bot's client secret in ${r}, in the environment or the .env beside the manifest. It is refused here rather than at the first reply, because an unset variable needs no round trip to Microsoft to discover.`,field:t("passwordEnv")});let o=An(e.config,"tenantId");if(o!==void 0&&!oi.test(o))throw new Q({code:"teams_tenant_invalid",message:`Channel "${e.id}" declares tenantId "${o}", which is not a tenant id.`,hint:"The Entra tenant (directory) id, a GUID. Omit it only for a legacy multi-tenant bot registration.",field:t("tenantId")});return new ui({id:e.id,agentId:e.agentId,dir:e.dir,auth:new ai({appId:n,password:i,...o===void 0?{}:{tenantId:o}}),...o===void 0?{}:{tenantId:o}})},yl="0.1.0",di={name:"channel-teams",version:yl,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["login.botframework.com","login.microsoftonline.com","smba.trafficmanager.net"]},{kind:"env",vars:["TEAMS_APP_PASSWORD"]}],setup(e){e.defineChannel("teams",Nn)}};import{readFile as fi}from"node:fs/promises";import{basename as hi}from"node:path";class Ne extends Error{status;retryable;retryAfterMs;detail;constructor(e){super(e.message);this.name="TelegramApiError",this.status=e.status,this.retryable=e.retryable,this.retryAfterMs=e.retryAfterMs,this.detail=e.detail}}var wl="https://api.telegram.org";class Cn{#e;#n;#t;constructor(e){this.#e=e.token,this.#n=e.fetch??((t,n)=>fetch(t,n)),this.#t=go(e.baseUrl??wl)}async call(e,t,n){let r;try{r=await this.#n(`${this.#t}/bot${this.#e}/${e}`,{method:"POST",...t instanceof FormData?{body:t}:{headers:{"content-type":"application/json"},body:JSON.stringify(t??{})},...n===void 0?{}:{signal:n}})}catch(o){throw new Ne({message:`Telegram ${e} did not complete: ${o instanceof Error?o.message:String(o)}`,status:0,retryable:!0,detail:{code:"telegram_unreachable",message:`Could not reach the Telegram Bot API for ${e}.`,hint:"Check network access from this host. api.telegram.org is blocked in some networks and from some cloud regions; a webhook deployment behind a proxy still needs outbound access for sendMessage."}})}let i=await r.json().catch(()=>({}));if(r.ok&&i.ok&&i.result!==void 0)return i.result;throw vl(e,r.status,i)}getMe(e){return this.call("getMe",{},e)}getUpdates(e,t){return this.call("getUpdates",{offset:e.offset,timeout:e.timeout,limit:e.limit??100,allowed_updates:["message"]},t)}sendMessage(e,t){return this.call("sendMessage",{chat_id:e.chatId,text:e.text,...e.threadId===void 0?{}:{message_thread_id:e.threadId}},t)}sendPhoto(e,t){let n=new FormData;if(n.set("chat_id",e.chatId),n.set("photo",e.photo,e.filename),e.caption!==void 0&&e.caption!=="")n.set("caption",e.caption);if(e.threadId!==void 0)n.set("message_thread_id",String(e.threadId));return this.call("sendPhoto",n,t)}sendVoice(e,t){let n=new FormData;if(n.set("chat_id",e.chatId),n.set("voice",e.voice,e.filename),e.threadId!==void 0)n.set("message_thread_id",String(e.threadId));return this.call("sendVoice",n,t)}getFile(e,t){return this.call("getFile",{file_id:e},t)}async download(e,t){let n=await this.#n(`${this.#t}/file/bot${this.#e}/${e}`,{...t===void 0?{}:{signal:t}});if(!n.ok)throw new Ne({message:`Downloading ${e} failed with HTTP ${n.status}`,status:n.status,retryable:n.status>=500,detail:{code:"telegram_download_failed",message:`Telegram would not serve ${e} (${n.status}).`,hint:"Bots may download files up to 20 MB; a larger voice note cannot be fetched through the Bot API."}});return new Uint8Array(await n.arrayBuffer())}sendChatAction(e){return this.call("sendChatAction",{chat_id:e.chatId,action:"typing",...e.threadId===void 0?{}:{message_thread_id:e.threadId}})}setWebhook(e,t){return this.call("setWebhook",{url:e.url,allowed_updates:["message"],...e.secretToken===void 0?{}:{secret_token:e.secretToken},...e.dropPending===void 0?{}:{drop_pending_updates:e.dropPending}},t)}deleteWebhook(e){return this.call("deleteWebhook",{},e)}}function vl(e,t,n){let r=n.description??`HTTP ${t}`,i=n.error_code??t,o=n.parameters?.retry_after;if(i===429)return new Ne({message:`Telegram rate-limited ${e}: ${r}`,status:i,retryable:!0,...o===void 0?{}:{retryAfterMs:o*1000},detail:{code:"telegram_rate_limited",message:`Telegram rate-limited ${e}.`,hint:o===void 0?"The outbox will back off and retry. Sustained rate limiting on one chat usually means replies are being split into many chunks — check the reply length.":`Telegram asked for ${o}s. The outbox honours that verbatim rather than applying its own backoff.`}});if(i===401)return new Ne({message:`Telegram rejected the bot token on ${e}: ${r}`,status:i,retryable:!1,detail:{code:"telegram_unauthorized",message:"The Telegram bot token was rejected.",hint:"Check the variable named by the channel's tokenEnv. A token is revoked whenever /revoke is sent to @BotFather, and a regenerated token invalidates the old one immediately."}});if(i===409)return new Ne({message:`Telegram reports a conflicting ${e}: ${r}`,status:i,retryable:!0,detail:{code:"telegram_conflict",message:"Another instance of this bot is already receiving updates.",hint:"Telegram allows one getUpdates consumer per bot token. Stop the other process — another terminal, a container that did not exit — or, if a webhook was registered earlier, this channel's own start clears it. Retried, so it recovers on its own once the other side stops."}});if(i===400&&/too long/i.test(r))return new Ne({message:`Telegram refused ${e}: ${r}`,status:i,retryable:!1,detail:{code:"telegram_message_too_long",message:"A chunk exceeded Telegram's message limit.",hint:"This is a chunking bug, not a configuration problem: the transport declares maxMessageChars and core splits to it. Report the reply length — the splitter reserves room for a code-fence reopen, so the effective limit is slightly under 4096."}});let s=i===400||i===403;return new Ne({message:`Telegram refused ${e}: ${r}`,status:i,retryable:!s,detail:{code:s?"telegram_refused":"telegram_error",message:`Telegram refused ${e}: ${r}`,hint:s?"Telegram reports this as a client error, so it is not retried. The usual causes are a chat the bot was removed from, a user who blocked it, or a chat id from a different bot — a chat id is not portable between bots.":"Treated as transient and retried with backoff. A 5xx from Telegram is usually brief."}})}var bl=4096,_l=30,pi=[1000,2000,5000,15000,30000],kl=350;class gi{id;type="telegram";limits={maxMessageChars:bl,idempotentSend:!1,minSendIntervalMs:kl,attachments:!0,voiceNotes:!0};#e;#n;#t;#r;#o;#i=0;#a=!1;#s;#c;constructor(e){this.id=e.id,this.#e=e.api??new Cn({token:e.token}),this.#n=e.mode,this.#t=e.webhookUrl,this.#r=e.secretToken}async start(e){if(this.#a)return;if(this.#a=!0,this.#o=e,this.#s=new AbortController,this.#n==="webhook"){let t=this.#t;if(t===void 0||t===""){e.status("error","no webhookUrl"),e.error({code:"telegram_webhook_url_missing",message:`Channel "${this.id}" is in webhook mode but declares no webhookUrl.`,hint:"Set webhookUrl to the public HTTPS address this runtime is reachable at, ending in /v1/channels/<channelId>/webhook/<agentId>. Telegram will not deliver to plain HTTP, and a missing registration looks identical to a bot nobody is messaging.",field:`channels[${this.id}].webhookUrl`});return}try{await this.#e.setWebhook({url:t,...this.#r===void 0?{}:{secretToken:this.#r}}),e.status("connected",`webhook at ${t}`)}catch(n){e.status("error",n instanceof Error?n.message:String(n)),e.error(In(n,`registering the webhook for channel "${this.id}"`))}return}this.#c=this.#l(e,this.#s.signal)}async stop(){if(!this.#a)return;this.#a=!1,this.#s?.abort(),await this.#c?.catch(()=>{}),this.#c=void 0,this.#o?.status("disconnected"),this.#o=void 0}async send(e,t){let n=mi(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 fi(r.path)],{type:"audio/ogg"}),filename:hi(r.path),...n===void 0?{}:{threadId:n}},t):await this.#e.sendPhoto({chatId:e.recipient,photo:new Blob([await fi(r.path)],{type:r.mimeType}),filename:hi(r.path),caption:e.text,...n===void 0?{}:{threadId:n}},t);return{ok:!0,providerMessageId:String(i.message_id)}}catch(r){if(r instanceof Ne)return{ok:!1,retryable:r.retryable,error:r.detail,...r.retryAfterMs===void 0?{}:{retryAfterMs:r.retryAfterMs}};return{ok:!1,retryable:!0,error:{code:"telegram_send_failed",message:r instanceof Error?r.message:String(r),hint:"An unclassified failure from the Telegram transport. Retried, because a failure nobody recognised is not a failure known to be permanent."}}}}async typing(e,t){let n=mi(t);await this.#e.sendChatAction({chatId:e,...n===void 0?{}:{threadId:n}})}async webhook(e){if(this.#r!==void 0){let r=e.headers["x-telegram-bot-api-secret-token"]??"";if(!$l(r,this.#r))return{status:401,detail:"bad secret token"}}let t=this.#o;if(t===void 0)return{status:503,detail:"channel not started"};let n=e.body;if(n===void 0||typeof n!=="object")return{status:400,detail:"not an update"};return this.#u(t,n),{status:200}}async#l(e,t){let n=0,r=!1;try{await this.#e.deleteWebhook(t)}catch{}try{let i=await this.#e.getMe(t);r=!0,e.status("connected",i.username===void 0?"long-poll":`@${i.username}, long-poll`)}catch(i){if(t.aborted)return;e.status("error",i instanceof Error?i.message:String(i)),e.error(In(i,`checking the bot token for channel "${this.id}"`))}while(this.#a&&!t.aborted)try{let i=await this.#e.getUpdates({offset:this.#i,timeout:_l},t);if(n>0)n=0,r=!0,e.status("connected","polling resumed");else if(!r)r=!0,e.status("connected","long-poll");for(let o of i)this.#i=Math.max(this.#i,o.update_id+1),this.#u(e,o)}catch(i){if(t.aborted)return;let o=pi[Math.min(n,pi.length-1)]??1000;if(n+=1,n===1||n%8===0)e.status("error",i instanceof Error?i.message:String(i)),e.error(In(i,`polling channel "${this.id}"`));await El(o,t)}}#u(e,t){let n=t.message;if(n===void 0)return;let r=n.text??n.caption??"",i=n.voice??n.audio,o=Sl(n);if(r.trim()===""&&i===void 0&&o===void 0)return;if(n.from?.is_bot===!0)return;let s=Tl(n,r),c=o===void 0?[]:[{...o.file_size===void 0?{}:{sizeBytes:o.file_size},fetch:(l)=>this.#d(o.file_id,"photo",l)}];e.receive({...s,...c.length===0?{}:{images:c},...i===void 0?{}:{audio:{mimeType:i.mime_type??"audio/ogg",...i.duration===void 0?{}:{durationS:i.duration},...i.file_size===void 0?{}:{sizeBytes:i.file_size},fetch:(l)=>this.#d(i.file_id,"voice note",l)}}})}async#d(e,t,n){let r=await this.#e.getFile(e,n);if(r.file_path===void 0)throw Error(`Telegram returned no file path for the ${t}`);return this.#e.download(r.file_path,n)}}function Sl(e){let t=e.photo??[];if(t.length>0)return t.findLast((r)=>(r.file_size??0)<=so)??t[0];let n=e.document;return n?.mime_type?.startsWith("image/")===!0?n:void 0}function Tl(e,t){let n=e.from?.username,r=[e.from?.first_name,e.from?.last_name].filter(Boolean).join(" ");return{providerMessageId:`${e.chat.id}:${e.message_id}`,peerId:String(e.chat.id),...e.from===void 0?{}:{senderId:String(e.from.id)},...n===void 0?{}:{senderHandle:`@${n}`},...r===""?{}:{senderName:r},...e.message_thread_id===void 0?{}:{thread:String(e.message_thread_id)},text:t,receivedAt:new Date(e.date*1000).toISOString()}}function mi(e){if(e===void 0)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function In(e,t){if(e instanceof Ne)return e.detail;return{code:"telegram_channel_error",message:`${t} failed: ${e instanceof Error?e.message:String(e)}`,hint:"The channel keeps retrying and the rest of the runtime is unaffected. If this repeats, check network access to api.telegram.org and the token named by tokenEnv."}}function $l(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function El(e,t){return new Promise((n)=>{let r=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}var Pn=(e)=>{let t=e.config,n=ut(t,"tokenEnv")??"TELEGRAM_BOT_TOKEN",r=e.env[n];if(r===void 0||r==="")throw new Q({code:"telegram_token_missing",message:`Channel "${e.id}" needs ${n}, which is not set.`,hint:`Export ${n}, or add it to the .env beside the manifest — then restart the agent. Get a token from @BotFather with /newbot. The agent starts either way: a channel is optional, so this channel is reported broken rather than blocking the load. It is refused here rather than at the first poll because an unset variable is a configuration mistake and needs no network round trip to discover.`,field:`channels[${e.id}].tokenEnv`});let i=ut(t,"mode")??"longpoll";if(i!=="longpoll"&&i!=="webhook")throw new Q({code:"telegram_mode_invalid",message:`Channel "${e.id}" declares mode "${i}".`,hint:"mode is longpoll or webhook, and the agent starts either way with this channel reported broken. Long-poll needs no inbound connectivity and is the right default for a laptop or a private network; webhook needs a public HTTPS URL and is lower latency.",field:`channels[${e.id}].mode`});let o=ut(t,"secretTokenEnv"),s=o===void 0?void 0:e.env[o];if(o!==void 0&&(s===void 0||s===""))throw new Q({code:"telegram_secret_missing",message:`Channel "${e.id}" names secretTokenEnv ${o}, which is not set.`,hint:`Export ${o} with any random string, or remove secretTokenEnv. Naming a variable and leaving it empty would start a webhook that verifies nothing, which is worse than one that never claimed to.`,field:`channels[${e.id}].secretTokenEnv`});let c=ut(t,"apiBaseUrl"),l=ut(t,"webhookUrl");return new gi({id:e.id,token:r,mode:i,...l===void 0?{}:{webhookUrl:l},...s===void 0||s===""?{}:{secretToken:s},...c===void 0?{}:{api:new Cn({token:r,baseUrl:c})}})};function ut(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}var Al="0.1.0",yi={name:"telegram",version:Al,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["api.telegram.org"]},{kind:"env",vars:["TELEGRAM_BOT_TOKEN"]}],setup(e){e.defineChannel("telegram",Pn)}};import{createRequire as Ol}from"node:module";import{isAbsolute as Yl,resolve as Xl}from"node:path";import{appendFile as Ki,mkdir as hm,readFile as pm}from"node:fs/promises";import{join as qi}from"node:path";import{appendFile as ao,mkdir as mm,readFile as gm,writeFile as ym}from"node:fs/promises";import{join as wm}from"node:path";import{chmodSync as Hi,mkdirSync as _g,readdirSync as kg,rmSync as Sg}from"node:fs";import{readFile as Vi}from"node:fs/promises";import{join as Tg}from"node:path";var C=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qt=Ol(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"),o=Symbol.for("yaml.scalar"),s=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,h=(y)=>!!y&&typeof y==="object"&&y[c]===r,f=(y)=>!!y&&typeof y==="object"&&y[c]===i,d=(y)=>!!y&&typeof y==="object"&&y[c]===o,u=(y)=>!!y&&typeof y==="object"&&y[c]===s;function p(y){if(y&&typeof y==="object")switch(y[c]){case r:case s:return!0}return!1}function m(y){if(y&&typeof y==="object")switch(y[c]){case t:case r:case o:case s:return!0}return!1}var g=(y)=>(d(y)||p(y))&&!!y.anchor;e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=c,e.PAIR=i,e.SCALAR=o,e.SEQ=s,e.hasAnchor=g,e.isAlias=l,e.isCollection=p,e.isDocument=a,e.isMap=h,e.isNode=m,e.isPair=f,e.isScalar=d,e.isSeq=u}),Zt=C(function(e){var t=z(),n=Symbol("break visit"),r=Symbol("skip children"),i=Symbol("remove node");function o(d,u){let p=a(u);if(t.isDocument(d)){if(s(null,d.contents,p,Object.freeze([d]))===i)d.contents=null}else s(null,d,p,Object.freeze([]))}o.BREAK=n,o.SKIP=r,o.REMOVE=i;function s(d,u,p,m){let g=h(d,u,p,m);if(t.isNode(g)||t.isPair(g))return f(d,m,g),s(d,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=s(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=s("key",u.key,p,m);if(y===n)return n;else if(y===i)u.key=null;let w=s("value",u.value,p,m);if(w===n)return n;else if(w===i)u.value=null}}return g}async function c(d,u){let p=a(u);if(t.isDocument(d)){if(await l(null,d.contents,p,Object.freeze([d]))===i)d.contents=null}else await l(null,d,p,Object.freeze([]))}c.BREAK=n,c.SKIP=r,c.REMOVE=i;async function l(d,u,p,m){let g=await h(d,u,p,m);if(t.isNode(g)||t.isPair(g))return f(d,m,g),l(d,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(d){if(typeof d==="object"&&(d.Collection||d.Node||d.Value))return Object.assign({Alias:d.Node,Map:d.Node,Scalar:d.Node,Seq:d.Node},d.Value&&{Map:d.Value,Scalar:d.Value,Seq:d.Value},d.Collection&&{Map:d.Collection,Seq:d.Collection},d);return d}function h(d,u,p,m){if(typeof p==="function")return p(d,u,m);if(t.isMap(u))return p.Map?.(d,u,m);if(t.isSeq(u))return p.Seq?.(d,u,m);if(t.isPair(u))return p.Pair?.(d,u,m);if(t.isScalar(u))return p.Scalar?.(d,u,m);if(t.isAlias(u))return p.Alias?.(d,u,m);return}function f(d,u,p){let m=u[u.length-1];if(t.isCollection(m))m.items[d]=p;else if(t.isPair(m))if(d==="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=o,e.visitAsync=c}),ns=C(function(e){var t=z(),n=Zt(),r={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},i=(s)=>s.replace(/[!,[\]{}]/g,(c)=>r[c]);class o{constructor(s,c){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},o.defaultYaml,s),this.tags=Object.assign({},o.defaultTags,c)}clone(){let s=new o(this.yaml,this.tags);return s.docStart=this.docStart,s}atDocument(){let s=new o(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:o.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},o.defaultTags);break}return s}add(s,c){if(this.atNextDocument)this.yaml={explicit:o.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},o.defaultTags),this.atNextDocument=!1;let l=s.trim().split(/[ \t]+/),a=l.shift();switch(a){case"%TAG":{if(l.length!==2){if(c(0,"%TAG directive should contain exactly two parts"),l.length<2)return!1}let[h,f]=l;return this.tags[h]=f,!0}case"%YAML":{if(this.yaml.explicit=!0,l.length!==1)return c(0,"%YAML directive should contain exactly one part"),!1;let[h]=l;if(h==="1.1"||h==="1.2")return this.yaml.version=h,!0;else{let f=/^\d+\.\d+$/.test(h);return c(6,`Unsupported YAML version ${h}`,f),!1}}default:return c(0,`Unknown directive ${a}`,!0),!1}}tagName(s,c){if(s==="!")return"!";if(s[0]!=="!")return c(`Not a valid tag: ${s}`),null;if(s[1]==="<"){let f=s.slice(2,-1);if(f==="!"||f==="!!")return c(`Verbatim tags aren't resolved, so ${s} is invalid.`),null;if(s[s.length-1]!==">")c("Verbatim tags must end with a >");return f}let[,l,a]=s.match(/^(.*!)([^!]*)$/s);if(!a)c(`The ${s} tag has no suffix`);let h=this.tags[l];if(h)try{return h+decodeURIComponent(a)}catch(f){return c(String(f)),null}if(l==="!")return s;return c(`Could not resolve tag: ${s}`),null}tagString(s){for(let[c,l]of Object.entries(this.tags))if(s.startsWith(l))return c+i(s.substring(l.length));return s[0]==="!"?s:`!<${s}>`}toString(s){let c=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],l=Object.entries(this.tags),a;if(s&&l.length>0&&t.isNode(s.contents)){let h={};n.visit(s.contents,(f,d)=>{if(t.isNode(d)&&d.tag)h[d.tag]=!0}),a=Object.keys(h)}else a=[];for(let[h,f]of l){if(h==="!!"&&f==="tag:yaml.org,2002:")continue;if(!s||a.some((d)=>d.startsWith(f)))c.push(`%TAG ${h} ${f}`)}return c.join(`
9
- `)}}o.defaultYaml={explicit:!1,version:"1.2"},o.defaultTags={"!!":"tag:yaml.org,2002:"},e.Directives=o}),Wn=C(function(e){var t=z(),n=Zt();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,h){if(h.anchor)l.add(h.anchor)}}),l}function o(c,l){for(let a=1;;++a){let h=`${c}${a}`;if(!l.has(h))return h}}function s(c,l){let a=[],h=new Map,f=null;return{onAnchor:(d)=>{a.push(d),f??(f=i(c));let u=o(l,f);return f.add(u),u},setAnchors:()=>{for(let d of a){let u=h.get(d);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=d,p}}},sourceObjects:h}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=s,e.findNewAnchor=o}),rs=C(function(e){function t(n,r,i,o){if(o&&typeof o==="object")if(Array.isArray(o))for(let s=0,c=o.length;s<c;++s){let l=o[s],a=t(n,o,String(s),l);if(a===void 0)delete o[s];else if(a!==l)o[s]=a}else if(o instanceof Map)for(let s of Array.from(o.keys())){let c=o.get(s),l=t(n,o,s,c);if(l===void 0)o.delete(s);else if(l!==c)o.set(s,l)}else if(o instanceof Set)for(let s of Array.from(o)){let c=t(n,o,s,s);if(c===void 0)o.delete(s);else if(c!==s)o.delete(s),o.add(c)}else for(let[s,c]of Object.entries(o)){let l=t(n,o,s,c);if(l===void 0)delete o[s];else if(l!==c)o[s]=l}return n.call(r,i,o)}e.applyReviver=t}),Be=C(function(e){var t=z();function n(r,i,o){if(Array.isArray(r))return r.map((s,c)=>n(s,String(c),o));if(r&&typeof r.toJSON==="function"){if(!o||!t.hasAnchor(r))return r.toJSON(i,o);let s={aliasCount:0,count:1,res:void 0};o.anchors.set(r,s),o.onCreate=(l)=>{s.res=l,delete o.onCreate};let c=r.toJSON(i,o);if(o.onCreate)o.onCreate(c);return c}if(typeof r==="bigint"&&!o?.keep)return Number(r);return r}e.toJS=n}),Jn=C(function(e){var t=rs(),n=z(),r=Be();class i{constructor(o){Object.defineProperty(this,n.NODE_TYPE,{value:o})}clone(){let o=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)o.range=this.range.slice();return o}toJS(o,{mapAsMap:s,maxAliasCount:c,onAnchor:l,reviver:a}={}){if(!n.isDocument(o))throw TypeError("A document argument is required");let h={anchors:new Map,doc:o,keep:!0,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof c==="number"?c:100},f=r.toJS(this,"",h);if(typeof l==="function")for(let{count:d,res:u}of h.anchors.values())l(u,d);return typeof a==="function"?t.applyReviver(a,{"":f},"",f):f}}e.NodeBase=i}),Ht=C(function(e){var t=Wn(),n=Zt(),r=z(),i=Jn(),o=Be();class s extends i.NodeBase{constructor(l){super(r.ALIAS);this.source=l,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve(l,a){if(a?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let h;if(a?.aliasResolveCache)h=a.aliasResolveCache;else if(h=[],n.visit(l,{Node:(d,u)=>{if(r.isAlias(u)||r.hasAnchor(u))h.push(u)}}),a)a.aliasResolveCache=h;let f=void 0;for(let d of h){if(d===this)break;if(d.anchor===this.source)f=d}return f}toJSON(l,a){if(!a)return{source:this.source};let{anchors:h,doc:f,maxAliasCount:d}=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=h.get(u);if(!p)o.toJS(u,null,a),p=h.get(u);if(p?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(d>=0){if(p.count+=1,p.aliasCount===0)p.aliasCount=c(f,u,h);if(p.count*p.aliasCount>d)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return p.res}toString(l,a,h){let f=`*${this.source}`;if(l){if(t.anchorIsValid(this.source),l.options.verifyAliasOrder&&!l.anchors.has(this.source)){let d=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(d)}if(l.implicitKey)return`${f} `}return f}}function c(l,a,h){if(r.isAlias(a)){let f=a.resolve(l),d=h&&f&&h.get(f);return d?d.count*d.aliasCount:0}else if(r.isCollection(a)){let f=0;for(let d of a.items){let u=c(l,d,h);if(u>f)f=u}return f}else if(r.isPair(a)){let f=c(l,a.key,h),d=c(l,a.value,h);return Math.max(f,d)}return 1}e.Alias=s}),se=C(function(e){var t=z(),n=Jn(),r=Be(),i=(s)=>!s||typeof s!=="function"&&typeof s!=="object";class o extends n.NodeBase{constructor(s){super(t.SCALAR);this.value=s}toJSON(s,c){return c?.keep?this.value:r.toJS(this.value,s,c)}toString(){return String(this.value)}}o.BLOCK_FOLDED="BLOCK_FOLDED",o.BLOCK_LITERAL="BLOCK_LITERAL",o.PLAIN="PLAIN",o.QUOTE_DOUBLE="QUOTE_DOUBLE",o.QUOTE_SINGLE="QUOTE_SINGLE",e.Scalar=o,e.isScalarValue=i}),Vt=C(function(e){var t=Ht(),n=z(),r=se(),i="tag:yaml.org,2002:";function o(c,l,a){if(l){let h=a.filter((d)=>d.tag===l),f=h.find((d)=>!d.format)??h[0];if(!f)throw Error(`Tag ${l} not found`);return f}return a.find((h)=>h.identify?.(c)&&!h.format)}function s(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:h,onAnchor:f,onTagObj:d,schema:u,sourceObjects:p}=a,m=void 0;if(h&&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=o(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(d)d(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=s}),Hn=C(function(e){var t=Vt(),n=z(),r=Jn();function i(c,l,a){let h=a;for(let f=l.length-1;f>=0;--f){let d=l[f];if(typeof d==="number"&&Number.isInteger(d)&&d>=0){let u=[];u[d]=h,h=u}else h=new Map([[d,h]])}return t.createNode(h,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:c,sourceObjects:new Map})}var o=(c)=>c==null||typeof c==="object"&&!!c[Symbol.iterator]().next().done;class s extends r.NodeBase{constructor(c,l){super(c);Object.defineProperty(this,"schema",{value:l,configurable:!0,enumerable:!1,writable:!0})}clone(c){let l=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(c)l.schema=c;if(l.items=l.items.map((a)=>n.isNode(a)||n.isPair(a)?a.clone(c):a),this.range)l.range=this.range.slice();return l}addIn(c,l){if(o(c))this.add(l);else{let[a,...h]=c,f=this.get(a,!0);if(n.isCollection(f))f.addIn(h,l);else if(f===void 0&&this.schema)this.set(a,i(this.schema,h,l));else throw Error(`Expected YAML collection at ${a}. Remaining path: ${h}`)}}deleteIn(c){let[l,...a]=c;if(a.length===0)return this.delete(l);let h=this.get(l,!0);if(n.isCollection(h))return h.deleteIn(a);else throw Error(`Expected YAML collection at ${l}. Remaining path: ${a}`)}getIn(c,l){let[a,...h]=c,f=this.get(a,!0);if(h.length===0)return!l&&n.isScalar(f)?f.value:f;else return n.isCollection(f)?f.getIn(h,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 h=this.get(l,!0);return n.isCollection(h)?h.hasIn(a):!1}setIn(c,l){let[a,...h]=c;if(h.length===0)this.set(a,l);else{let f=this.get(a,!0);if(n.isCollection(f))f.setIn(h,l);else if(f===void 0&&this.schema)this.set(a,i(this.schema,h,l));else throw Error(`Expected YAML collection at ${a}. Remaining path: ${h}`)}}}e.Collection=s,e.collectionFromPath=i,e.isEmptyPath=o}),Gt=C(function(e){var t=(i)=>i.replace(/^(?!$)(?: $)?/gm,"#");function n(i,o){if(/^\n+$/.test(i))return i.substring(1);return o?i.replace(/^(?! *$)/gm,o):i}var r=(i,o,s)=>i.endsWith(`
10
- `)?n(s,o):s.includes(`
11
- `)?`
12
- `+n(s,o):(i.endsWith(" ")?"":" ")+s;e.indentComment=n,e.lineComment=r,e.stringifyComment=t}),Nl=C(function(e){var t="flow",n="block",r="quoted";function i(s,c,l="flow",{indentAtStart:a,lineWidth:h=80,minContentWidth:f=20,onFold:d,onOverflow:u}={}){if(!h||h<0)return s;if(h<f)f=0;let p=Math.max(1+f,1+h-c.length);if(s.length<=p)return s;let m=[],g={},y=h-c.length;if(typeof a==="number")if(a>h-Math.max(2,f))m.push(0);else y=h-a;let w=void 0,v=void 0,S=!1,k=-1,T=-1,A=-1;if(l===n){if(k=o(s,k,c.length),k!==-1)y=k+p}for(let I;I=s[k+=1];){if(l===r&&I==="\\"){switch(T=k,s[k+1]){case"x":k+=3;break;case"u":k+=5;break;case"U":k+=9;break;default:k+=1}A=k}if(I===`
13
- `){if(l===n)k=o(s,k,c.length);y=k+c.length+p,w=void 0}else{if(I===" "&&v&&v!==" "&&v!==`
14
- `&&v!=="\t"){let O=s[k+1];if(O&&O!==" "&&O!==`
15
- `&&O!=="\t")w=k}if(k>=y)if(w)m.push(w),y=w+p,w=void 0;else if(l===r){while(v===" "||v==="\t")v=I,I=s[k+=1],S=!0;let O=k>A+1?k-2:T-1;if(g[O])return s;m.push(O),g[O]=!0,y=O+p,w=void 0}else S=!0}v=I}if(S&&u)u();if(m.length===0)return s;if(d)d();let N=s.slice(0,m[0]);for(let I=0;I<m.length;++I){let O=m[I],R=m[I+1]||s.length;if(O===0)N=`
16
- ${c}${s.slice(0,R)}`;else{if(l===r&&g[O])N+=`${s[O]}\\`;N+=`
17
- ${c}${s.slice(O+1,R)}`}}return N}function o(s,c,l){let a=c,h=c+1,f=s[h];while(f===" "||f==="\t")if(c<h+l)f=s[++c];else{do f=s[++c];while(f&&f!==`
18
- `);a=c,h=c+1,f=s[h]}return a}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=i}),Yt=C(function(e){var t=se(),n=Nl(),r=(u,p)=>({indentAtStart:p?u.indent.length:u.indentAtStart,lineWidth:u.options.lineWidth,minContentWidth:u.options.minContentWidth}),i=(u)=>/^(%|---|\.\.\.)/m.test(u);function o(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 s(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="",S=0;for(let k=0,T=m[k];T;T=m[++k]){if(T===" "&&m[k+1]==="\\"&&m[k+2]==="n")v+=m.slice(S,k)+"\\ ",k+=1,S=k,T="\\";if(T==="\\")switch(m[k+1]){case"u":{v+=m.slice(S,k);let A=m.substr(k+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(k,6)}k+=5,S=k+1}break;case"n":if(g||m[k+2]==='"'||m.length<y)k+=1;else{v+=m.slice(S,k)+`
20
-
21
- `;while(m[k+2]==="\\"&&m[k+3]==="n"&&m[k+4]!=='"')v+=`
22
- `,k+=2;if(v+=w,m[k+2]===" ")v+="\\";k+=1,S=k+1}break;default:k+=1}}return v=S?v+m.slice(S):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 s(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=s;else{let y=u.includes('"'),w=u.includes("'");if(y&&!w)g=c;else if(w&&!y)g=s;else g=m?c:s}return g(u,p)}var a;try{a=new RegExp(`(^|(?<!
25
- ))
26
- +(?!
27
- |$)`,"g")}catch{a=/\n+(?!\n|$)/g}function h({comment:u,type:p,value:m},g,y,w){let{blockQuote:v,commentString:S,lineWidth:k}=g.options;if(!v||/\n[\t ]+$/.test(m))return l(m,g);let T=g.indent||(g.forceBlockIndent||i(m)?" ":""),A=v==="literal"?!0:v==="folded"||p===t.Scalar.BLOCK_FOLDED?!1:p===t.Scalar.BLOCK_LITERAL?!0:!o(m,k,T.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,`$&${T}`)}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 G=m.substring(0,re<F?re+1:F);if(G)m=m.substring(G.length),G=G.replace(/\n+/g,`$&${T}`);let ie=(x?T?"2":"1":"")+N;if(u){if(ie+=" "+S(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,`$&${T}`),ce=!1,J=r(g,!0);if(v!=="folded"&&p!==t.Scalar.BLOCK_FOLDED)J.onOverflow=()=>{ce=!0};let le=n.foldFlowLines(`${G}${j}${O}`,T,n.FOLD_BLOCK,J);if(!ce)return`>${ie}
35
- ${T}${le}`}return m=m.replace(/\n+/g,`$&${T}`),`|${ie}
36
- ${T}${G}${m}${O}`}function f(u,p,m,g){let{type:y,value:w}=u,{actualString:v,implicitKey:S,indent:k,indentStep:T,inFlow:A}=p;if(S&&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 S||A||!w.includes(`
38
- `)?l(w,p):h(u,p,m,g);if(!S&&!A&&y!==t.Scalar.PLAIN&&w.includes(`
39
- `))return h(u,p,m,g);if(i(w)){if(k==="")return p.forceBlockIndent=!0,h(u,p,m,g);else if(S&&k===T)return l(w,p)}let N=w.replace(/\n+/g,`$&
40
- ${k}`);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 S?N:n.foldFlowLines(N,k,n.FOLD_FLOW,r(p,!1))}function d(u,p,m,g){let{implicitKey:y,inFlow:w}=p,v=typeof u.value==="string"?u:Object.assign({},u,{value:String(u.value)}),{type:S}=u;if(S!==t.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(v.value))S=t.Scalar.QUOTE_DOUBLE}let k=(A)=>{switch(A){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return y||w?l(v.value,p):h(v,p,m,g);case t.Scalar.QUOTE_DOUBLE:return s(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}},T=k(S);if(T===null){let{defaultKeyType:A,defaultStringType:N}=p.options,I=y&&A||N;if(T=k(I),T===null)throw Error(`Unsupported default string type ${I}`)}return T}e.stringifyString=d}),Xt=C(function(e){var t=Wn(),n=z(),r=Gt(),i=Yt();function o(a,h){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,h),d;switch(f.collectionStyle){case"block":d=!1;break;case"flow":d=!0;break;default:d=null}return{anchors:new Set,doc:a,flowCollectionPadding:f.flowCollectionPadding?" ":"",indent:"",indentStep:typeof f.indent==="number"?" ".repeat(f.indent):" ",inFlow:d,options:f}}function s(a,h){if(h.tag){let u=a.filter((p)=>p.tag===h.tag);if(u.length>0)return u.find((p)=>p.format===h.format)??u[0]}let f=void 0,d;if(n.isScalar(h)){d=h.value;let u=a.filter((p)=>p.identify?.(d));if(u.length>1){let p=u.filter((m)=>m.test);if(p.length>0)u=p}f=u.find((p)=>p.format===h.format)??u.find((p)=>!p.format)}else d=h,f=a.find((u)=>u.nodeClass&&d instanceof u.nodeClass);if(!f){let u=d?.constructor?.name??(d===null?"null":typeof d);throw Error(`Tag not resolved for ${u} value`)}return f}function c(a,h,{anchors:f,doc:d}){if(!d.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??(h.default?null:h.tag);if(m)u.push(d.directives.tagString(m));return u.join(" ")}function l(a,h,f,d){if(n.isPair(a))return a.toString(h,f,d);if(n.isAlias(a)){if(h.doc.directives)return a.toString(h);if(h.resolvedAliases?.has(a))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(h.resolvedAliases)h.resolvedAliases.add(a);else h.resolvedAliases=new Set([a]);a=a.resolve(h.doc)}}let u=void 0,p=n.isNode(a)?a:h.doc.createNode(a,{onTagObj:(y)=>u=y});u??(u=s(h.doc.schema.tags,p));let m=c(p,u,h);if(m.length>0)h.indentAtStart=(h.indentAtStart??0)+m.length+1;let g=typeof u.stringify==="function"?u.stringify(p,h,f,d):n.isScalar(p)?i.stringifyString(p,h,f,d):p.toString(h,f,d);if(!m)return g;return n.isScalar(p)||g[0]==="{"||g[0]==="["?`${m} ${g}`:`${m}
41
- ${h.indent}${g}`}e.createStringifyContext=o,e.stringify=l}),Il=C(function(e){var t=z(),n=se(),r=Xt(),i=Gt();function o({key:s,value:c},l,a,h){let{allNullValues:f,doc:d,indent:u,indentStep:p,options:{commentString:m,indentSeq:g,simpleKeys:y}}=l,w=t.isNode(s)&&s.comment||null;if(y){if(w)throw Error("With simple keys, key nodes cannot have comments");if(t.isCollection(s)||!t.isNode(s)&&typeof s==="object")throw Error("With simple keys, collection cannot be used as a key value")}let v=!y&&(!s||w&&c==null&&!l.inFlow||t.isCollection(s)||(t.isScalar(s)?s.type===n.Scalar.BLOCK_FOLDED||s.type===n.Scalar.BLOCK_LITERAL:typeof s==="object"));l=Object.assign({},l,{allNullValues:!1,implicitKey:!v&&(y||!f),indent:u+p});let S=!1,k=!1,T=r.stringify(s,l,()=>S=!0,()=>k=!0);if(!v&&!l.inFlow&&T.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(S&&a)a();return T===""?"?":v?`? ${T}`:T}}else if(f&&!y||c==null&&v){if(T=`? ${T}`,w&&!S)T+=i.lineComment(T,l.indent,m(w));else if(k&&h)h();return T}if(S)w=null;if(v){if(w)T+=i.lineComment(T,l.indent,m(w));T=`? ${T}
42
- ${u}:`}else if(T=`${T}:`,w)T+=i.lineComment(T,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=d.createNode(c);if(l.implicitKey=!1,!v&&!w&&t.isScalar(c))l.indentAtStart=T.length+1;if(k=!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,()=>k=!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
- `),G=re!==-1,Te=l.inFlow??c.flow??c.items.length===0;if(G||!Te){let ie=!1;if(G&&(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(T+=x+R,l.inFlow){if(O&&a)a()}else if(I&&!O)T+=i.lineComment(T,l.indent,m(I));else if(k&&h)h();return T}e.stringifyPair=o}),is=C(function(e){var t=qt("process");function n(i,...o){if(i==="debug")console.log(...o)}function r(i,o){if(i==="debug"||i==="warn")if(typeof t.emitWarning==="function")t.emitWarning(o);else console.warn(o)}e.debug=n,e.warn=r}),Vn=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:s}),stringify:()=>r},o=(a,h)=>(i.identify(h)||t.isScalar(h)&&(!h.type||h.type===n.Scalar.PLAIN)&&i.identify(h.value))&&a?.doc.schema.tags.some((f)=>f.tag===i.tag&&f.default);function s(a,h,f){let d=l(a,f);if(t.isSeq(d))for(let u of d.items)c(a,h,u);else if(Array.isArray(d))for(let u of d)c(a,h,u);else c(a,h,d)}function c(a,h,f){let d=l(a,f);if(!t.isMap(d))throw Error("Merge sources must be maps or map aliases");let u=d.toJSON(null,a,Map);for(let[p,m]of u)if(h instanceof Map){if(!h.has(p))h.set(p,m)}else if(h instanceof Set)h.add(p);else if(!Object.prototype.hasOwnProperty.call(h,p))Object.defineProperty(h,p,{value:m,writable:!0,enumerable:!0,configurable:!0});return h}function l(a,h){return a&&t.isAlias(h)?h.resolve(a.doc,a):h}e.addMergeToJSMap=s,e.isMergeKey=o,e.merge=i}),ss=C(function(e){var t=is(),n=Vn(),r=Xt(),i=z(),o=Be();function s(l,a,{key:h,value:f}){if(i.isNode(h)&&h.addToJSMap)h.addToJSMap(l,a,f);else if(n.isMergeKey(l,h))n.addMergeToJSMap(l,a,f);else{let d=o.toJS(h,"",l);if(a instanceof Map)a.set(d,o.toJS(f,d,l));else if(a instanceof Set)a.add(d);else{let u=c(h,d,l),p=o.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,h){if(a===null)return"";if(typeof a!=="object")return String(a);if(i.isNode(l)&&h?.doc){let f=r.createStringifyContext(h.doc,{});f.anchors=new Set;for(let u of h.anchors.keys())f.anchors.add(u.anchor);f.inFlow=!0,f.inStringifyKey=!0;let d=l.toString(f);if(!h.mapKeyWarned){let u=JSON.stringify(d);if(u.length>40)u=u.substring(0,36)+'..."';t.warn(h.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${u}. Set mapAsMap: true to use object keys.`),h.mapKeyWarned=!0}return d}return JSON.stringify(a)}e.addPairToJSMap=s}),Ke=C(function(e){var t=Vt(),n=Il(),r=ss(),i=z();function o(c,l,a){let h=t.createNode(c,void 0,a),f=t.createNode(l,void 0,a);return new s(h,f)}class s{constructor(c,l=null){Object.defineProperty(this,i.NODE_TYPE,{value:i.PAIR}),this.key=c,this.value=l}clone(c){let{key:l,value:a}=this;if(i.isNode(l))l=l.clone(c);if(i.isNode(a))a=a.clone(c);return new s(l,a)}toJSON(c,l){let a=l?.mapAsMap?new Map:{};return r.addPairToJSMap(l,a,this)}toString(c,l,a){return c?.doc?n.stringifyPair(this,c,l,a):JSON.stringify(this)}}e.Pair=s,e.createPair=o}),os=C(function(e){var t=z(),n=Xt(),r=Gt();function i(l,a,h){return(a.inFlow??l.flow?s:o)(l,a,h)}function o({comment:l,items:a},h,{blockItemPrefix:f,flowChars:d,itemIndent:u,onChompKeep:p,onComment:m}){let{indent:g,options:{commentString:y}}=h,w=Object.assign({},h,{indent:u,type:null}),v=!1,S=[];for(let T=0;T<a.length;++T){let A=a[T],N=null;if(t.isNode(A)){if(!v&&A.spaceBefore)S.push("");if(c(h,S,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)S.push("");c(h,S,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;S.push(f+I)}let k;if(S.length===0)k=d.start+d.end;else{k=S[0];for(let T=1;T<S.length;++T){let A=S[T];k+=A?`
52
- ${g}${A}`:`
53
- `}}if(l){if(k+=`
54
- `+r.indentComment(y(l),g),m)m()}else if(v&&p)p();return k}function s({items:l},a,{flowChars:h,itemIndent:f}){let{indent:d,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 T=0;T<l.length;++T){let A=l[T],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
- `)),T<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:S,end:k}=h;if(v.length===0)return S+k;else{if(!y){let T=v.reduce((A,N)=>A+N.length+2,2);y=a.options.lineWidth>0&&T>a.options.lineWidth}if(y){let T=S;for(let A of v)T+=A?`
56
- ${u}${d}${A}`:`
57
- `;return`${T}
58
- ${d}${k}`}else return`${S}${p}${v.join(" ")}${p}${k}`}}function c({indent:l,options:{commentString:a}},h,f,d){if(f&&d)f=f.replace(/^\n+/,"");if(f){let u=r.indentComment(a(f),l);h.push(u.trimStart())}}e.stringifyCollection=i}),qe=C(function(e){var t=os(),n=ss(),r=Hn(),i=z(),o=Ke(),s=se();function c(a,h){let f=i.isScalar(h)?h.value:h;for(let d of a)if(i.isPair(d)){if(d.key===h||d.key===f)return d;if(i.isScalar(d.key)&&d.key.value===f)return d}return}class l extends r.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(a){super(i.MAP,a);this.items=[]}static from(a,h,f){let{keepUndefined:d,replacer:u}=f,p=new this(a),m=(g,y)=>{if(typeof u==="function")y=u.call(h,g,y);else if(Array.isArray(u)&&!u.includes(g))return;if(y!==void 0||d)p.items.push(o.createPair(g,y,f))};if(h instanceof Map)for(let[g,y]of h)m(g,y);else if(h&&typeof h==="object")for(let g of Object.keys(h))m(g,h[g]);if(typeof a.sortMapEntries==="function")p.items.sort(a.sortMapEntries);return p}add(a,h){let f;if(i.isPair(a))f=a;else if(!a||typeof a!=="object"||!("key"in a))f=new o.Pair(a,a?.value);else f=new o.Pair(a.key,a.value);let d=c(this.items,f.key),u=this.schema?.sortMapEntries;if(d){if(!h)throw Error(`Key ${f.key} already set`);if(i.isScalar(d.value)&&s.isScalarValue(f.value))d.value.value=f.value;else d.value=f.value}else if(u){let 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 h=c(this.items,a);if(!h)return!1;return this.items.splice(this.items.indexOf(h),1).length>0}get(a,h){let d=c(this.items,a)?.value;return(!h&&i.isScalar(d)?d.value:d)??void 0}has(a){return!!c(this.items,a)}set(a,h){this.add(new o.Pair(a,h),!0)}toJSON(a,h,f){let d=f?new f:h?.mapAsMap?new Map:{};if(h?.onCreate)h.onCreate(d);for(let u of this.items)n.addPairToJSMap(h,d,u);return d}toString(a,h,f){if(!a)return JSON.stringify(this);for(let d of this.items)if(!i.isPair(d))throw Error(`Map items must all be pairs; found ${JSON.stringify(d)} instead`);if(!a.allNullValues&&this.hasAllNullValues(!1))a=Object.assign({},a,{allNullValues:!0});return t.stringifyCollection(this,a,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:a.indent||"",onChompKeep:f,onComment:h})}}e.YAMLMap=l,e.findPair=c}),ht=C(function(e){var t=z(),n=qe(),r={collection:"map",default:!0,nodeClass:n.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(i,o){if(!t.isMap(i))o("Expected a mapping for this tag");return i},createNode:(i,o,s)=>n.YAMLMap.from(i,o,s)};e.map=r}),Ze=C(function(e){var t=Vt(),n=os(),r=Hn(),i=z(),o=se(),s=Be();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 h=l(a);if(typeof h!=="number")return!1;return this.items.splice(h,1).length>0}get(a,h){let f=l(a);if(typeof f!=="number")return;let d=this.items[f];return!h&&i.isScalar(d)?d.value:d}has(a){let h=l(a);return typeof h==="number"&&h<this.items.length}set(a,h){let f=l(a);if(typeof f!=="number")throw Error(`Expected a valid index, not ${a}.`);let d=this.items[f];if(i.isScalar(d)&&o.isScalarValue(h))d.value=h;else this.items[f]=h}toJSON(a,h){let f=[];if(h?.onCreate)h.onCreate(f);let d=0;for(let u of this.items)f.push(s.toJS(u,String(d++),h));return f}toString(a,h,f){if(!a)return JSON.stringify(this);return n.stringifyCollection(this,a,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(a.indent||"")+" ",onChompKeep:f,onComment:h})}static from(a,h,f){let{replacer:d}=f,u=new this(a);if(h&&Symbol.iterator in Object(h)){let p=0;for(let m of h){if(typeof d==="function"){let g=h instanceof Set?m:String(p++);m=d.call(h,g,m)}u.items.push(t.createNode(m,void 0,f))}}return u}}function l(a){let h=i.isScalar(a)?a.value:a;if(h&&typeof h==="string")h=Number(h);return typeof h==="number"&&Number.isInteger(h)&&h>=0?h:null}e.YAMLSeq=c}),pt=C(function(e){var t=z(),n=Ze(),r={collection:"seq",default:!0,nodeClass:n.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(i,o){if(!t.isSeq(i))o("Expected a sequence for this tag");return i},createNode:(i,o,s)=>n.YAMLSeq.from(i,o,s)};e.seq=r}),Qt=C(function(e){var t=Yt(),n={identify:(r)=>typeof r==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(r)=>r,stringify(r,i,o,s){return i=Object.assign({actualString:!0},i),t.stringifyString(r,i,o,s)}};e.string=n}),Gn=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}),as=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},o){if(r&&n.test.test(r)){let s=r[0]==="t"||r[0]==="T";if(i===s)return r}return i?o.options.trueStr:o.options.falseStr}};e.boolTag=n}),mt=C(function(e){function t({format:n,minFractionDigits:r,tag:i,value:o}){if(typeof o==="bigint")return String(o);let s=typeof o==="number"?o:Number(o);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let c=Object.is(o,-0)?"-0":JSON.stringify(o);if(!n&&r&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(c)&&!c.includes("e")){let l=c.indexOf(".");if(l<0)l=c.length,c+=".";let a=r-(c.length-l-1);while(a-- >0)c+="0"}return c}e.stringifyNumber=t}),cs=C(function(e){var t=se(),n=mt(),r={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(s)=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:n.stringifyNumber},i={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(s)=>parseFloat(s),stringify(s){let c=Number(s.value);return isFinite(c)?c.toExponential():n.stringifyNumber(s)}},o={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){let c=new t.Scalar(parseFloat(s)),l=s.indexOf(".");if(l!==-1&&s[s.length-1]==="0")c.minFractionDigits=s.length-l-1;return c},stringify:n.stringifyNumber};e.float=o,e.floatExp=i,e.floatNaN=r}),ls=C(function(e){var t=mt(),n=(l)=>typeof l==="bigint"||Number.isInteger(l),r=(l,a,h,{intAsBigInt:f})=>f?BigInt(l):parseInt(l.substring(a),h);function i(l,a,h){let{value:f}=l;if(n(f)&&f>=0)return h+f.toString(a);return t.stringifyNumber(l)}var o={identify:(l)=>n(l)&&l>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(l,a,h)=>r(l,2,8,h),stringify:(l)=>i(l,8,"0o")},s={identify:n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(l,a,h)=>r(l,0,10,h),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,h)=>r(l,2,16,h),stringify:(l)=>i(l,16,"0x")};e.int=s,e.intHex=c,e.intOct=o}),Cl=C(function(e){var t=ht(),n=Gn(),r=pt(),i=Qt(),o=as(),s=cs(),c=ls(),l=[t.map,r.seq,i.string,n.nullTag,o.boolTag,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float];e.schema=l}),Pl=C(function(e){var t=se(),n=ht(),r=pt();function i(a){return typeof a==="bigint"||Number.isInteger(a)}var o=({value:a})=>JSON.stringify(a),s=[{identify:(a)=>typeof a==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(a)=>a,stringify:o},{identify:(a)=>a==null,createNode:()=>new t.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:o},{identify:(a)=>typeof a==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(a)=>a==="true",stringify:o},{identify:i,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(a,h,{intAsBigInt:f})=>f?BigInt(a):parseInt(a,10),stringify:({value:a})=>i(a)?a.toString():JSON.stringify(a)},{identify:(a)=>typeof a==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:(a)=>parseFloat(a),stringify:o}],c={default:!0,tag:"",test:/^/,resolve(a,h){return h(`Unresolved plain scalar ${JSON.stringify(a)}`),a}},l=[n.map,r.seq].concat(s,c);e.schema=l}),us=C(function(e){var t=qt("buffer"),n=se(),r=Yt(),i={identify:(o)=>o instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(o,s){if(typeof t.Buffer==="function")return t.Buffer.from(o,"base64");else if(typeof atob==="function"){let c=atob(o.replace(/[\n\r]/g,"")),l=new Uint8Array(c.length);for(let a=0;a<c.length;++a)l[a]=c.charCodeAt(a);return l}else return s("This environment does not support reading binary tags; either Buffer or atob is required"),o},stringify({comment:o,type:s,value:c},l,a,h){if(!c)return"";let f=c,d;if(typeof t.Buffer==="function")d=f instanceof t.Buffer?f.toString("base64"):t.Buffer.from(f.buffer).toString("base64");else if(typeof btoa==="function"){let u="";for(let p=0;p<f.length;++p)u+=String.fromCharCode(f[p]);d=btoa(u)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(s??(s=n.Scalar.BLOCK_LITERAL),s!==n.Scalar.QUOTE_DOUBLE){let u=Math.max(l.options.lineWidth-l.indent.length,l.options.minContentWidth),p=Math.ceil(d.length/u),m=Array(p);for(let g=0,y=0;g<p;++g,y+=u)m[g]=d.substr(y,u);d=m.join(s===n.Scalar.BLOCK_LITERAL?`
59
- `:" ")}return r.stringifyString({comment:o,type:s,value:d},l,a,h)}};e.binary=i}),Yn=C(function(e){var t=z(),n=Ke(),r=se(),i=Ze();function o(l,a){if(t.isSeq(l))for(let h=0;h<l.items.length;++h){let f=l.items[h];if(t.isPair(f))continue;else if(t.isMap(f)){if(f.items.length>1)a("Each pair must have its own sequence indicator");let d=f.items[0]||new n.Pair(new r.Scalar(null));if(f.commentBefore)d.key.commentBefore=d.key.commentBefore?`${f.commentBefore}
60
- ${d.key.commentBefore}`:f.commentBefore;if(f.comment){let u=d.value??d.key;u.comment=u.comment?`${f.comment}
61
- ${u.comment}`:f.comment}f=d}l.items[h]=t.isPair(f)?f:new n.Pair(f)}else a("Expected a sequence for this tag");return l}function s(l,a,h){let{replacer:f}=h,d=new i.YAMLSeq(l);d.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;d.items.push(n.createPair(m,g,h))}return d}var c={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:o,createNode:s};e.createPairs=s,e.pairs=c,e.resolvePairs=o}),ds=C(function(e){var t=z(),n=Be(),r=qe(),i=Ze(),o=Yn();class s extends i.YAMLSeq{constructor(){super();this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=s.tag}toJSON(l,a){if(!a)return super.toJSON(l);let h=new Map;if(a?.onCreate)a.onCreate(h);for(let f of this.items){let d,u;if(t.isPair(f))d=n.toJS(f.key,"",a),u=n.toJS(f.value,d,a);else d=n.toJS(f,"",a);if(h.has(d))throw Error("Ordered maps must not include duplicate keys");h.set(d,u)}return h}static from(l,a,h){let f=o.createPairs(l,a,h),d=new this;return d.items=f.items,d}}s.tag="tag:yaml.org,2002:omap";var c={collection:"seq",identify:(l)=>l instanceof Map,nodeClass:s,default:!1,tag:"tag:yaml.org,2002:omap",resolve(l,a){let h=o.resolvePairs(l,a),f=[];for(let{key:d}of h.items)if(t.isScalar(d))if(f.includes(d.value))a(`Ordered maps must not include duplicate keys: ${d.value}`);else f.push(d.value);return Object.assign(new s,h)},createNode:(l,a,h)=>s.from(l,a,h)};e.YAMLOMap=s,e.omap=c}),Ml=C(function(e){var t=se();function n({value:o,source:s},c){if(s&&(o?r:i).test.test(s))return s;return o?c.options.trueStr:c.options.falseStr}var r={identify:(o)=>o===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:(o)=>o===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r}),Rl=C(function(e){var t=se(),n=mt(),r={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(s)=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:n.stringifyNumber},i={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(s)=>parseFloat(s.replace(/_/g,"")),stringify(s){let c=Number(s.value);return isFinite(c)?c.toExponential():n.stringifyNumber(s)}},o={identify:(s)=>typeof s==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){let c=new t.Scalar(parseFloat(s.replace(/_/g,""))),l=s.indexOf(".");if(l!==-1){let a=s.substring(l+1).replace(/_/g,"");if(a[a.length-1]==="0")c.minFractionDigits=a.length}return c},stringify:n.stringifyNumber};e.float=o,e.floatExp=i,e.floatNaN=r}),Ll=C(function(e){var t=mt(),n=(a)=>typeof a==="bigint"||Number.isInteger(a);function r(a,h,f,{intAsBigInt:d}){let u=a[0];if(u==="-"||u==="+")h+=1;if(a=a.substring(h).replace(/_/g,""),d){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,h,f){let{value:d}=a;if(n(d)){let u=d.toString(h);return d<0?"-"+f+u.substr(1):f+u}return t.stringifyNumber(a)}var o={identify:n,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(a,h,f)=>r(a,2,2,f),stringify:(a)=>i(a,2,"0b")},s={identify:n,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(a,h,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,h,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,h,f)=>r(a,2,16,f),stringify:(a)=>i(a,16,"0x")};e.int=c,e.intBin=o,e.intHex=l,e.intOct=s}),fs=C(function(e){var t=z(),n=Ke(),r=qe();class i extends r.YAMLMap{constructor(s){super(s);this.tag=i.tag}add(s){let c;if(t.isPair(s))c=s;else if(s&&typeof s==="object"&&"key"in s&&"value"in s&&s.value===null)c=new n.Pair(s.key,null);else c=new n.Pair(s,null);if(!r.findPair(this.items,c.key))this.items.push(c)}get(s,c){let l=r.findPair(this.items,s);return!c&&t.isPair(l)?t.isScalar(l.key)?l.key.value:l.key:l}set(s,c){if(typeof c!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof c}`);let l=r.findPair(this.items,s);if(l&&!c)this.items.splice(this.items.indexOf(l),1);else if(!l&&c)this.items.push(new n.Pair(s))}toJSON(s,c){return super.toJSON(s,c,Set)}toString(s,c,l){if(!s)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},s,{allNullValues:!0}),c,l);else throw Error("Set items must all have null values")}static from(s,c,l){let{replacer:a}=l,h=new this(s);if(c&&Symbol.iterator in Object(c))for(let f of c){if(typeof a==="function")f=a.call(c,f,f);h.items.push(n.createPair(f,null,l))}return h}}i.tag="tag:yaml.org,2002:set";var o={collection:"map",identify:(s)=>s instanceof Set,nodeClass:i,default:!1,tag:"tag:yaml.org,2002:set",createNode:(s,c,l)=>i.from(s,c,l),resolve(s,c){if(t.isMap(s))if(s.hasAllNullValues(!0))return Object.assign(new i,s);else c("Set items must all have null values");else c("Expected a mapping for this tag");return s}};e.YAMLSet=i,e.set=o}),hs=C(function(e){var t=mt();function n(c,l){let a=c[0],h=a==="-"||a==="+"?c.substring(1):c,f=(u)=>l?BigInt(u):Number(u),d=h.replace(/_/g,"").split(":").reduce((u,p)=>u*f(60)+f(p),f(0));return a==="-"?f(-1)*d:d}function r(c){let{value:l}=c,a=(u)=>u;if(typeof l==="bigint")a=(u)=>BigInt(u);else if(isNaN(l)||!isFinite(l))return t.stringifyNumber(c);let h="";if(l<0)h="-",l*=a(-1);let f=a(60),d=[l%f];if(l<60)d.unshift(0);else if(l=(l-d[0])/f,d.unshift(l%f),l>=60)l=(l-d[0])/f,d.unshift(l);return h+d.map((u)=>String(u).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var i={identify:(c)=>typeof c==="bigint"||Number.isInteger(c),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(c,l,{intAsBigInt:a})=>n(c,a),stringify:r},o={identify:(c)=>typeof c==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(c)=>n(c,!1),stringify:r},s={identify:(c)=>c instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(c){let l=c.match(s.test);if(!l)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,a,h,f,d,u,p]=l.map(Number),m=l[7]?Number((l[7]+"00").substr(1,3)):0,g=Date.UTC(a,h-1,f,d||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=o,e.intTime=i,e.timestamp=s}),xl=C(function(e){var t=ht(),n=Gn(),r=pt(),i=Qt(),o=us(),s=Ml(),c=Rl(),l=Ll(),a=Vn(),h=ds(),f=Yn(),d=fs(),u=hs(),p=[t.map,r.seq,i.string,n.nullTag,s.trueTag,s.falseTag,l.intBin,l.intOct,l.int,l.intHex,c.floatNaN,c.floatExp,c.float,o.binary,a.merge,h.omap,f.pairs,d.set,u.intTime,u.floatTime,u.timestamp];e.schema=p}),Dl=C(function(e){var t=ht(),n=Gn(),r=pt(),i=Qt(),o=as(),s=cs(),c=ls(),l=Cl(),a=Pl(),h=us(),f=Vn(),d=ds(),u=Yn(),p=xl(),m=fs(),g=hs(),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:h.binary,bool:o.boolTag,float:s.float,floatExp:s.floatExp,floatNaN:s.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:d.omap,pairs:u.pairs,seq:r.seq,set:m.set,timestamp:g.timestamp},v={"tag:yaml.org,2002:binary":h.binary,"tag:yaml.org,2002:merge":f.merge,"tag:yaml.org,2002:omap":d.omap,"tag:yaml.org,2002:pairs":u.pairs,"tag:yaml.org,2002:set":m.set,"tag:yaml.org,2002:timestamp":g.timestamp};function S(k,T,A){let N=y.get(T);if(N&&!k)return A&&!N.includes(f.merge)?N.concat(f.merge):N.slice();let I=N;if(!I)if(Array.isArray(k))I=[];else{let O=Array.from(y.keys()).filter((R)=>R!=="yaml11").map((R)=>JSON.stringify(R)).join(", ");throw Error(`Unknown schema "${T}"; use one of ${O} or define customTags array`)}if(Array.isArray(k))for(let O of k)I=I.concat(O);else if(typeof k==="function")I=k(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((G)=>JSON.stringify(G)).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=S}),ps=C(function(e){var t=z(),n=ht(),r=pt(),i=Qt(),o=Dl(),s=(l,a)=>l.key<a.key?-1:l.key>a.key?1:0;class c{constructor({compat:l,customTags:a,merge:h,resolveKnownTags:f,schema:d,sortMapEntries:u,toStringDefaults:p}){this.compat=Array.isArray(l)?o.getTags(l,"compat"):l?o.getTags(null,l):null,this.name=typeof d==="string"&&d||"core",this.knownTags=f?o.coreKnownTags:{},this.tags=o.getTags(a,this.name,h),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?s:null}clone(){let l=Object.create(c.prototype,Object.getOwnPropertyDescriptors(this));return l.tags=this.tags.slice(),l}}e.Schema=c}),jl=C(function(e){var t=z(),n=Xt(),r=Gt();function i(o,s){let c=[],l=s.directives===!0;if(s.directives!==!1&&o.directives){let u=o.directives.toString(o);if(u)c.push(u),l=!0;else if(o.directives.docStart)l=!0}if(l)c.push("---");let a=n.createStringifyContext(o,s),{commentString:h}=a.options;if(o.commentBefore){if(c.length!==1)c.unshift("");let u=h(o.commentBefore);c.unshift(r.indentComment(u,""))}let f=!1,d=null;if(o.contents){if(t.isNode(o.contents)){if(o.contents.spaceBefore&&l)c.push("");if(o.contents.commentBefore){let m=h(o.contents.commentBefore);c.push(r.indentComment(m,""))}a.forceBlockIndent=!!o.comment,d=o.contents.comment}let u=d?void 0:()=>f=!0,p=n.stringify(o.contents,a,()=>d=null,u);if(d)p+=r.lineComment(p,"",h(d));if((p[0]==="|"||p[0]===">")&&c[c.length-1]==="---")c[c.length-1]=`--- ${p}`;else c.push(p)}else c.push(n.stringify(o.contents,a));if(o.directives?.docEnd)if(o.comment){let u=h(o.comment);if(u.includes(`
62
- `))c.push("..."),c.push(r.indentComment(u,""));else c.push(`... ${u}`)}else c.push("...");else{let u=o.comment;if(u&&f)u=u.replace(/^\n+/,"");if(u){if((!f||d)&&c[c.length-1]!=="")c.push("");c.push(r.indentComment(h(u),""))}}return c.join(`
63
- `)+`
64
- `}e.stringifyDocument=i}),en=C(function(e){var t=Ht(),n=Hn(),r=z(),i=Ke(),o=Be(),s=ps(),c=jl(),l=Wn(),a=rs(),h=Vt(),f=ns();class d{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(d.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=(G)=>typeof G==="number"||G instanceof String||G 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:S,keepUndefined:k,onTagObj:T,tag:A}=g??{},{onAnchor:N,setAnchors:I,sourceObjects:O}=l.createNodeAnchors(this,v||"a"),R={aliasDuplicateObjects:w??!0,keepUndefined:k??!1,onAnchor:N,onTagObj:T,replacer:y,schema:this.schema,sourceObjects:O},x=h.createNode(p,A,R);if(S&&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 s.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 S={anchors:new Map,doc:this,keep:!p,mapAsMap:g===!0,mapKeyWarned:!1,maxAliasCount:typeof y==="number"?y:100},k=o.toJS(this.contents,m??"",S);if(typeof w==="function")for(let{count:T,res:A}of S.anchors.values())w(A,T);return typeof v==="function"?a.applyReviver(v,{"":k},"",k):k}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=d}),tn=C(function(e){class t extends Error{constructor(o,s,c,l){super();this.name=o,this.code=c,this.message=l,this.pos=s}}class n extends t{constructor(o,s,c){super("YAMLParseError",o,s,c)}}class r extends t{constructor(o,s,c){super("YAMLWarning",o,s,c)}}var i=(o,s)=>(c)=>{if(c.pos[0]===-1)return;c.linePos=c.pos.map((d)=>s.linePos(d));let{line:l,col:a}=c.linePos[0];c.message+=` at line ${l}, column ${a}`;let h=a-1,f=o.substring(s.lineStarts[l-1],s.lineStarts[l]).replace(/[\n\r]+$/,"");if(h>=60&&f.length>80){let d=Math.min(h-39,f.length-79);f="…"+f.substring(d),h-=d-1}if(f.length>80)f=f.substring(0,79)+"…";if(l>1&&/^ *$/.test(f.substring(0,h))){let d=o.substring(s.lineStarts[l-2],s.lineStarts[l-1]);if(d.length>80)d=d.substring(0,79)+`…
65
- `;f=d+f}if(/[^ ]/.test(f)){let d=1,u=c.linePos[1];if(u?.line===l&&u.col>a)d=Math.max(1,Math.min(u.col-a,80-h));let p=" ".repeat(h)+"^".repeat(d);c.message+=`:
66
-
67
- ${f}
68
- ${p}
69
- `}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=i}),nn=C(function(e){function t(n,{flow:r,indicator:i,next:o,offset:s,onError:c,parentIndent:l,startOnNewline:a}){let h=!1,f=a,d=a,u="",p="",m=!1,g=!1,y=null,w=null,v=null,S=null,k=null,T=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"||o?.type!=="flow-collection")&&O.source.includes("\t"))y=O;d=!0;break;case"comment":{if(!d)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(!T||i!=="seq-item-ind")h=!0}else p+=O.source;if(f=!0,m=!0,w||v)S=O;d=!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,d=!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,d=!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(T)c(O,"UNEXPECTED_TOKEN",`Unexpected ${O.source} in ${r??"collection"}`);T=O,f=i==="seq-item-ind"||i==="explicit-key-ind",d=!1;break;case"comma":if(r){if(k)c(O,"UNEXPECTED_TOKEN",`Unexpected , in ${r}`);k=O,f=!1,d=!1;break}default:c(O,"UNEXPECTED_TOKEN",`Unexpected ${O.type} token`),f=!1,d=!1}}let N=n[n.length-1],I=N?N.offset+N.source.length:s;if(g&&o&&o.type!=="space"&&o.type!=="newline"&&o.type!=="comma"&&(o.type!=="scalar"||o.source!==""))c(o.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(y&&(f&&y.indent<=l||o?.type==="block-map"||o?.type==="block-seq"))c(y,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:k,found:T,spaceBefore:h,comment:u,hasNewline:m,anchor:w,tag:v,newlineAfterProp:S,end:I,start:A??I}}e.resolveProps=t}),Xn=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}),ms=C(function(e){var t=Xn();function n(r,i,o){if(i?.type==="flow-collection"){let s=i.end[0];if(s.indent===r&&(s.source==="]"||s.source==="}")&&t.containsNewline(i))o(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}e.flowIndentCheck=n}),gs=C(function(e){var t=z();function n(r,i,o){let{uniqueKeys:s}=r.options;if(s===!1)return!1;let c=typeof s==="function"?s:(l,a)=>l===a||t.isScalar(l)&&t.isScalar(a)&&l.value===a.value;return i.some((l)=>c(l.key,o))}e.mapIncludes=n}),Ul=C(function(e){var t=Ke(),n=qe(),r=nn(),i=Xn(),o=ms(),s=gs(),c="All mapping items must start at the same column";function l({composeNode:a,composeEmptyNode:h},f,d,u,p){let g=new(p?.nodeClass??n.YAMLMap)(f.schema);if(f.atRoot)f.atRoot=!1;let y=d.offset,w=null;for(let v of d.items){let{start:S,key:k,sep:T,value:A}=v,N=r.resolveProps(S,{indicator:"explicit-key-ind",next:k??T?.[0],offset:y,onError:u,parentIndent:d.indent,startOnNewline:!0}),I=!N.found;if(I){if(k){if(k.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 k&&k.indent!==d.indent)u(y,"BAD_INDENT",c)}if(!N.anchor&&!N.tag&&!T){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(k))u(k??S[S.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(N.found?.indent!==d.indent)u(y,"BAD_INDENT",c);f.atKey=!0;let O=N.end,R=k?a(f,k,N,u):h(f,O,S,null,N,u);if(f.schema.compat)o.flowIndentCheck(d.indent,k,u);if(f.atKey=!1,s.mapIncludes(f,g.items,R))u(O,"DUPLICATE_KEY","Map keys must be unique");let x=r.resolveProps(T??[],{indicator:"map-value-ind",next:A,offset:R.range[2],onError:u,parentIndent:d.indent,startOnNewline:!k||k.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):h(f,y,T,null,x,u);if(f.schema.compat)o.flowIndentCheck(d.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=[d.offset,y,w??y],g}e.resolveBlockMap=l}),zl=C(function(e){var t=Ze(),n=nn(),r=ms();function i({composeNode:o,composeEmptyNode:s},c,l,a,h){let d=new(h?.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)d.comment=y.comment;continue}let w=g?o(c,g,y,a):s(c,y.end,m,null,y,a);if(c.schema.compat)r.flowIndentCheck(l.indent,g,a);u=w.range[2],d.items.push(w)}return d.range=[l.offset,u,p??u],d}e.resolveBlockSeq=i}),gt=C(function(e){function t(n,r,i,o){let s="";if(n){let c=!1,l="";for(let a of n){let{source:h,type:f}=a;switch(f){case"space":c=!0;break;case"comment":{if(i&&!c)o(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=h.substring(1)||" ";if(!s)s=d;else s+=l+d;l="";break}case"newline":if(s)l+=h;c=!0;break;default:o(a,"UNEXPECTED_TOKEN",`Unexpected ${f} at node end`)}r+=h.length}}return{comment:s,offset:r}}e.resolveEnd=t}),Fl=C(function(e){var t=z(),n=Ke(),r=qe(),i=Ze(),o=gt(),s=nn(),c=Xn(),l=gs(),a="Block collections are not allowed within flow collections",h=(d)=>d&&(d.type==="block-map"||d.type==="block-seq");function f({composeNode:d,composeEmptyNode:u},p,m,g,y){let w=m.start.source==="{",v=w?"flow map":"flow sequence",k=new(y?.nodeClass??(w?r.YAMLMap:i.YAMLSeq))(p.schema);k.flow=!0;let T=p.atRoot;if(T)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:G,sep:Te,value:ie}=F,j=s.resolveProps(re,{flow:v,indicator:"explicit-key-ind",next:G??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(k.comment)k.comment+=`
73
- `+j.comment;else k.comment=j.comment;A=j.end;continue}if(!w&&p.options.strict&&c.containsNewline(G))g(G,"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 J of re)switch(J.type){case"comma":case"space":break;case"comment":ce=J.source.substring(1);break e;default:break e}if(ce){let J=k.items[k.items.length-1];if(t.isPair(J))J=J.value??J.key;if(J.comment)J.comment+=`
74
- `+ce;else J.comment=ce;j.comment=j.comment.substring(ce.length+1)}}}if(!w&&!Te&&!j.found){let ce=ie?d(p,ie,j,g):u(p,j.end,Te,null,j,g);if(k.items.push(ce),A=ce.range[2],h(ie))g(ce.range,"BLOCK_IN_FLOW",a)}else{p.atKey=!0;let ce=j.end,J=G?d(p,G,j,g):u(p,ce,re,null,j,g);if(h(G))g(J.range,"BLOCK_IN_FLOW",a);p.atKey=!1;let le=s.resolveProps(Te??[],{flow:v,indicator:"map-value-ind",next:ie,offset:J.range[2],onError:g,parentIndent:m.indent,startOnNewline:!1});if(le.found){if(!w&&!j.found&&p.options.strict){if(Te)for(let $e of Te){if($e===le.found)break;if($e.type==="newline"){g($e,"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 He=ie?d(p,ie,le,g):le.found?u(p,le.end,Te,null,le,g):null;if(He){if(h(ie))g(He.range,"BLOCK_IN_FLOW",a)}else if(le.comment)if(J.comment)J.comment+=`
75
- `+le.comment;else J.comment=le.comment;let Tn=new n.Pair(J,He);if(p.options.keepSourceTokens)Tn.srcToken=F;if(w){let $e=k;if(l.mapIncludes(p,$e.items,J))g(ce,"DUPLICATE_KEY","Map keys must be unique");$e.items.push(Tn)}else{let $e=new r.YAMLMap(p.schema);$e.flow=!0,$e.items.push(Tn);let Jr=(He??J).range;$e.range=[J.range[0],Jr[1],Jr[2]],k.items.push($e)}A=He?He.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=T?`${x} must end with a ${N}`:`${x} in block collection must be sufficiently indented and end with a ${N}`;if(g(A,T?"MISSING_CHAR":"BAD_INDENT",F),I&&I.source.length!==1)O.unshift(I)}if(O.length>0){let x=o.resolveEnd(O,R,p.options.strict,g);if(x.comment)if(k.comment)k.comment+=`
76
- `+x.comment;else k.comment=x.comment;k.range=[m.offset,R,x.offset]}else k.range=[m.offset,R,R];return k}e.resolveFlowCollection=f}),Bl=C(function(e){var t=z(),n=se(),r=qe(),i=Ze(),o=Ul(),s=zl(),c=Fl();function l(h,f,d,u,p,m){let g=d.type==="block-map"?o.resolveBlockMap(h,f,d,u,m):d.type==="block-seq"?s.resolveBlockSeq(h,f,d,u,m):c.resolveFlowCollection(h,f,d,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(h,f,d,u,p){let m=u.tag,g=!m?null:f.directives.tagName(m.source,(T)=>p(m,"TAG_RESOLVE_FAILED",T));if(d.type==="block-seq"){let{anchor:T,newlineAfterProp:A}=u,N=T&&m?T.offset>m.offset?T:m:T??m;if(N&&(!A||A.offset<N.offset))p(N,"MISSING_CHAR","Missing newline after block sequence props")}let y=d.type==="block-map"?"map":d.type==="block-seq"?"seq":d.start.source==="{"?"map":"seq";if(!m||!g||g==="!"||g===r.YAMLMap.tagName&&y==="map"||g===i.YAMLSeq.tagName&&y==="seq")return l(h,f,d,p,g);let w=f.schema.tags.find((T)=>T.tag===g&&T.collection===y);if(!w){let T=f.schema.knownTags[g];if(T?.collection===y)f.schema.tags.push(Object.assign({},T,{default:!1})),w=T;else{if(T)p(m,"BAD_COLLECTION_TYPE",`${T.tag} used for ${y} collection, but expects ${T.collection??"scalar"}`,!0);else p(m,"TAG_RESOLVE_FAILED",`Unresolved tag: ${g}`,!0);return l(h,f,d,p,g)}}let v=l(h,f,d,p,g,w),S=w.resolve?.(v,(T)=>p(m,"TAG_RESOLVE_FAILED",T),f.options)??v,k=t.isNode(S)?S:new n.Scalar(S);if(k.range=v.range,k.tag=g,w?.format)k.format=w.format;return k}e.composeCollection=a}),ys=C(function(e){var t=se();function n(o,s,c){let l=s.offset,a=r(s,o.options.strict,c);if(!a)return{value:"",type:null,comment:"",range:[l,l,l]};let h=a.mode===">"?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,f=s.source?i(s.source):[],d=f.length;for(let S=f.length-1;S>=0;--S){let k=f[S][1];if(k===""||k==="\r")d=S;else break}if(d===0){let S=a.chomp==="+"&&f.length>0?`
77
- `.repeat(Math.max(1,f.length-1)):"",k=l+a.length;if(s.source)k+=s.source.length;return{value:S,type:h,comment:a.comment,range:[l,k,k]}}let u=s.indent+a.indent,p=s.offset+a.length,m=0;for(let S=0;S<d;++S){let[k,T]=f[S];if(T===""||T==="\r"){if(a.indent===0&&k.length>u)u=k.length}else{if(k.length<u)c(p+k.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(a.indent===0)u=k.length;if(m=S,u===0&&!o.atRoot)c(p,"BAD_INDENT","Block scalar values in collections must be indented");break}p+=k.length+T.length+1}for(let S=f.length-1;S>=d;--S)if(f[S][0].length>u)d=S+1;let g="",y="",w=!1;for(let S=0;S<m;++S)g+=f[S][0].slice(u)+`
78
- `;for(let S=m;S<d;++S){let[k,T]=f[S];p+=k.length+T.length+1;let A=T[T.length-1]==="\r";if(A)T=T.slice(0,-1);if(T&&k.length<u){let I=`Block scalar lines must not be less indented than their ${a.indent?"explicit indentation indicator":"first line"}`;c(p-T.length-(A?2:1),"BAD_INDENT",I),k=""}if(h===t.Scalar.BLOCK_LITERAL)g+=y+k.slice(u)+T,y=`
79
- `;else if(k.length>u||T[0]==="\t"){if(y===" ")y=`
80
- `;else if(!w&&y===`
81
- `)y=`
82
-
83
- `;g+=y+k.slice(u)+T,y=`
84
- `,w=!0}else if(T==="")if(y===`
85
- `)g+=`
86
- `;else y=`
87
- `;else g+=y+T,y=" ",w=!1}switch(a.chomp){case"-":break;case"+":for(let S=d;S<f.length;++S)g+=`
88
- `+f[S][0].slice(u);if(g[g.length-1]!==`
89
- `)g+=`
90
- `;break;default:g+=`
91
- `}let v=l+a.length+s.source.length;return{value:g,type:h,comment:a.comment,range:[l,v,v]}}function r({offset:o,props:s},c,l){if(s[0].type!=="block-scalar-header")return l(s[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:a}=s[0],h=a[0],f=0,d="",u=-1;for(let y=1;y<a.length;++y){let w=a[y];if(!d&&(w==="-"||w==="+"))d=w;else{let v=Number(w);if(!f&&v)f=v;else if(u===-1)u=o+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<s.length;++y){let w=s[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 S=w.source;if(S&&typeof S==="string")g+=S.length}}}return{mode:h,indent:f,chomp:d,comment:m,length:g}}function i(o){let s=o.split(/\n( *)/),c=s[0],l=c.match(/^( *)/),h=[l?.[1]?[l[1],c.slice(l[1].length)]:["",c]];for(let f=1;f<s.length;f+=2)h.push([s[f],s[f+1]]);return h}e.resolveBlockScalar=n}),ws=C(function(e){var t=se(),n=gt();function r(f,d,u){let{offset:p,type:m,source:g,end:y}=f,w,v,S=(A,N,I)=>u(p+A,N,I);switch(m){case"scalar":w=t.Scalar.PLAIN,v=i(g,S);break;case"single-quoted-scalar":w=t.Scalar.QUOTE_SINGLE,v=o(g,S);break;case"double-quoted-scalar":w=t.Scalar.QUOTE_DOUBLE,v=c(g,S);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 k=p+g.length,T=n.resolveEnd(y,k,d,u);return{value:v,type:w,comment:T.comment,range:[p,k,T.offset]}}function i(f,d){let u="";switch(f[0]){case"\t":u="a tab character";break;case",":u="flow indicator character ,";break;case"%":u="directive indicator character %";break;case"|":case">":{u=`block scalar indicator ${f[0]}`;break}case"@":case"`":{u=`reserved character ${f[0]}`;break}}if(u)d(0,"BAD_SCALAR_START",`Plain value cannot start with ${u}`);return s(f)}function o(f,d){if(f[f.length-1]!=="'"||f.length===1)d(f.length,"MISSING_CHAR","Missing closing 'quote");return s(f.slice(1,-1)).replace(/''/g,"'")}function s(f){let d,u;try{d=new RegExp(`(.*?)(?<![ ])[ ]*\r?
92
- `,"sy"),u=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
93
- `,"sy")}catch{d=/(.*?)[ \t]*\r?\n/sy,u=/[ \t]*(.*?)[ \t]*\r?\n/sy}let p=d.exec(f);if(!p)return f;let m=p[1],g=" ",y=d.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,d){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+=h(f,p+1,w,d),p+=w}else{let w=f.substr(p-1,2);d(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)d(f.length,"MISSING_CHAR",'Missing closing "quote');return u}function l(f,d){let u="",p=f[d+1];while(p===" "||p==="\t"||p===`
102
- `||p==="\r"){if(p==="\r"&&f[d+2]!==`
103
- `)break;if(p===`
104
- `)u+=`
105
- `;d+=1,p=f[d+1]}if(!u)u=" ";return{fold:u,offset:d}}var a={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
106
- `,r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function h(f,d,u,p){let m=f.substr(d,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(d-2,u+2);return p(d-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${w}`),w}}e.resolveFlowScalar=r}),Kl=C(function(e){var t=z(),n=se(),r=ys(),i=ws();function o(l,a,h,f){let{value:d,type:u,comment:p,range:m}=a.type==="block-scalar"?r.resolveBlockScalar(l,a,f):i.resolveFlowScalar(a,l.options.strict,f),g=h?l.directives.tagName(h.source,(v)=>f(h,"TAG_RESOLVE_FAILED",v)):null,y;if(l.options.stringKeys&&l.atKey)y=l.schema[t.SCALAR];else if(g)y=s(l.schema,d,g,h,f);else if(a.type==="scalar")y=c(l,d,a,f);else y=l.schema[t.SCALAR];let w;try{let v=y.resolve(d,(S)=>f(h??a,"TAG_RESOLVE_FAILED",S),l.options);w=t.isScalar(v)?v:new n.Scalar(v)}catch(v){let S=v instanceof Error?v.message:String(v);f(h??a,"TAG_RESOLVE_FAILED",S),w=new n.Scalar(d)}if(w.range=m,w.source=d,u)w.type=u;if(g)w.tag=g;if(y.format)w.format=y.format;if(p)w.comment=p;return w}function s(l,a,h,f,d){if(h==="!")return l[t.SCALAR];let u=[];for(let m of l.tags)if(!m.collection&&m.tag===h)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[h];if(p&&!p.collection)return l.tags.push(Object.assign({},p,{default:!1,test:void 0})),p;return d(f,"TAG_RESOLVE_FAILED",`Unresolved tag: ${h}`,h!=="tag:yaml.org,2002:str"),l[t.SCALAR]}function c({atKey:l,directives:a,schema:h},f,d,u){let p=h.tags.find((m)=>(m.default===!0||l&&m.default==="key")&&m.test?.test(f))||h[t.SCALAR];if(h.compat){let m=h.compat.find((g)=>g.default&&g.test?.test(f))??h[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(d,"TAG_RESOLVE_FAILED",w,!0)}}return p}e.composeScalar=o}),ql=C(function(e){function t(n,r,i){if(r){i??(i=r.length);for(let o=i-1;o>=0;--o){let s=r[o];switch(s.type){case"space":case"comment":case"newline":n-=s.source.length;continue}s=r[++o];while(s?.type==="space")n+=s.source.length,s=r[++o];break}}return n}e.emptyScalarPosition=t}),Zl=C(function(e){var t=Ht(),n=z(),r=Bl(),i=Kl(),o=gt(),s=ql(),c={composeNode:l,composeEmptyNode:a};function l(f,d,u,p){let m=f.atKey,{spaceBefore:g,comment:y,anchor:w,tag:v}=u,S,k=!0;switch(d.type){case"alias":if(S=h(f,d,p),w||v)p(d,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(S=i.composeScalar(f,d,v,p),w)S.anchor=w.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(S=r.composeCollection(c,f,d,u,p),w)S.anchor=w.source.substring(1)}catch(T){let A=T instanceof Error?T.message:String(T);p(d,"RESOURCE_EXHAUSTION",A)}break;default:{let T=d.type==="error"?d.message:`Unsupported token (type: ${d.type})`;p(d,"UNEXPECTED_TOKEN",T),k=!1}}if(S??(S=a(f,d.offset,void 0,null,u,p)),w&&S.anchor==="")p(w,"BAD_ALIAS","Anchor cannot be an empty string");if(m&&f.options.stringKeys&&(!n.isScalar(S)||typeof S.value!=="string"||S.tag&&S.tag!=="tag:yaml.org,2002:str"))p(v??d,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(g)S.spaceBefore=!0;if(y)if(d.type==="scalar"&&d.source==="")S.comment=y;else S.commentBefore=y;if(f.options.keepSourceTokens&&k)S.srcToken=d;return S}function a(f,d,u,p,{spaceBefore:m,comment:g,anchor:y,tag:w,end:v},S){let k={type:"scalar",offset:s.emptyScalarPosition(d,u,p),indent:-1,source:""},T=i.composeScalar(f,k,w,S);if(y){if(T.anchor=y.source.substring(1),T.anchor==="")S(y,"BAD_ALIAS","Anchor cannot be an empty string")}if(m)T.spaceBefore=!0;if(g)T.comment=g,T.range[2]=v;return T}function h({options:f},{offset:d,source:u,end:p},m){let g=new t.Alias(u.substring(1));if(g.source==="")m(d,"BAD_ALIAS","Alias cannot be an empty string");if(g.source.endsWith(":"))m(d+u.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let y=d+u.length,w=o.resolveEnd(p,y,f.strict,m);if(g.range=[d,y,w.offset],w.comment)g.comment=w.comment;return g}e.composeEmptyNode=a,e.composeNode=l}),Wl=C(function(e){var t=en(),n=Zl(),r=gt(),i=nn();function o(s,c,{offset:l,start:a,value:h,end:f},d){let u=Object.assign({_directives:c},s),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:h??f?.[0],offset:l,onError:d,parentIndent:0,startOnNewline:!0});if(g.found){if(p.directives.docStart=!0,h&&(h.type==="block-map"||h.type==="block-seq")&&!g.hasNewline)d(g.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}p.contents=h?n.composeNode(m,h,g,d):n.composeEmptyNode(m,g.end,a,null,g,d);let y=p.contents.range[2],w=r.resolveEnd(f,y,!1,d);if(w.comment)p.comment=w.comment;return p.range=[l,y,w.offset],p}e.composeDoc=o}),vs=C(function(e){var t=qt("process"),n=ns(),r=en(),i=tn(),o=z(),s=Wl(),c=gt();function l(f){if(typeof f==="number")return[f,f+1];if(Array.isArray(f))return f.length===2?f:[f[0],f[1]];let{offset:d,source:u}=f;return[d,d+(typeof u==="string"?u.length:1)]}function a(f){let d="",u=!1,p=!1;for(let m=0;m<f.length;++m){let g=f[m];switch(g[0]){case"#":d+=(d===""?"":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:d,afterEmptyLine:p}}class h{constructor(f={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(d,u,p,m)=>{let g=l(d);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,d){let{comment:u,afterEmptyLine:p}=a(this.prelude);if(u){let m=f.contents;if(d)f.comment=f.comment?`${f.comment}
110
- ${u}`:u;else if(p||f.directives.docStart||!m)f.commentBefore=u;else if(o.isCollection(m)&&!m.flow&&m.items.length>0){let g=m.items[0];if(o.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(d){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,d=!1,u=-1){for(let p of f)yield*this.next(p);yield*this.end(d,u)}*next(f){if(t.env.LOG_STREAM)console.dir(f,{depth:null});switch(f.type){case"directive":this.directives.add(f.source,(d,u,p)=>{let m=l(f);m[0]+=d,this.onError(m,"BAD_DIRECTIVE",u,p)}),this.prelude.push(f.source),this.atDirectives=!0;break;case"document":{let d=s.composeDoc(this.options,this.directives,f,this.onError);if(this.atDirectives&&!d.directives.docStart)this.onError(f,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(d,!1),this.doc)yield this.doc;this.doc=d,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(f.source);break;case"error":{let d=f.source?`${f.message}: ${JSON.stringify(f.source)}`:f.message,u=new i.YAMLParseError(l(f),"UNEXPECTED_TOKEN",d);if(this.atDirectives||!this.doc)this.errors.push(u);else this.doc.errors.push(u);break}case"doc-end":{if(!this.doc){this.errors.push(new i.YAMLParseError(l(f),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let d=c.resolveEnd(f.end,f.offset+f.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),d.comment){let u=this.doc.comment;this.doc.comment=u?`${u}
113
- ${d.comment}`:d.comment}this.doc.range[2]=d.offset;break}default:this.errors.push(new i.YAMLParseError(l(f),"UNEXPECTED_TOKEN",`Unsupported token ${f.type}`))}}*end(f=!1,d=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(f){let u=Object.assign({_directives:this.directives},this.options),p=new r.Document(void 0,u);if(this.atDirectives)this.onError(d,"MISSING_CHAR","Missing directives-end indicator line");p.range=[0,d,d],this.decorate(p,!1),yield p}}}e.Composer=h}),Jl=C(function(e){var t=ys(),n=ws(),r=tn(),i=Yt();function o(f,d=!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,d,p);case"block-scalar":return t.resolveBlockScalar({options:{strict:d}},f,p)}}return null}function s(f,d){let{implicitKey:u=!1,indent:p,inFlow:m=!1,offset:g=-1,type:y="PLAIN"}=d,w=i.stringifyString({type:y,value:f},{implicitKey:u,indent:p>0?" ".repeat(p):"",inFlow:m,options:{blockQuote:!0,lineWidth:-1}}),v=d.end??[{type:"newline",offset:-1,indent:p,source:`
114
- `}];switch(w[0]){case"|":case">":{let S=w.indexOf(`
115
- `),k=w.substring(0,S),T=w.substring(S+1)+`
116
- `,A=[{type:"block-scalar-header",offset:g,indent:p,source:k}];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:T}}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,d,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 S=f.props[0];if(S.type!=="block-scalar-header")throw Error("Invalid block scalar header");y=S.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:y="PLAIN"}let v=i.stringifyString({type:y,value:d},{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'"':h(f,v,"double-quoted-scalar");break;case"'":h(f,v,"single-quoted-scalar");break;default:h(f,v,"scalar")}}function l(f,d){let u=d.indexOf(`
118
- `),p=d.substring(0,u),m=d.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,d){if(d)for(let u of d)switch(u.type){case"space":case"comment":f.push(u);break;case"newline":return f.push(u),!0}return!1}function h(f,d,u){switch(f.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":f.type=u,f.source=d;break;case"block-scalar":{let p=f.props.slice(1),m=d.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:d,end:p});break}case"block-map":case"block-seq":{let m={type:"newline",offset:f.offset+d.length,indent:f.indent,source:`
121
- `};delete f.items,Object.assign(f,{type:u,source:d,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:d,end:m})}}}e.createScalarToken=s,e.resolveAsScalar=o,e.setScalarValue=c}),Hl=C(function(e){var t=(i)=>("type"in i)?n(i):r(i);function n(i){switch(i.type){case"block-scalar":{let o="";for(let s of i.props)o+=n(s);return o+i.source}case"block-map":case"block-seq":{let o="";for(let s of i.items)o+=r(s);return o}case"flow-collection":{let o=i.start.source;for(let s of i.items)o+=r(s);for(let s of i.end)o+=s.source;return o}case"document":{let o=r(i);if(i.end)for(let s of i.end)o+=s.source;return o}default:{let o=i.source;if("end"in i&&i.end)for(let s of i.end)o+=s.source;return o}}}function r({start:i,key:o,sep:s,value:c}){let l="";for(let a of i)l+=a.source;if(o)l+=n(o);if(s)for(let a of s)l+=a.source;if(c)l+=n(c);return l}e.stringify=t}),Vl=C(function(e){var t=Symbol("break visit"),n=Symbol("skip children"),r=Symbol("remove item");function i(s,c){if("type"in s&&s.type==="document")s={start:s.start,value:s.value};o(Object.freeze([]),s,c)}i.BREAK=t,i.SKIP=n,i.REMOVE=r,i.itemAtPath=(s,c)=>{let l=s;for(let[a,h]of c){let f=l?.[a];if(f&&"items"in f)l=f.items[h];else return}return l},i.parentCollection=(s,c)=>{let l=i.itemAtPath(s,c.slice(0,-1)),a=c[c.length-1][0],h=l?.[a];if(h&&"items"in h)return h;throw Error("Parent collection not found")};function o(s,c,l){let a=l(c,s);if(typeof a==="symbol")return a;for(let h of["key","value"]){let f=c[h];if(f&&"items"in f){for(let d=0;d<f.items.length;++d){let u=o(Object.freeze(s.concat([[h,d]])),f.items[d],l);if(typeof u==="number")d=u-1;else if(u===t)return t;else if(u===r)f.items.splice(d,1),d-=1}if(typeof a==="function"&&h==="key")a=a(c,s)}}return typeof a==="function"?a(c,s):a}e.visit=i}),Qn=C(function(e){var t=Jl(),n=Hl(),r=Vl(),i="\uFEFF",o="\x02",s="\x18",c="\x1F",l=(d)=>!!d&&("items"in d),a=(d)=>!!d&&(d.type==="scalar"||d.type==="single-quoted-scalar"||d.type==="double-quoted-scalar"||d.type==="block-scalar");function h(d){switch(d){case i:return"<BOM>";case o:return"<DOC>";case s:return"<FLOW_END>";case c:return"<SCALAR>";default:return JSON.stringify(d)}}function f(d){switch(d){case i:return"byte-order-mark";case o:return"doc-mode";case s:return"flow-error-end";case c:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
122
- `:case`\r
123
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(d[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=i,e.DOCUMENT=o,e.FLOW_END=s,e.SCALAR=c,e.isCollection=l,e.isScalar=a,e.prettyToken=h,e.tokenType=f}),bs=C(function(e){var t=Qn();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-#;/?:@&=+$_.!~*'()"),o=new Set(",[]{}"),s=new Set(` ,[]{}
125
- \r `),c=(a)=>!a||s.has(a);class l{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(a,h=!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=!h;let f=this.next??"stream";while(f&&(h||this.hasChars(1)))f=yield*this.parseNext(f)}atLineEnd(){let a=this.pos,h=this.buffer[a];while(h===" "||h==="\t")h=this.buffer[++a];if(!h||h==="#"||h===`
126
- `)return!0;if(h==="\r")return this.buffer[a+1]===`
127
- `;return!1}charAt(a){return this.buffer[this.pos+a]}continueScalar(a){let h=this.buffer[a];if(this.indentNext>0){let f=0;while(h===" ")h=this.buffer[++f+a];if(h==="\r"){let d=this.buffer[f+a+1];if(d===`
128
- `||!d&&!this.atEnd)return a+f+1}return h===`
129
- `||f>=this.indentNext||!h&&!this.atEnd?a+f:-1}if(h==="-"||h==="."){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 h=a.length,f=a.indexOf("#");while(f!==-1){let u=a[f-1];if(u===" "||u==="\t"){h=f-1;break}else f=a.indexOf("#",f+1)}while(!0){let u=a[h-1];if(u===" "||u==="\t")h-=1;else break}let d=(yield*this.pushCount(h))+(yield*this.pushSpaces(!0));return yield*this.pushCount(a.length-d),this.pushNewline(),"stream"}if(this.atLineEnd()){let h=yield*this.pushSpaces(!0);return yield*this.pushCount(a.length-h),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 h=this.peek(3);if((h==="---"||h==="...")&&n(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,h==="---"?"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,h]=this.peek(2);if(!h&&!this.atEnd)return this.setNext("block-start");if((a==="-"||a==="?"||a===":")&&n(h)){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 h=yield*this.pushIndicators();switch(a[h]){case"#":yield*this.pushCount(a.length-h);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 h+=yield*this.parseBlockScalarHeader(),h+=yield*this.pushSpaces(!0),yield*this.pushCount(a.length-h),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let a,h,f=-1;do{if(a=yield*this.pushNewline(),a>0)h=yield*this.pushSpaces(!1),this.indentValue=f=h;else h=0;h+=yield*this.pushSpaces(!0)}while(a+h>0);let d=this.getLine();if(d===null)return this.setNext("flow");if(f!==-1&&f<this.indentNext&&d[0]!=="#"||f===0&&(d.startsWith("---")||d.startsWith("..."))&&n(d[3])){if(!(f===this.indentNext-1&&this.flowLevel===1&&(d[0]==="]"||d[0]==="}")))return this.flowLevel=0,yield t.FLOW_END,yield*this.parseLineStart()}let u=0;while(d[u]===",")u+=yield*this.pushCount(1),u+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(u+=yield*this.pushIndicators(),d[u]){case void 0:return"flow";case"#":return yield*this.pushCount(d.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),h=this.buffer.indexOf(a,this.pos+1);if(a==="'")while(h!==-1&&this.buffer[h+1]==="'")h=this.buffer.indexOf("'",h+2);else while(h!==-1){let u=0;while(this.buffer[h-1-u]==="\\")u+=1;if(u%2===0)break;h=this.buffer.indexOf('"',h+1)}let f=this.buffer.substring(0,h),d=f.indexOf(`
131
- `,this.pos);if(d!==-1){while(d!==-1){let u=this.continueScalar(d+1);if(u===-1)break;d=f.indexOf(`
132
- `,u)}if(d!==-1)h=d-(f[d-1]==="\r"?2:1)}if(h===-1){if(!this.atEnd)return this.setNext("quoted-scalar");h=this.buffer.length}return yield*this.pushToIndex(h+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let a=this.pos;while(!0){let h=this.buffer[++a];if(h==="+")this.blockScalarKeep=!0;else if(h>"0"&&h<="9")this.blockScalarIndent=Number(h)-1;else if(h!=="-")break}return yield*this.pushUntil((h)=>n(h)||h==="#")}*parseBlockScalar(){let a=this.pos-1,h=0,f;e:for(let u=this.pos;f=this.buffer[u];++u)switch(f){case" ":h+=1;break;case`
133
- `:a=u,h=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(h>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=h;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 d=a+1;f=this.buffer[d];while(f===" ")f=this.buffer[++d];if(f==="\t"){while(f==="\t"||f===" "||f==="\r"||f===`
136
- `)f=this.buffer[++d];a=d-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+h>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,h=this.pos-1,f=this.pos-1,d;while(d=this.buffer[++f])if(d===":"){let u=this.buffer[f+1];if(n(u)||a&&o.has(u))break;h=f}else if(n(d)){let u=this.buffer[f+1];if(d==="\r")if(u===`
138
- `)f+=1,d=`
139
- `,u=this.buffer[f+1];else h=f;if(u==="#"||a&&o.has(u))break;if(d===`
140
- `){let p=this.continueScalar(f+1);if(p===-1)break;f=Math.max(f,p-2)}}else{if(a&&o.has(d))break;h=f}if(!d&&!this.atEnd)return this.setNext("plain-scalar");return yield t.SCALAR,yield*this.pushToIndex(h+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,h){let f=this.buffer.slice(this.pos,a);if(f)return yield f,this.pos+=f.length,f.length;else if(h)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 h=this.flowLevel>0,f=this.charAt(1);if(n(f)||h&&o.has(f)){if(!h)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,h=this.buffer[a];while(!n(h)&&h!==">")h=this.buffer[++a];return yield*this.pushToIndex(h===">"?a+1:a,!1)}else{let a=this.pos+1,h=this.buffer[a];while(h)if(i.has(h))h=this.buffer[++a];else if(h==="%"&&r.has(this.buffer[a+1])&&r.has(this.buffer[a+2]))h=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 h=this.pos-1,f;do f=this.buffer[++h];while(f===" "||a&&f==="\t");let d=h-this.pos;if(d>0)yield this.buffer.substr(this.pos,d),this.pos=h;return d}*pushUntil(a){let h=this.pos,f=this.buffer[h];while(!a(f))f=this.buffer[++h];return yield*this.pushToIndex(h,!1)}}e.Lexer=l}),_s=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 s=r+i>>1;if(this.lineStarts[s]<n)r=s+1;else i=s}if(this.lineStarts[r]===n)return{line:r+1,col:1};if(r===0)return{line:0,col:n};let o=this.lineStarts[r-1];return{line:r,col:n-o+1}}}}e.LineCounter=t}),ks=C(function(e){var t=qt("process"),n=Qn(),r=bs();function i(d,u){for(let p=0;p<d.length;++p)if(d[p].type===u)return!0;return!1}function o(d){for(let u=0;u<d.length;++u)switch(d[u].type){case"space":case"comment":case"newline":break;default:return u}return-1}function s(d){switch(d?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function c(d){switch(d.type){case"document":return d.start;case"block-map":{let u=d.items[d.items.length-1];return u.sep??u.start}case"block-seq":return d.items[d.items.length-1].start;default:return[]}}function l(d){if(d.length===0)return[];let u=d.length;e:while(--u>=0)switch(d[u].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}while(d[++u]?.type==="space");return d.splice(u,d.length)}function a(d,u){if(u.length<1e5)Array.prototype.push.apply(d,u);else for(let p=0;p<u.length;++p)d.push(u[p])}function h(d){if(d.start.type==="flow-seq-start"){for(let u of d.items)if(u.sep&&!u.value&&!i(u.start,"explicit-key-ind")&&!i(u.sep,"map-value-ind")){if(u.key)u.value=u.key;if(delete u.key,s(u.value))if(u.value.end)a(u.value.end,u.sep);else u.value.end=u.sep;else a(u.start,u.sep);delete u.sep}}}class f{constructor(d){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new r.Lexer,this.onNewLine=d}*parse(d,u=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let p of this.lexer.lex(d,u))yield*this.next(p);if(!u)yield*this.end()}*next(d){if(this.source=d,t.env.LOG_TOKENS)console.log("|",n.prettyToken(d));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=d.length;return}let u=n.tokenType(d);if(!u){let p=`Not a YAML token: ${d}`;yield*this.pop({type:"error",offset:this.offset,message:p,source:d}),this.offset+=d.length}else if(u==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=u,yield*this.step(),u){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+d.length);break;case"space":if(this.atNewLine&&d[0]===" ")this.indent+=d.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=d.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=d.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let d=this.peek(1);if(this.type==="doc-end"&&d?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!d)return yield*this.stream();switch(d.type){case"document":return yield*this.document(d);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(d);case"block-scalar":return yield*this.blockScalar(d);case"block-map":return yield*this.blockMap(d);case"block-seq":return yield*this.blockSequence(d);case"flow-collection":return yield*this.flowCollection(d);case"doc-end":return yield*this.documentEnd(d)}yield*this.pop()}peek(d){return this.stack[this.stack.length-d]}*pop(d){let u=d??this.stack.pop();if(!u)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield u;else{let 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")h(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&&o(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 d={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")d.start.push(this.sourceToken);this.stack.push(d);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(d){if(d.value)return yield*this.lineEnd(d);switch(this.type){case"doc-start":{if(o(d.start)!==-1)yield*this.pop(),yield*this.step();else d.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":d.start.push(this.sourceToken);return}let u=this.startBlockValue(d);if(u)this.stack.push(u);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(d){if(this.type==="map-value-ind"){let u=c(this.peek(2)),p=l(u),m;if(d.end)m=d.end,m.push(this.sourceToken),delete d.end;else m=[this.sourceToken];let g={type:"block-map",offset:d.offset,indent:d.indent,items:[{start:p,key:d,sep:m}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=g}else yield*this.lineEnd(d)}*blockScalar(d){switch(this.type){case"space":case"comment":case"newline":d.props.push(this.sourceToken);return;case"scalar":if(d.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let u=this.source.indexOf(`
143
- `)+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(d){let u=d.items[d.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 d.items.push({start:[this.sourceToken]})}else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"space":case"comment":if(u.value)d.items.push({start:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else{if(this.atIndentedComment(u.start,d.indent)){let m=d.items[d.items.length-2]?.value?.end;if(Array.isArray(m)){a(m,u.start),m.push(this.sourceToken),d.items.pop();return}}u.start.push(this.sourceToken)}return}if(this.indent>=d.indent){let p=!this.onKeyLine&&this.indent===d.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>d.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),d.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),d.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)d.items.push({start:[],key:null,sep:[this.sourceToken]});else if(i(u.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:g,key:null,sep:[this.sourceToken]}]});else if(s(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)d.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)d.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(d);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)d.items.push({start:g});this.stack.push(y);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(d){let u=d.items[d.items.length-1];switch(this.type){case"newline":if(u.value){let 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 d.items.push({start:[this.sourceToken]})}else u.start.push(this.sourceToken);return;case"space":case"comment":if(u.value)d.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(u.start,d.indent)){let m=d.items[d.items.length-2]?.value?.end;if(Array.isArray(m)){a(m,u.start),m.push(this.sourceToken),d.items.pop();return}}u.start.push(this.sourceToken)}return;case"anchor":case"tag":if(u.value||this.indent<=d.indent)break;u.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==d.indent)break;if(u.value||i(u.start,"seq-item-ind"))d.items.push({start:[this.sourceToken]});else u.start.push(this.sourceToken);return}if(this.indent>d.indent){let p=this.startBlockValue(d);if(p){this.stack.push(p);return}}yield*this.pop(),yield*this.step()}*flowCollection(d){let u=d.items[d.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(d.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!u||u.sep)d.items.push({start:[this.sourceToken]});else u.start.push(this.sourceToken);return;case"map-value-ind":if(!u||u.value)d.items.push({start:[],key:null,sep:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else Object.assign(u,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!u||u.value)d.items.push({start:[this.sourceToken]});else if(u.sep)u.sep.push(this.sourceToken);else u.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let m=this.flowScalar(this.type);if(!u||u.value)d.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":d.end.push(this.sourceToken);return}let p=this.startBlockValue(d);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===d.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);h(d);let y=d.end.splice(1,d.end.length);y.push(this.sourceToken);let w={type:"block-map",offset:d.offset,indent:d.indent,items:[{start:g,key:d,sep:y}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=w}else yield*this.lineEnd(d)}}flowScalar(d){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:d,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(d){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let u=c(d),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(d),p=l(u);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:p,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(d,u){if(this.type!=="comment")return!1;if(this.indent<=u)return!1;return d.every((p)=>p.type==="newline"||p.type==="space")}*documentEnd(d){if(this.type!=="doc-mode"){if(d.end)d.end.push(this.sourceToken);else d.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(d){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(d.end)d.end.push(this.sourceToken);else d.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}e.Parser=f}),Gl=C(function(e){var t=vs(),n=en(),r=tn(),i=is(),o=z(),s=_s(),c=ks();function l(u){let p=u.prettyErrors!==!1;return{lineCounter:u.lineCounter||p&&new s.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 S of v)S.errors.forEach(r.prettifyError(u,m)),S.warnings.forEach(r.prettifyError(u,m));if(v.length>0)return v;return Object.assign([],{empty:!0},w.streamInfo())}function h(u,p={}){let{lineCounter:m,prettyErrors:g}=l(p),y=new c.Parser(m?.addNewLine),w=new t.Composer(p),v=null;for(let S of w.compose(y.parse(u),!0,u.length))if(!v)v=S;else if(v.options.logLevel!=="silent"){v.errors.push(new r.YAMLParseError(S.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=h(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 d(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(o.isDocument(u)&&!g)return u.toString(m);return new n.Document(u,g,m).toString(m)}e.parse=f,e.parseAllDocuments=a,e.parseDocument=h,e.stringify=d}),Ql="dispach",eu="Dispach",tu=1;function Ss(e,t){return{slug:e,name:t,envPrefix:`${e.toUpperCase()}_`,stateDir:`.${e}`,apiVersion:`${e}/v${tu}`,packageScope:`@${e}`}}var Rt=Ss(Ql,eu),Lt=`${Rt.envPrefix}BRAND`,nu=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;function ru(e){return e.split("-").map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function iu(e){if(e===void 0)return Rt;let t=e.trim();if(t==="")throw Error(`${Lt} is set but empty. hint: unset ${Lt} entirely to use the default brand — an empty value `+'is treated as a mistake rather than as "no override", because a declared-but-unset variable is usually a container passing through a name it never assigned.');if(!nu.test(t))throw Error(`${Lt}="${t}" is not a usable brand slug. hint: the slug becomes an env var prefix, a dot-directory, an npm scope, and the `+"manifest apiVersion, so it must be lowercase alphanumeric with inner hyphens — "+"e.g. acme or acme-run.");if(t===Rt.slug)return Rt;return Ss(t,ru(t))}var er=iu(process.env[Lt]),su=Symbol.for("dispach.HarnessError");class tr extends Error{static ERROR_NAME="HarnessError";code;hint;field;details;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause});if(this.name=new.target.ERROR_NAME??"HarnessError",this[su]=!0,this.code=e.code,this.hint=e.hint,this.field=e.field,e.detail!==void 0)this.detail=e.detail;this.details=e.details??[]}toDetail(){return{code:this.code,message:this.message,hint:this.hint,...this.field===void 0?{}:{field:this.field},...this.detail===void 0?{}:{detail:this.detail},...this.details.length>1?{details:this.details}:{}}}format(){let e=[`${this.code}: ${this.message}`];if(this.field!==void 0)e.push(` field: ${this.field}`);if(e.push(` hint: ${this.hint}`),this.detail!==void 0)e.push(` detail: ${this.detail}`);if(this.details.length===1)return e.join(`
147
- `);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 zn extends tr{static ERROR_NAME="ConfigError"}class rt extends tr{static ERROR_NAME="ToolError"}function ou(e,t){return new rt({code:"workspace_not_editable",message:`${e} is declared editable: ${t}, so it cannot be written to.`,hint:"Point the write at a volatile file whose frontmatter allows it (editable: append or replace), or change that file's frontmatter. Read-only identity is deliberate — it is the most effective known mitigation for persona drift, so this refuses rather than silently doing nothing."})}function au(){return new rt({code:"memory_forget_arguments",message:"memory_forget needs either `query` or `ids`, not both and not neither.",hint:"Call it with `query` first to see what matches, show the person, then call it again with the `ids` they confirm."})}function cu(){return new rt({code:"memory_forget_unavailable",message:"Memory cannot be changed from here: nothing runs turns in this context.",hint:"memory_forget works inside a turn of a running agent."})}function lu(){return new rt({code:"artifact_unavailable",message:"This runtime has no artifact store, so a compacted observation cannot be read back.",hint:"artifact_read only works inside a session backed by a store. If you are seeing a compaction pointer without one, the pointer was written by a different process — report the text of the pointer rather than guessing at what it replaced."})}function uu(e){return new rt({code:"artifact_not_found",message:`No compacted observation is stored under ${JSON.stringify(e)} in this conversation.`,hint:"Copy the id exactly from the pointer in the conversation — it is not guessable and it is scoped to this conversation. If the pointer came from a session you have since switched away from, the observation is not reachable from here."})}var rk="What I already know, carried from before this conversation and kept current. "+"Not a transcript — these are standing facts about the person I work for and my own working notes. "+"If they ask what I know or remember about them, this is the answer.",Ae=(e)=>String.fromCharCode(e),et=Ae(27),$s=Ae(7),ik=new RegExp(`${et}\\[[0-?]*[ -/]*[@-~]`,"g"),sk=new RegExp(`${et}\\][\\s\\S]*?(?:${$s}|${et}\\\\|$)`,"g"),ok=new RegExp(`${et}[P^_X][\\s\\S]*?(?:${et}\\\\|${$s}|$)`,"g"),ak=new RegExp(`${et}[@-Z\\\\-_0-9=><]?`,"g"),ck=new RegExp(`[${Ae(128)}-${Ae(159)}]`,"g"),lk=new RegExp(`[${Ae(0)}-${Ae(8)}${Ae(11)}${Ae(12)}${Ae(14)}-${Ae(31)}${Ae(127)}]`,"g");function du(e){return e==="untrusted"?"obu":"obs"}function fu(e){return e.startsWith(`${du("untrusted")}_`)?"untrusted":"trusted"}var hu=3.8;function pu(e){if(e==="")return 0;let t=0;for(let n=0;n<e.length;n+=1)if(e.charCodeAt(n)===10)t+=1;return Math.ceil(e.length/hu)+t}var mu="<<<",gu=">>>",uk=`# Tools
149
-
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 \`${mu}\` and close it with \`${gu}\` 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.`,wi;function E(e,t,n){function r(c,l){if(!c._zod)Object.defineProperty(c,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1});if(c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);let a=s.prototype,h=Object.keys(a);for(let f=0;f<h.length;f++){let d=h[f];if(!(d in c))c[d]=a[d].bind(c)}}let i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(c){var l;let a=n?.Parent?new o:this;r(a,c),(l=a._zod).deferred??(l.deferred=[]);for(let h of a._zod.deferred)h();return a}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:(c)=>{if(n?.Parent&&c instanceof n.Parent)return!0;return c?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var dk=Symbol("zod_brand");class ze extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class nr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(wi=globalThis).__zod_globalConfig??(wi.__zod_globalConfig={});var xt=globalThis.__zod_globalConfig;function Me(e){if(e)Object.assign(xt,e);return xt}function Es(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function Fn(e,t){if(typeof t==="bigint")return t.toString();return t}function rr(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function ir(e){return e===null||e===void 0}function sr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function yu(e,t){let n=e/t,r=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<i)return 0;return n-r}var vi=Symbol("evaluating");function U(e,t,n){let r=void 0;Object.defineProperty(e,t,{get(){if(r===vi)return;if(r===void 0)r=vi,r=n();return r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function We(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Le(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function bi(e){return JSON.stringify(e)}function wu(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var As="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Dt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var vu=rr(()=>{if(xt.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function tt(e){if(Dt(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(Dt(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Os(e){if(tt(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var bu=new Set(["string","number","symbol"]);function nt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xe(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function M(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function _u(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var ku={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Su(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let o=Le(e._zod.def,{get shape(){let s={};for(let c in t){if(!(c in n.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;s[c]=n.shape[c]}return We(this,"shape",s),s},checks:[]});return xe(e,o)}function Tu(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let o=Le(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let c in t){if(!(c in n.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;delete s[c]}return We(this,"shape",s),s},checks:[]});return xe(e,o)}function $u(e,t){if(!tt(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=Le(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return We(this,"shape",o),o}});return xe(e,i)}function Eu(e,t){if(!tt(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=Le(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return We(this,"shape",r),r}});return xe(e,n)}function Au(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Le(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return We(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return xe(e,n)}function Ou(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=Le(t._zod.def,{get shape(){let c=t._zod.def.shape,l={...c};if(n)for(let a in n){if(!(a in c))throw Error(`Unrecognized key: "${a}"`);if(!n[a])continue;l[a]=e?new e({type:"optional",innerType:c[a]}):c[a]}else for(let a in c)l[a]=e?new e({type:"optional",innerType:c[a]}):c[a];return We(this,"shape",l),l},checks:[]});return xe(t,s)}function Nu(e,t,n){let r=Le(t._zod.def,{get shape(){let i=t._zod.def.shape,o={...i};if(n)for(let s in n){if(!(s in o))throw Error(`Unrecognized key: "${s}"`);if(!n[s])continue;o[s]=new e({type:"nonoptional",innerType:i[s]})}else for(let s in i)o[s]=new e({type:"nonoptional",innerType:i[s]});return We(this,"shape",o),o}});return xe(t,r)}function Ge(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Iu(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Xe(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function At(e){return typeof e==="string"?e:e?.message}function Re(e,t,n){let r=e.message?e.message:At(e.inst?._zod.def?.error?.(e))??At(t?.error?.(e))??At(n.customError?.(e))??At(n.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:s,...c}=e;if(c.path??(c.path=[]),c.message=r,t?.reportInput)c.input=s;return c}function or(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function ft(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}var Ns=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Fn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Is=E("$ZodError",Ns),Cs=E("$ZodError",Ns,{Parent:Error});function Cu(e,t=(n)=>n.message){let n={},r=[];for(let i of e.issues)if(i.path.length>0)n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i));else r.push(t(i));return{formErrors:r,fieldErrors:n}}function Pu(e,t=(n)=>n.message){let n={_errors:[]},r=(i,o=[])=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((c)=>r({issues:c},[...o,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...o,...s.path]);else{let c=[...o,...s.path];if(c.length===0)n._errors.push(t(s));else{let l=n,a=0;while(a<c.length){let h=c[a];if(a!==c.length-1)l[h]=l[h]||{_errors:[]};else l[h]=l[h]||{_errors:[]},l[h]._errors.push(t(s));l=l[h],a++}}}};return r(e),n}var ar=(e)=>(t,n,r,i)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new ze;if(s.issues.length){let c=new(i?.Err??e)(s.issues.map((l)=>Re(l,o,Me())));throw As(c,i?.callee),c}return s.value},cr=(e)=>async(t,n,r,i)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)s=await s;if(s.issues.length){let c=new(i?.Err??e)(s.issues.map((l)=>Re(l,o,Me())));throw As(c,i?.callee),c}return s.value},rn=(e)=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new ze;return o.issues.length?{success:!1,error:new(e??Is)(o.issues.map((s)=>Re(s,i,Me())))}:{success:!0,data:o.value}},Mu=rn(Cs),sn=(e)=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)o=await o;return o.issues.length?{success:!1,error:new e(o.issues.map((s)=>Re(s,i,Me())))}:{success:!0,data:o.value}},Ru=sn(Cs),Lu=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return ar(e)(t,n,i)},xu=(e)=>(t,n,r)=>ar(e)(t,n,r),Du=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return cr(e)(t,n,i)},ju=(e)=>async(t,n,r)=>cr(e)(t,n,r),Uu=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return rn(e)(t,n,i)},zu=(e)=>(t,n,r)=>rn(e)(t,n,r),Fu=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return sn(e)(t,n,i)},Bu=(e)=>async(t,n,r)=>sn(e)(t,n,r),Ku=/^[cC][0-9a-z]{6,}$/,qu=/^[0-9a-z]+$/,Zu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Wu=/^[0-9a-vA-V]{20}$/,Ju=/^[A-Za-z0-9]{27}$/,Hu=/^[a-zA-Z0-9_-]{21}$/,Vu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Gu=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_i=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Yu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Xu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Qu(){return new RegExp(Xu,"u")}var ed=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,td=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,nd=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,rd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,id=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ps=/^[A-Za-z0-9_-]*$/,sd=/^https?$/,od=/^\+[1-9]\d{6,14}$/,Ls="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ad=new RegExp(`^${Ls}$`);function xs(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function cd(e){return new RegExp(`^${xs(e)}$`)}function ld(e){let t=xs({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Ls}T(?:${r})$`)}var ud=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},dd=/^-?\d+$/,Ds=/^-?\d+(?:\.\d+)?$/,fd=/^(?:true|false)$/i,hd=/^[^A-Z]*$/,pd=/^[^a-z]*$/,he=E("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),js={number:"number",bigint:"bigint",object:"date"},Us=E("$ZodCheckLessThan",(e,t)=>{he.init(e,t);let n=js[typeof t.value];e._zod.onattach.push((r)=>{let i=r._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<o)if(t.inclusive)i.maximum=t.value;else i.exclusiveMaximum=t.value}),e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),zs=E("$ZodCheckGreaterThan",(e,t)=>{he.init(e,t);let n=js[typeof t.value];e._zod.onattach.push((r)=>{let i=r._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>o)if(t.inclusive)i.minimum=t.value;else i.exclusiveMinimum=t.value}),e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),md=E("$ZodCheckMultipleOf",(e,t)=>{he.init(e,t),e._zod.onattach.push((n)=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):yu(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),gd=E("$ZodCheckNumberFormat",(e,t)=>{he.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=ku[t.format];e._zod.onattach.push((s)=>{let c=s._zod.bag;if(c.format=t.format,c.minimum=i,c.maximum=o,n)c.pattern=dd}),e._zod.check=(s)=>{let c=s.value;if(n){if(!Number.isInteger(c)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){if(c>0)s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(c<i)s.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort});if(c>o)s.issues.push({origin:"number",input:c,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),yd=E("$ZodCheckMaxLength",(e,t)=>{var n;he.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!ir(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<i)r._zod.bag.maximum=t.maximum}),e._zod.check=(r)=>{let i=r.value;if(i.length<=t.maximum)return;let s=or(i);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),wd=E("$ZodCheckMinLength",(e,t)=>{var n;he.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!ir(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>i)r._zod.bag.minimum=t.minimum}),e._zod.check=(r)=>{let i=r.value;if(i.length>=t.minimum)return;let s=or(i);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),vd=E("$ZodCheckLengthEquals",(e,t)=>{var n;he.init(e,t),(n=e._zod.def).when??(n.when=(r)=>{let i=r.value;return!ir(i)&&i.length!==void 0}),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=(r)=>{let i=r.value,o=i.length;if(o===t.length)return;let s=or(i),c=o>t.length;r.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),on=E("$ZodCheckStringFormat",(e,t)=>{var n,r;if(he.init(e,t),e._zod.onattach.push((i)=>{let o=i._zod.bag;if(o.format=t.format,t.pattern)o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(i)=>{if(t.pattern.lastIndex=0,t.pattern.test(i.value))return;i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),bd=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})}}),_d=E("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=hd),on.init(e,t)}),kd=E("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=pd),on.init(e,t)}),Sd=E("$ZodCheckIncludes",(e,t)=>{he.init(e,t);let n=nt(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push((i)=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(i)=>{if(i.value.includes(t.includes,t.position))return;i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Td=E("$ZodCheckStartsWith",(e,t)=>{he.init(e,t);let n=new RegExp(`^${nt(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),$d=E("$ZodCheckEndsWith",(e,t)=>{he.init(e,t);let n=new RegExp(`.*${nt(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((r)=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Ed=E("$ZodCheckOverwrite",(e,t)=>{he.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Fs{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
170
- `).filter((o)=>o),r=Math.min(...n.map((o)=>o.length-o.trimStart().length)),i=n.map((o)=>o.slice(r)).map((o)=>" ".repeat(this.indent*2)+o);for(let o of i)this.content.push(o)}compile(){let e=Function,t=this?.args,r=[...(this?.content??[""]).map((i)=>` ${i}`)];return new e(...t,r.join(`
171
- `))}}var Ad={major:4,minor:4,patch:3},K=E("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ad;let r=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))r.unshift(e);for(let i of r)for(let o of i._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,c,l)=>{let a=Ge(s),h;for(let f of c){if(f._zod.def.when){if(Iu(s))continue;if(!f._zod.def.when(s))continue}else if(a)continue;let d=s.issues.length,u=f._zod.check(s);if(u instanceof Promise&&l?.async===!1)throw new ze;if(h||u instanceof Promise)h=(h??Promise.resolve()).then(async()=>{if(await u,s.issues.length===d)return;if(!a)a=Ge(s,d)});else{if(s.issues.length===d)continue;if(!a)a=Ge(s,d)}}if(h)return h.then(()=>s);return s},o=(s,c,l)=>{if(Ge(s))return s.aborted=!0,s;let a=i(c,r,l);if(a instanceof Promise){if(l.async===!1)throw new ze;return a.then((h)=>e._zod.parse(h,l))}return e._zod.parse(a,l)};e._zod.run=(s,c)=>{if(c.skipChecks)return e._zod.parse(s,c);if(c.direction==="backward"){let a=e._zod.parse({value:s.value,issues:[]},{...c,skipChecks:!0});if(a instanceof Promise)return a.then((h)=>o(h,s,c));return o(a,s,c)}let l=e._zod.parse(s,c);if(l instanceof Promise){if(c.async===!1)throw new ze;return l.then((a)=>i(a,r,c))}return i(l,r,c)}}U(e,"~standard",()=>({validate:(i)=>{try{let o=Mu(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch(o){return Ru(e,i).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),lr=E("$ZodString",(e,t)=>{K.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ud(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),q=E("$ZodStringFormat",(e,t)=>{on.init(e,t),lr.init(e,t)}),Od=E("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Gu),q.init(e,t)}),Nd=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=_i(r))}else t.pattern??(t.pattern=_i());q.init(e,t)}),Id=E("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Yu),q.init(e,t)}),Cd=E("$ZodURL",(e,t)=>{q.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===sd.source){if(!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}}let i=new URL(r);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(i.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=i.href;else n.value=r;return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Pd=E("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Qu()),q.init(e,t)}),Md=E("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Hu),q.init(e,t)}),Rd=E("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ku),q.init(e,t)}),Ld=E("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=qu),q.init(e,t)}),xd=E("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Zu),q.init(e,t)}),Dd=E("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Wu),q.init(e,t)}),jd=E("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ju),q.init(e,t)}),Ud=E("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=ld(t)),q.init(e,t)}),zd=E("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ad),q.init(e,t)}),Fd=E("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=cd(t)),q.init(e,t)}),Bd=E("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Vu),q.init(e,t)}),Kd=E("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ed),q.init(e,t),e._zod.bag.format="ipv4"}),qd=E("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=td),q.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(n)=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Zd=E("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=nd),q.init(e,t)}),Wd=E("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=rd),q.init(e,t),e._zod.check=(n)=>{let r=n.value.split("/");try{if(r.length!==2)throw Error();let[i,o]=r;if(!o)throw Error();let s=Number(o);if(`${s}`!==o)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Bs(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Jd=E("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=id),q.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(Bs(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Hd(e){if(!Ps.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Bs(n)}var Vd=E("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ps),q.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(Hd(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Gd=E("$ZodE164",(e,t)=>{t.pattern??(t.pattern=od),q.init(e,t)});function Yd(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}var Xd=E("$ZodJWT",(e,t)=>{q.init(e,t),e._zod.check=(n)=>{if(Yd(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Ks=E("$ZodNumber",(e,t)=>{K.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ds,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}let i=n.value;if(typeof i==="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o=typeof i==="number"?Number.isNaN(i)?"NaN":!Number.isFinite(i)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Qd=E("$ZodNumberFormat",(e,t)=>{gd.init(e,t),Ks.init(e,t)}),ef=E("$ZodBoolean",(e,t)=>{K.init(e,t),e._zod.pattern=fd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}let i=n.value;if(typeof i==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),tf=E("$ZodUnknown",(e,t)=>{K.init(e,t),e._zod.parse=(n)=>n}),nf=E("$ZodNever",(e,t)=>{K.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function ki(e,t,n){if(e.issues.length)t.issues.push(...Xe(n,e.issues));t.value[n]=e.value}var rf=E("$ZodArray",(e,t)=>{K.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let c=i[s],l=t.element._zod.run({value:c,issues:[]},r);if(l instanceof Promise)o.push(l.then((a)=>ki(a,n,s)));else ki(l,n,s)}if(o.length)return Promise.all(o).then(()=>n);return n}});function jt(e,t,n,r,i,o){let s=n in r;if(e.issues.length){if(i&&o&&!s)return;t.issues.push(...Xe(n,e.issues))}if(!s&&!i){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(s)t.value[n]=void 0}else t.value[n]=e.value}function qs(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let n=_u(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Zs(e,t,n,r,i,o){let s=[],c=i.keySet,l=i.catchall._zod,a=l.def.type,h=l.optin==="optional",f=l.optout==="optional";for(let d in t){if(d==="__proto__")continue;if(c.has(d))continue;if(a==="never"){s.push(d);continue}let u=l.run({value:t[d],issues:[]},r);if(u instanceof Promise)e.push(u.then((p)=>jt(p,n,d,t,h,f)));else jt(u,n,d,t,h,f)}if(s.length)n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o});if(!e.length)return n;return Promise.all(e).then(()=>n)}var sf=E("$ZodObject",(e,t)=>{if(K.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}let r=rr(()=>qs(t));U(e._zod,"propValues",()=>{let c=t.shape,l={};for(let a in c){let h=c[a]._zod;if(h.values){l[a]??(l[a]=new Set);for(let f of h.values)l[a].add(f)}}return l});let i=Dt,o=t.catchall,s;e._zod.parse=(c,l)=>{s??(s=r.value);let a=c.value;if(!i(a))return c.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),c;c.value={};let h=[],f=s.shape;for(let d of s.keys){let u=f[d],p=u._zod.optin==="optional",m=u._zod.optout==="optional",g=u._zod.run({value:a[d],issues:[]},l);if(g instanceof Promise)h.push(g.then((y)=>jt(y,c,d,a,p,m)));else jt(g,c,d,a,p,m)}if(!o)return h.length?Promise.all(h).then(()=>c):c;return Zs(h,a,c,l,r.value,e)}}),of=E("$ZodObjectJIT",(e,t)=>{sf.init(e,t);let n=e._zod.parse,r=rr(()=>qs(t)),i=(d)=>{let u=new Fs(["shape","payload","ctx"]),p=r.value,m=(v)=>{let S=bi(v);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};u.write("const input = payload.value;");let g=Object.create(null),y=0;for(let v of p.keys)g[v]=`key_${y++}`;u.write("const newResult = {};");for(let v of p.keys){let S=g[v],k=bi(v),T=d[v],A=T?._zod?.optin==="optional",N=T?._zod?.optout==="optional";if(u.write(`const ${S} = ${m(v)};`),A&&N)u.write(`
172
- if (${S}.issues.length) {
173
- if (${k} in input) {
174
- payload.issues = payload.issues.concat(${S}.issues.map(iss => ({
175
- ...iss,
176
- path: iss.path ? [${k}, ...iss.path] : [${k}]
177
- })));
178
- }
179
- }
180
-
181
- if (${S}.value === undefined) {
182
- if (${k} in input) {
183
- newResult[${k}] = undefined;
184
- }
185
- } else {
186
- newResult[${k}] = ${S}.value;
187
- }
188
-
189
- `);else if(!A)u.write(`
190
- const ${S}_present = ${k} in input;
191
- if (${S}.issues.length) {
192
- payload.issues = payload.issues.concat(${S}.issues.map(iss => ({
193
- ...iss,
194
- path: iss.path ? [${k}, ...iss.path] : [${k}]
195
- })));
196
- }
197
- if (!${S}_present && !${S}.issues.length) {
198
- payload.issues.push({
199
- code: "invalid_type",
200
- expected: "nonoptional",
201
- input: undefined,
202
- path: [${k}]
203
- });
204
- }
205
-
206
- if (${S}_present) {
207
- if (${S}.value === undefined) {
208
- newResult[${k}] = undefined;
209
- } else {
210
- newResult[${k}] = ${S}.value;
211
- }
212
- }
213
-
214
- `);else u.write(`
215
- if (${S}.issues.length) {
216
- payload.issues = payload.issues.concat(${S}.issues.map(iss => ({
217
- ...iss,
218
- path: iss.path ? [${k}, ...iss.path] : [${k}]
219
- })));
220
- }
221
-
222
- if (${S}.value === undefined) {
223
- if (${k} in input) {
224
- newResult[${k}] = undefined;
225
- }
226
- } else {
227
- newResult[${k}] = ${S}.value;
228
- }
229
-
230
- `)}u.write("payload.value = newResult;"),u.write("return payload;");let w=u.compile();return(v,S)=>w(d,v,S)},o,s=Dt,c=!xt.jitless,a=c&&vu.value,h=t.catchall,f;e._zod.parse=(d,u)=>{f??(f=r.value);let p=d.value;if(!s(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d;if(c&&a&&u?.async===!1&&u.jitless!==!0){if(!o)o=i(t.shape);if(d=o(d,u),!h)return d;return Zs([],p,d,u,f,e)}return n(d,u)}});function Si(e,t,n,r){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let i=e.filter((o)=>!Ge(o));if(i.length===1)return t.value=i[0].value,i[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((o)=>o.issues.map((s)=>Re(s,r,Me())))}),t}var af=E("$ZodUnion",(e,t)=>{K.init(e,t),U(e._zod,"optin",()=>t.options.some((r)=>r._zod.optin==="optional")?"optional":void 0),U(e._zod,"optout",()=>t.options.some((r)=>r._zod.optout==="optional")?"optional":void 0),U(e._zod,"values",()=>{if(t.options.every((r)=>r._zod.values))return new Set(t.options.flatMap((r)=>Array.from(r._zod.values)));return}),U(e._zod,"pattern",()=>{if(t.options.every((r)=>r._zod.pattern)){let r=t.options.map((i)=>i._zod.pattern);return new RegExp(`^(${r.map((i)=>sr(i.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1,s=[];for(let c of t.options){let l=c._zod.run({value:r.value,issues:[]},i);if(l instanceof Promise)s.push(l),o=!0;else{if(l.issues.length===0)return l;s.push(l)}}if(!o)return Si(s,r,e,i);return Promise.all(s).then((c)=>Si(c,r,e,i))}}),cf=E("$ZodIntersection",(e,t)=>{K.init(e,t),e._zod.parse=(n,r)=>{let i=n.value,o=t.left._zod.run({value:i,issues:[]},r),s=t.right._zod.run({value:i,issues:[]},r);if(o instanceof Promise||s instanceof Promise)return Promise.all([o,s]).then(([l,a])=>Ti(n,l,a));return Ti(n,o,s)}});function Kn(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(tt(e)&&tt(t)){let n=Object.keys(t),r=Object.keys(e).filter((o)=>n.indexOf(o)!==-1),i={...e,...t};for(let o of r){let s=Kn(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[r],s=Kn(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ti(e,t,n){let r=new Map,i;for(let c of t.issues)if(c.code==="unrecognized_keys"){i??(i=c);for(let l of c.keys){if(!r.has(l))r.set(l,{});r.get(l).l=!0}}else e.issues.push(c);for(let c of n.issues)if(c.code==="unrecognized_keys")for(let l of c.keys){if(!r.has(l))r.set(l,{});r.get(l).r=!0}else e.issues.push(c);let o=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(o.length&&i)e.issues.push({...i,keys:o});if(Ge(e))return e;let s=Kn(t.value,n.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var lf=E("$ZodRecord",(e,t)=>{K.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!tt(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.value={};let c=new Set;for(let a of s)if(typeof a==="string"||typeof a==="number"||typeof a==="symbol"){c.add(typeof a==="number"?a.toString():a);let h=t.keyType._zod.run({value:a,issues:[]},r);if(h instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(h.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map((u)=>Re(u,r,Me())),input:a,path:[a],inst:e});continue}let f=h.value,d=t.valueType._zod.run({value:i[a],issues:[]},r);if(d instanceof Promise)o.push(d.then((u)=>{if(u.issues.length)n.issues.push(...Xe(a,u.issues));n.value[f]=u.value}));else{if(d.issues.length)n.issues.push(...Xe(a,d.issues));n.value[f]=d.value}}let l;for(let a in i)if(!c.has(a))l=l??[],l.push(a);if(l&&l.length>0)n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l})}else{n.value={};for(let c of Reflect.ownKeys(i)){if(c==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(i,c))continue;let l=t.keyType._zod.run({value:c,issues:[]},r);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof c==="string"&&Ds.test(c)&&l.issues.length){let f=t.keyType._zod.run({value:Number(c),issues:[]},r);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length===0)l=f}if(l.issues.length){if(t.mode==="loose")n.value[c]=i[c];else n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((f)=>Re(f,r,Me())),input:c,path:[c],inst:e});continue}let h=t.valueType._zod.run({value:i[c],issues:[]},r);if(h instanceof Promise)o.push(h.then((f)=>{if(f.issues.length)n.issues.push(...Xe(c,f.issues));n.value[l.value]=f.value}));else{if(h.issues.length)n.issues.push(...Xe(c,h.issues));n.value[l.value]=h.value}}}if(o.length)return Promise.all(o).then(()=>n);return n}}),uf=E("$ZodEnum",(e,t)=>{K.init(e,t);let n=Es(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter((i)=>bu.has(typeof i)).map((i)=>typeof i==="string"?nt(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{let s=i.value;if(r.has(s))return i;return i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),df=E("$ZodLiteral",(e,t)=>{if(K.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map((r)=>typeof r==="string"?nt(r):r?nt(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,i)=>{let o=r.value;if(n.has(o))return r;return r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),ff=E("$ZodTransform",(e,t)=>{K.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new nr(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then((s)=>(n.value=s,n.fallback=!0,n));if(i instanceof Promise)throw new ze;return n.value=i,n.fallback=!0,n}});function $i(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var Ws=E("$ZodOptional",(e,t)=>{K.init(e,t),e._zod.optin="optional",e._zod.optout="optional",U(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),U(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${sr(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let i=n.value,o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>$i(s,i));return $i(o,i)}if(n.value===void 0)return n;return t.innerType._zod.run(n,r)}}),hf=E("$ZodExactOptional",(e,t)=>{Ws.init(e,t),U(e._zod,"values",()=>t.innerType._zod.values),U(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),pf=E("$ZodNullable",(e,t)=>{K.init(e,t),U(e._zod,"optin",()=>t.innerType._zod.optin),U(e._zod,"optout",()=>t.innerType._zod.optout),U(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${sr(n.source)}|null)$`):void 0}),U(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),mf=E("$ZodDefault",(e,t)=>{K.init(e,t),e._zod.optin="optional",U(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>Ei(o,t));return Ei(i,t)}});function Ei(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var gf=E("$ZodPrefault",(e,t)=>{K.init(e,t),e._zod.optin="optional",U(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),yf=E("$ZodNonOptional",(e,t)=>{K.init(e,t),U(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter((r)=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>Oi(o,e));return Oi(i,e)}});function Oi(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var wf=E("$ZodCatch",(e,t)=>{K.init(e,t),e._zod.optin="optional",U(e._zod,"optout",()=>t.innerType._zod.optout),U(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>{if(n.value=o.value,o.issues.length)n.value=t.catchValue({...n,error:{issues:o.issues.map((s)=>Re(s,r,Me()))},input:n.value}),n.issues=[],n.fallback=!0;return n});if(n.value=i.value,i.issues.length)n.value=t.catchValue({...n,error:{issues:i.issues.map((o)=>Re(o,r,Me()))},input:n.value}),n.issues=[],n.fallback=!0;return n}}),vf=E("$ZodPipe",(e,t)=>{K.init(e,t),U(e._zod,"values",()=>t.in._zod.values),U(e._zod,"optin",()=>t.in._zod.optin),U(e._zod,"optout",()=>t.out._zod.optout),U(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let o=t.out._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>It(s,t.in,r));return It(o,t.in,r)}let i=t.in._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>It(o,t.out,r));return It(i,t.out,r)}});function It(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var bf=E("$ZodReadonly",(e,t)=>{K.init(e,t),U(e._zod,"propValues",()=>t.innerType._zod.propValues),U(e._zod,"values",()=>t.innerType._zod.values),U(e._zod,"optin",()=>t.innerType?._zod?.optin),U(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then(Ni);return Ni(i)}});function Ni(e){return e.value=Object.freeze(e.value),e}var _f=E("$ZodLazy",(e,t)=>{K.init(e,t),U(e._zod,"innerType",()=>{let n=t;if(!n._cachedInner)n._cachedInner=t.getter();return n._cachedInner}),U(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),U(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),U(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),U(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),kf=E("$ZodCustom",(e,t)=>{he.init(e,t),K.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then((o)=>Ii(o,n,r,e));Ii(i,n,r,e);return}});function Ii(e,t,n,r){if(!e){let i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)i.params=r._zod.def.params;t.issues.push(ft(i))}}var Ci,fk=Symbol("ZodOutput"),hk=Symbol("ZodInput");class Js{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Sf(){return new Js}(Ci=globalThis).__zod_globalRegistry??(Ci.__zod_globalRegistry=Sf());var dt=globalThis.__zod_globalRegistry;function Tf(e,t){return new e({type:"string",...M(t)})}function $f(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function Pi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function Ef(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function Af(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function Of(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function Nf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function If(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function Cf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function Pf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function Mf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function Rf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function Lf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function xf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function Df(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function jf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function Uf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function zf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function Ff(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function Bf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function Kf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function qf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function Zf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}function Wf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function Jf(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function Hf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function Vf(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function Gf(e,t){return new e({type:"number",checks:[],...M(t)})}function Yf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function Xf(e,t){return new e({type:"boolean",...M(t)})}function Qf(e){return new e({type:"unknown"})}function eh(e,t){return new e({type:"never",...M(t)})}function Mi(e,t){return new Us({check:"less_than",...M(t),value:e,inclusive:!1})}function Mn(e,t){return new Us({check:"less_than",...M(t),value:e,inclusive:!0})}function Ri(e,t){return new zs({check:"greater_than",...M(t),value:e,inclusive:!1})}function Rn(e,t){return new zs({check:"greater_than",...M(t),value:e,inclusive:!0})}function Li(e,t){return new md({check:"multiple_of",...M(t),value:e})}function Hs(e,t){return new yd({check:"max_length",...M(t),maximum:e})}function Ut(e,t){return new wd({check:"min_length",...M(t),minimum:e})}function Vs(e,t){return new vd({check:"length_equals",...M(t),length:e})}function th(e,t){return new bd({check:"string_format",format:"regex",...M(t),pattern:e})}function nh(e){return new _d({check:"string_format",format:"lowercase",...M(e)})}function rh(e){return new kd({check:"string_format",format:"uppercase",...M(e)})}function ih(e,t){return new Sd({check:"string_format",format:"includes",...M(t),includes:e})}function sh(e,t){return new Td({check:"string_format",format:"starts_with",...M(t),prefix:e})}function oh(e,t){return new $d({check:"string_format",format:"ends_with",...M(t),suffix:e})}function it(e){return new Ed({check:"overwrite",tx:e})}function ah(e){return it((t)=>t.normalize(e))}function ch(){return it((e)=>e.trim())}function lh(){return it((e)=>e.toLowerCase())}function uh(){return it((e)=>e.toUpperCase())}function dh(){return it((e)=>wu(e))}function fh(e,t,n){return new e({type:"array",element:t,...M(n)})}function hh(e,t,n){return new e({type:"custom",check:"custom",fn:t,...M(n)})}function ph(e,t){let n=mh((r)=>(r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(ft(i,r.value,n._zod.def));else{let o=i;if(o.fatal)o.continue=!1;o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),r.issues.push(ft(o))}},e(r.value,r)),t);return n}function mh(e,t){let n=new he({check:"custom",...M(t)});return n._zod.check=e,n}function Gs(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??dt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function ee(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,o=t.seen.get(e);if(o){if(o.count++,n.schemaPath.includes(e))o.cycle=n.path;return o.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);let c=e._zod.toJSONSchema?.();if(c)s.schema=c;else{let h={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,h);else{let d=s.schema,u=t.processors[i.type];if(!u)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);u(e,t,d,h)}let f=e._zod.parent;if(f){if(!s.ref)s.ref=f;ee(f,t,h),t.seen.get(f).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(s.schema,l);if(t.io==="input"&&ue(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(r=s.schema).default??(r.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Ys(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let s of e.seen.entries()){let c=e.metadataRegistry.get(s[0])?.id;if(c){let l=r.get(c);if(l&&l!==s[0])throw Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(c,s[0])}}let i=(s)=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(s[0])?.id,d=e.external.uri??((p)=>p);if(f)return{ref:d(f)};let u=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=u,{defId:u,ref:`${d("__shared")}#/${c}/${u}`}}if(s[1]===n)return{ref:"#"};let a=`${"#"}/${c}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:a+h}},o=(s)=>{if(s[1].schema.$ref)return;let c=s[1],{ref:l,defId:a}=i(s);if(c.def={...c.schema},a)c.defId=a;let h=c.schema;for(let f in h)delete h[f];h.$ref=l};if(e.cycles==="throw")for(let s of e.seen.entries()){let c=s[1];if(c.cycle)throw Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
231
-
232
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let c=s[1];if(t===s[0]){o(s);continue}if(e.external){let a=e.external.registry.get(s[0])?.id;if(t!==s[0]&&a){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(c.cycle){o(s);continue}if(c.count>1){if(e.reused==="ref"){o(s);continue}}}}function Xs(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(c)=>{let l=e.seen.get(c);if(l.ref===null)return;let a=l.def??l.schema,h={...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 Object.assign(a,p);if(Object.assign(a,h),c._zod.parent===f)for(let g in a){if(g==="$ref"||g==="allOf")continue;if(!(g in h))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 d=c._zod.parent;if(d&&d!==f){r(d);let u=e.seen.get(d);if(u?.schema.$ref){if(a.$ref=u.schema.$ref,u.def)for(let 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??[]})};for(let c of[...e.seen.entries()].reverse())r(c[0]);let i={};if(e.target==="draft-2020-12")i.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")i.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")i.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let c=e.external.registry.get(t)?.id;if(!c)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(c)}Object.assign(i,n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;if(o!==void 0&&i.id===o)delete i.id;let s=e.external?.defs??{};for(let c of e.seen.entries()){let l=c[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;s[l.defId]=l.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")i.$defs=s;else i.definitions=s;try{let c=JSON.parse(JSON.stringify(i));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:zt(t,"input",e.processors),output:zt(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")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 gh=(e,t={})=>(n)=>{let r=Gs({...n,processors:t});return ee(e,r),Ys(r,e),Xs(r,e)},zt=(e,t,n={})=>(r)=>{let{libraryOptions:i,target:o}=r??{},s=Gs({...i??{},target:o,io:t,processors:n});return ee(e,s),Ys(s,e),Xs(s,e)},yh={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},wh=(e,t,n,r)=>{let i=n;i.type="string";let{minimum:o,maximum:s,format:c,patterns:l,contentEncoding:a}=e._zod.bag;if(typeof o==="number")i.minLength=o;if(typeof s==="number")i.maxLength=s;if(c){if(i.format=yh[c]??c,i.format==="")delete i.format;if(c==="time")delete i.format}if(a)i.contentEncoding=a;if(l&&l.size>0){let h=[...l];if(h.length===1)i.pattern=h[0].source;else if(h.length>1)i.allOf=[...h.map((f)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}},vh=(e,t,n,r)=>{let i=n,{minimum:o,maximum:s,format:c,multipleOf:l,exclusiveMaximum:a,exclusiveMinimum:h}=e._zod.bag;if(typeof c==="string"&&c.includes("int"))i.type="integer";else i.type="number";let f=typeof h==="number"&&h>=(o??Number.NEGATIVE_INFINITY),d=typeof a==="number"&&a<=(s??Number.POSITIVE_INFINITY),u=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(u)i.minimum=h,i.exclusiveMinimum=!0;else i.exclusiveMinimum=h;else if(typeof o==="number")i.minimum=o;if(d)if(u)i.maximum=a,i.exclusiveMaximum=!0;else i.exclusiveMaximum=a;else if(typeof s==="number")i.maximum=s;if(typeof l==="number")i.multipleOf=l},bh=(e,t,n,r)=>{n.type="boolean"},_h=(e,t,n,r)=>{n.not={}},kh=(e,t,n,r)=>{},Sh=(e,t,n,r)=>{let i=e._zod.def,o=Es(i.entries);if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";n.enum=o},Th=(e,t,n,r)=>{let i=e._zod.def,o=[];for(let s of i.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else o.push(Number(s));else o.push(s);if(o.length===0);else if(o.length===1){let s=o[0];if(n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[s];else n.const=s}else{if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";if(o.every((s)=>typeof s==="boolean"))n.type="boolean";if(o.every((s)=>s===null))n.type="null";n.enum=o}},$h=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Eh=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Ah=(e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:c}=e._zod.bag;if(typeof s==="number")i.minItems=s;if(typeof c==="number")i.maxItems=c;i.type="array",i.items=ee(o.element,t,{...r,path:[...r.path,"items"]})},Oh=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object",i.properties={};let s=o.shape;for(let a in s)i.properties[a]=ee(s[a],t,{...r,path:[...r.path,"properties",a]});let c=new Set(Object.keys(s)),l=new Set([...c].filter((a)=>{let h=o.shape[a]._zod;if(t.io==="input")return h.optin===void 0;else return h.optout===void 0}));if(l.size>0)i.required=Array.from(l);if(o.catchall?._zod.def.type==="never")i.additionalProperties=!1;else if(!o.catchall){if(t.io==="output")i.additionalProperties=!1}else if(o.catchall)i.additionalProperties=ee(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},Nh=(e,t,n,r)=>{let i=e._zod.def,o=i.inclusive===!1,s=i.options.map((c,l)=>ee(c,t,{...r,path:[...r.path,o?"oneOf":"anyOf",l]}));if(o)n.oneOf=s;else n.anyOf=s},Ih=(e,t,n,r)=>{let i=e._zod.def,o=ee(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=ee(i.right,t,{...r,path:[...r.path,"allOf",1]}),c=(a)=>("allOf"in a)&&Object.keys(a).length===1,l=[...c(o)?o.allOf:[o],...c(s)?s.allOf:[s]];n.allOf=l},Ch=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object";let s=o.keyType,l=s._zod.bag?.patterns;if(o.mode==="loose"&&l&&l.size>0){let h=ee(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let f of l)i.patternProperties[f.source]=h}else{if(t.target==="draft-07"||t.target==="draft-2020-12")i.propertyNames=ee(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});i.additionalProperties=ee(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let a=s._zod.values;if(a){let h=[...a].filter((f)=>typeof f==="string"||typeof f==="number");if(h.length>0)i.required=h}},Ph=(e,t,n,r)=>{let i=e._zod.def,o=ee(i.innerType,t,r),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=i.innerType,n.nullable=!0;else n.anyOf=[o,{type:"null"}]},Mh=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},Rh=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Lh=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let o=t.seen.get(e);if(o.ref=i.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(i.defaultValue))},xh=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},Dh=(e,t,n,r)=>{let i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?i.out:i.in:i.out;ee(s,t,r);let c=t.seen.get(e);c.ref=s},jh=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},Qs=(e,t,n,r)=>{let i=e._zod.def;ee(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},Uh=(e,t,n,r)=>{let i=e._zod.innerType;ee(i,t,r);let o=t.seen.get(e);o.ref=i},zh=E("ZodISODateTime",(e,t)=>{Ud.init(e,t),H.init(e,t)});function Fh(e){return Wf(zh,e)}var Bh=E("ZodISODate",(e,t)=>{zd.init(e,t),H.init(e,t)});function Kh(e){return Jf(Bh,e)}var qh=E("ZodISOTime",(e,t)=>{Fd.init(e,t),H.init(e,t)});function Zh(e){return Hf(qh,e)}var Wh=E("ZodISODuration",(e,t)=>{Bd.init(e,t),H.init(e,t)});function Jh(e){return Vf(Wh,e)}var Hh=(e,t)=>{Is.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>Pu(e,n)},flatten:{value:(n)=>Cu(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Fn,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Fn,2)}},isEmpty:{get(){return e.issues.length===0}}})},Se=E("ZodError",Hh,{Parent:Error}),Vh=ar(Se),Gh=cr(Se),Yh=rn(Se),Xh=sn(Se),Qh=Lu(Se),ep=xu(Se),tp=Du(Se),np=ju(Se),rp=Uu(Se),ip=zu(Se),sp=Fu(Se),op=Bu(Se),xi=new WeakMap;function yt(e,t,n){let r=Object.getPrototypeOf(e),i=xi.get(r);if(!i)i=new Set,xi.set(r,i);if(i.has(t))return;i.add(t);for(let o in n){let s=n[o];Object.defineProperty(r,o,{configurable:!0,enumerable:!1,get(){let c=s.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}var Z=E("ZodType",(e,t)=>(K.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:zt(e,"input"),output:zt(e,"output")}}),e.toJSONSchema=gh(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>Vh(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Yh(e,n,r),e.parseAsync=async(n,r)=>Gh(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Xh(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>Qh(e,n,r),e.decode=(n,r)=>ep(e,n,r),e.encodeAsync=async(n,r)=>tp(e,n,r),e.decodeAsync=async(n,r)=>np(e,n,r),e.safeEncode=(n,r)=>rp(e,n,r),e.safeDecode=(n,r)=>ip(e,n,r),e.safeEncodeAsync=async(n,r)=>sp(e,n,r),e.safeDecodeAsync=async(n,r)=>op(e,n,r),yt(e,"ZodType",{check(...n){let r=this.def;return this.clone(Le(r,{checks:[...r.checks??[],...n.map((i)=>typeof i==="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return xe(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(em(n,r))},superRefine(n,r){return this.check(tm(n,r))},overwrite(n){return this.check(it(n))},optional(){return zi(this)},exactOptional(){return Up(this)},nullable(){return Fi(this)},nullish(){return zi(Fi(this))},nonoptional(n){return Zp(this,n)},array(){return B(this)},or(n){return wt([this,n])},and(n){return Rp(this,n)},transform(n){return Bi(this,Dp(n))},default(n){return Bp(this,n)},prefault(n){return qp(this,n)},catch(n){return Jp(this,n)},pipe(n){return Bi(this,n)},readonly(){return Gp(this)},describe(n){let r=this.clone();return dt.add(r,{description:n}),r},meta(...n){if(n.length===0)return dt.get(this);let r=this.clone();return dt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return dt.get(e)?.description},configurable:!0}),e)),eo=E("_ZodString",(e,t)=>{lr.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,i,o)=>wh(e,r,i,o);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,yt(e,"_ZodString",{regex(...r){return this.check(th(...r))},includes(...r){return this.check(ih(...r))},startsWith(...r){return this.check(sh(...r))},endsWith(...r){return this.check(oh(...r))},min(...r){return this.check(Ut(...r))},max(...r){return this.check(Hs(...r))},length(...r){return this.check(Vs(...r))},nonempty(...r){return this.check(Ut(1,...r))},lowercase(r){return this.check(nh(r))},uppercase(r){return this.check(rh(r))},trim(){return this.check(ch())},normalize(...r){return this.check(ah(...r))},toLowerCase(){return this.check(lh())},toUpperCase(){return this.check(uh())},slugify(){return this.check(dh())}})}),ap=E("ZodString",(e,t)=>{lr.init(e,t),eo.init(e,t),e.email=(n)=>e.check($f(cp,n)),e.url=(n)=>e.check(If(lp,n)),e.jwt=(n)=>e.check(Zf(Tp,n)),e.emoji=(n)=>e.check(Cf(up,n)),e.guid=(n)=>e.check(Pi(Di,n)),e.uuid=(n)=>e.check(Ef(Ct,n)),e.uuidv4=(n)=>e.check(Af(Ct,n)),e.uuidv6=(n)=>e.check(Of(Ct,n)),e.uuidv7=(n)=>e.check(Nf(Ct,n)),e.nanoid=(n)=>e.check(Pf(dp,n)),e.guid=(n)=>e.check(Pi(Di,n)),e.cuid=(n)=>e.check(Mf(fp,n)),e.cuid2=(n)=>e.check(Rf(hp,n)),e.ulid=(n)=>e.check(Lf(pp,n)),e.base64=(n)=>e.check(Bf(_p,n)),e.base64url=(n)=>e.check(Kf(kp,n)),e.xid=(n)=>e.check(xf(mp,n)),e.ksuid=(n)=>e.check(Df(gp,n)),e.ipv4=(n)=>e.check(jf(yp,n)),e.ipv6=(n)=>e.check(Uf(wp,n)),e.cidrv4=(n)=>e.check(zf(vp,n)),e.cidrv6=(n)=>e.check(Ff(bp,n)),e.e164=(n)=>e.check(qf(Sp,n)),e.datetime=(n)=>e.check(Fh(n)),e.date=(n)=>e.check(Kh(n)),e.time=(n)=>e.check(Zh(n)),e.duration=(n)=>e.check(Jh(n))});function P(e){return Tf(ap,e)}var H=E("ZodStringFormat",(e,t)=>{q.init(e,t),eo.init(e,t)}),cp=E("ZodEmail",(e,t)=>{Id.init(e,t),H.init(e,t)}),Di=E("ZodGUID",(e,t)=>{Od.init(e,t),H.init(e,t)}),Ct=E("ZodUUID",(e,t)=>{Nd.init(e,t),H.init(e,t)}),lp=E("ZodURL",(e,t)=>{Cd.init(e,t),H.init(e,t)}),up=E("ZodEmoji",(e,t)=>{Pd.init(e,t),H.init(e,t)}),dp=E("ZodNanoID",(e,t)=>{Md.init(e,t),H.init(e,t)}),fp=E("ZodCUID",(e,t)=>{Rd.init(e,t),H.init(e,t)}),hp=E("ZodCUID2",(e,t)=>{Ld.init(e,t),H.init(e,t)}),pp=E("ZodULID",(e,t)=>{xd.init(e,t),H.init(e,t)}),mp=E("ZodXID",(e,t)=>{Dd.init(e,t),H.init(e,t)}),gp=E("ZodKSUID",(e,t)=>{jd.init(e,t),H.init(e,t)}),yp=E("ZodIPv4",(e,t)=>{Kd.init(e,t),H.init(e,t)}),wp=E("ZodIPv6",(e,t)=>{qd.init(e,t),H.init(e,t)}),vp=E("ZodCIDRv4",(e,t)=>{Zd.init(e,t),H.init(e,t)}),bp=E("ZodCIDRv6",(e,t)=>{Wd.init(e,t),H.init(e,t)}),_p=E("ZodBase64",(e,t)=>{Jd.init(e,t),H.init(e,t)}),kp=E("ZodBase64URL",(e,t)=>{Vd.init(e,t),H.init(e,t)}),Sp=E("ZodE164",(e,t)=>{Gd.init(e,t),H.init(e,t)}),Tp=E("ZodJWT",(e,t)=>{Xd.init(e,t),H.init(e,t)}),to=E("ZodNumber",(e,t)=>{Ks.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,i,o)=>vh(e,r,i,o),yt(e,"ZodNumber",{gt(r,i){return this.check(Ri(r,i))},gte(r,i){return this.check(Rn(r,i))},min(r,i){return this.check(Rn(r,i))},lt(r,i){return this.check(Mi(r,i))},lte(r,i){return this.check(Mn(r,i))},max(r,i){return this.check(Mn(r,i))},int(r){return this.check(ji(r))},safe(r){return this.check(ji(r))},positive(r){return this.check(Ri(0,r))},nonnegative(r){return this.check(Rn(0,r))},negative(r){return this.check(Mi(0,r))},nonpositive(r){return this.check(Mn(0,r))},multipleOf(r,i){return this.check(Li(r,i))},step(r,i){return this.check(Li(r,i))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??0.5),e.isFinite=!0,e.format=n.format??null});function L(e){return Gf(to,e)}var $p=E("ZodNumberFormat",(e,t)=>{Qd.init(e,t),to.init(e,t)});function ji(e){return Yf($p,e)}var Ep=E("ZodBoolean",(e,t)=>{ef.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bh(e,n,r,i)});function oe(e){return Xf(Ep,e)}var Ap=E("ZodUnknown",(e,t)=>{tf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kh(e,n,r,i)});function Fe(){return Qf(Ap)}var Op=E("ZodNever",(e,t)=>{nf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_h(e,n,r,i)});function Np(e){return eh(Op,e)}var Ip=E("ZodArray",(e,t)=>{rf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ah(e,n,r,i),e.element=t.element,yt(e,"ZodArray",{min(n,r){return this.check(Ut(n,r))},nonempty(n){return this.check(Ut(1,n))},max(n,r){return this.check(Hs(n,r))},length(n,r){return this.check(Vs(n,r))},unwrap(){return this.element}})});function B(e,t){return fh(Ip,e,t)}var Cp=E("ZodObject",(e,t)=>{of.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Oh(e,n,r,i),U(e,"shape",()=>t.shape),yt(e,"ZodObject",{keyof(){return Y(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Fe()})},loose(){return this.clone({...this._zod.def,catchall:Fe()})},strict(){return this.clone({...this._zod.def,catchall:Np()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return $u(this,n)},safeExtend(n){return Eu(this,n)},merge(n){return Au(this,n)},pick(n){return Su(this,n)},omit(n){return Tu(this,n)},partial(...n){return Ou(no,this,n[0])},required(...n){return Nu(ro,this,n[0])}})});function D(e,t){let n={type:"object",shape:e??{},...M(t)};return new Cp(n)}var Pp=E("ZodUnion",(e,t)=>{af.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Nh(e,n,r,i),e.options=t.options});function wt(e,t){return new Pp({type:"union",options:e,...M(t)})}var Mp=E("ZodIntersection",(e,t)=>{cf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ih(e,n,r,i)});function Rp(e,t){return new Mp({type:"intersection",left:e,right:t})}var Ui=E("ZodRecord",(e,t)=>{lf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ch(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function ke(e,t,n){if(!t||!t._zod)return new Ui({type:"record",keyType:P(),valueType:e,...M(t)});return new Ui({type:"record",keyType:e,valueType:t,...M(n)})}var qn=E("ZodEnum",(e,t)=>{uf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(r,i,o)=>Sh(e,r,i,o),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{let o={};for(let s of r)if(n.has(s))o[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new qn({...t,checks:[],...M(i),entries:o})},e.exclude=(r,i)=>{let o={...t.entries};for(let s of r)if(n.has(s))delete o[s];else throw Error(`Key ${s} not found in enum`);return new qn({...t,checks:[],...M(i),entries:o})}});function Y(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new qn({type:"enum",entries:n,...M(t)})}var Lp=E("ZodLiteral",(e,t)=>{df.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Th(e,n,r,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Ft(e,t){return new Lp({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}var xp=E("ZodTransform",(e,t)=>{ff.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Eh(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new nr(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(ft(o,n.value,t));else{let s=o;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(ft(s))}};let i=t.transform(n.value,n);if(i instanceof Promise)return i.then((o)=>(n.value=o,n.fallback=!0,n));return n.value=i,n.fallback=!0,n}});function Dp(e){return new xp({type:"transform",transform:e})}var no=E("ZodOptional",(e,t)=>{Ws.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Qs(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function zi(e){return new no({type:"optional",innerType:e})}var jp=E("ZodExactOptional",(e,t)=>{hf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Qs(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Up(e){return new jp({type:"optional",innerType:e})}var zp=E("ZodNullable",(e,t)=>{pf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ph(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Fi(e){return new zp({type:"nullable",innerType:e})}var Fp=E("ZodDefault",(e,t)=>{mf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Rh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bp(e,t){return new Fp({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Os(t)}})}var Kp=E("ZodPrefault",(e,t)=>{gf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Lh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function qp(e,t){return new Kp({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Os(t)}})}var ro=E("ZodNonOptional",(e,t)=>{yf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Mh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Zp(e,t){return new ro({type:"nonoptional",innerType:e,...M(t)})}var Wp=E("ZodCatch",(e,t)=>{wf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Jp(e,t){return new Wp({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var Hp=E("ZodPipe",(e,t)=>{vf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Dh(e,n,r,i),e.in=t.in,e.out=t.out});function Bi(e,t){return new Hp({type:"pipe",in:e,out:t})}var Vp=E("ZodReadonly",(e,t)=>{bf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jh(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Gp(e){return new Vp({type:"readonly",innerType:e})}var Yp=E("ZodLazy",(e,t)=>{_f.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Uh(e,n,r,i),e.unwrap=()=>e._zod.def.getter()});function Xp(e){return new Yp({type:"lazy",getter:e})}var Qp=E("ZodCustom",(e,t)=>{kf.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(n,r,i)=>$h(e,n,r,i)});function em(e,t={}){return hh(Qp,e,t)}function tm(e,t){return ph(e,t)}var nm=vs(),rm=en(),im=ps(),ur=tn(),sm=Ht(),De=z(),om=Ke(),am=se(),cm=qe(),lm=Ze(),pk=Qn(),um=bs(),dm=_s(),fm=ks(),an=Gl(),oo=Zt(),mk=nm.Composer,gk=rm.Document,yk=im.Schema,{YAMLError:wk,YAMLParseError:vk,YAMLWarning:bk}=ur,_k=sm.Alias,{isAlias:kk,isCollection:Sk,isDocument:Tk,isMap:$k,isNode:Ek,isPair:Ak,isScalar:Ok,isSeq:Nk}=De,Ik=om.Pair,Ck=am.Scalar,Pk=cm.YAMLMap,Mk=lm.YAMLSeq,Rk=um.Lexer,Lk=dm.LineCounter,xk=fm.Parser,{parse:Dk,parseAllDocuments:jk,parseDocument:Uk,stringify:zk}=an,{visit:Fk,visitAsync:Bk}=oo,Jk=`${er.slug}_`,Hk=new RegExp("[\\u0000-\\u001f\\u007f]");function vm(e,t=""){let n="",r=0;for(;;){let i=e.indexOf("<!--",r);if(i===-1)break;let o=e.indexOf("-->",i+4);if(o===-1)break;n+=e.slice(r,i)+t,r=o+3}return n+e.slice(r)}var bm=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,_m=/\n{3,}/g;function km(e){let t=bm.exec(e);return t===null||t===void 0?e:e.slice(t[0].length)}function Sm(e){return vm(e).replace(_m,`
233
-
234
- `).trim()}var Pt={static:2000,volatile:3500,reminder:500,total:6000},ye=P().min(1),Tm=D({delimiters:Y(["xml","markdown","plain"]).optional(),intensity:Y(["emphatic","neutral","soft"]).optional(),examplesIn:Y(["system","user"]).optional(),skillsIn:Y(["system","user"]).optional()}).strict(),$m=D({nativeTools:oe().optional(),strictSchema:oe().optional(),thinking:Y(["none","anthropic","openai","deepseek"]).optional(),promptCache:Y(["none","anthropic","openai","bedrock"]).optional(),parallelToolCalls:oe().optional(),contextWindow:L().int().positive().optional(),maxOutput:L().int().positive().optional(),vision:oe().optional(),promptStyle:Tm.optional()}).strict(),Zi="chat-completions",lo=D({id:P().min(1),api:P().min(1).optional(),options:ke(P(),Fe()).optional(),baseUrl:P().min(1).optional(),apiKeyEnv:P().min(1).optional(),temperature:L().min(0).max(2).optional(),topP:L().min(0).max(1).optional(),maxTokens:L().int().positive().optional(),reasoningEffort:Y(["none","minimal","low","medium","high","xhigh","max"]).optional(),headers:ke(P(),P()).optional(),streamUsage:oe().optional(),capabilities:$m.optional()}).strict();function uo(e,t){if((e.api??Zi)===Zi&&e.baseUrl===void 0)t.addIssue({code:"custom",path:["baseUrl"],message:"baseUrl is required for the chat-completions transport"})}var Em=lo.superRefine(uo),Mt=lo.extend({fallbacks:B(Em).min(1).optional()}).superRefine(uo),Am=D({main:Mt,selector:Mt.optional(),compactor:Mt.optional()}).catchall(Mt),Om=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(),Nm=D({static:L().int().positive().default(Pt.static),volatile:L().int().positive().default(Pt.volatile),reminder:L().int().positive().default(Pt.reminder),total:L().int().positive().default(Pt.total)}).strict(),Im=D({perRuleSuccess:L().gt(0).lte(1).default(0.9),reliabilityTarget:L().gt(0).lt(1).default(0.8),onExceed:Y(["fail","warn"]).default("fail")}).strict(),Cm=D({file:P().min(1),requires:D({contextWindow:P().min(1).optional(),class:Y(["frontier","small"]).optional()}).strict().optional(),onUnmet:Y(["distill","omit","fail"]).default("distill"),distilled:P().min(1).optional()}).strict(),Pm=D({dir:P().min(1),maxActive:L().int().nonnegative().default(2),budget:L().int().positive().default(600)}).strict(),Mm=D({window:L().int().positive().optional(),reserveOutput:L().int().positive().default(4096),observationMaxTokens:L().int().positive().optional(),modelIdentity:Y(["shown","hidden"]).default("shown"),files:B(P().min(1)).default([]),workspace:P().min(1).default("./workspace"),static:B(P().min(1)).default([]),volatile:B(P().min(1)).default([]),reminder:P().min(1).optional(),budgets:Nm.prefault({}),rules:Im.prefault({}),soul:Cm.optional(),compactionNotice:oe().optional(),thresholds:Om.prefault({})}).strict(),Rm=D({max:L().int().positive().default(24),reserveWrite:L().int().nonnegative().default(6)}).strict(),Lm=D({onMutate:Y(["refuse","confirm","allow"]).default("refuse")}).strict(),xm=D({mode:Y(["ask","allow","deny"]).default("allow"),allow:B(P().min(1)).default([]),deny:B(P().min(1)).default([]),onNoApprover:Y(["deny","allow"]).default("deny")}).strict(),Dm=D({dialect:Y(["nlt","native"]).default("nlt"),providers:ke(ye,ke(P(),Fe())).default({}),provider:ye.optional(),providerConfig:ke(P(),Fe()).default({}),budget:Rm.prefault({}),pinned:B(P().min(1)).default([]),search:D({enabled:oe().default(!1)}).strict().prefault({}),local:B(P().min(1)).default([]),untrusted:Lm.prefault({}),policy:xm.prefault({}),eventDetail:Y(["none","redacted"]).default("none")}).strict(),jm=D({allow:B(P().min(1)),entry:oe().optional()}).strict(),Um=D({dir:P().min(1).default("./skills"),maxActive:L().int().nonnegative().default(1),threshold:L().default(0.35),trusted:B(P().min(1)).optional()}).strict(),zm=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(),Fm=["owner","peer","channel-peer"],Bm=D({scope:Y(Fm).default("channel-peer")}).strict(),Km=D({type:ye,id:ye,allowFrom:B(P().min(1)).optional(),enabled:oe().default(!0),role:ye.optional()}).passthrough(),fo=D({channel:ye,to:P().min(1)}).strict(),qm=D({default:ye.optional(),reply:Y(["all","final"]).default("all"),targets:ke(P(),fo).default({})}).strict(),Bt=Xp(()=>D({type:Y(["string","number","integer","boolean","array","object"]),description:P().optional(),enum:B(wt([P(),L(),oe()])).optional(),items:Bt.optional(),properties:ke(P(),Bt).optional(),required:B(P()).optional()})),ho=D({id:ye,manifest:P().min(1),task:P().min(1),artifact:D({type:Ft("object"),properties:ke(P(),Bt),required:B(P()).optional()}).strict()}).strict(),Zm=D({members:B(ho).min(1)}).strict(),Wm=D({name:ye,task:P().min(1),tools:B(P().min(1)).min(1),route:D({tools:B(P().min(1)).min(1)}).strict().optional(),spawn:oe().default(!1),artifact:ho.shape.artifact.optional(),model:P().min(1).optional(),maxSteps:L().int().positive().optional(),timeoutMs:L().int().positive().optional()}).strict(),Ln={provider:P().min(1),model:P().min(1).optional(),baseUrl:P().min(1).optional(),apiKeyEnv:P().min(1).optional(),options:ke(P(),Fe()).optional()},Jm=D({transcription:D({...Ln,timeoutMs:L().int().positive().default(60000),maxBytes:L().int().positive().default(26214400)}).strict().optional(),speech:D({...Ln,timeoutMs:L().int().positive().default(60000),maxCharacters:L().int().positive().default(3000)}).strict().optional(),image:D({...Ln,timeoutMs:L().int().positive().default(120000),size:P().regex(/^[0-9]+x[0-9]+$/).default("1024x1024")}).strict().optional()}).strict(),Hm=D({enabled:oe().default(!1),escalateAfterMs:L().int().nonnegative().default(0)}).strict(),Vm=D({offer:D({task:P().min(1),artifact:D({type:Ft("object"),properties:ke(P(),Bt),required:B(P()).optional()}).strict()}).strict().optional(),to:wt([Ft("*"),B(ye).min(1)]).optional(),ask:oe().default(!1)}).strict(),Gm=D({id:ye,kind:Y(["cron","every","at"]),expr:P().min(1),task:P().min(1),deliver:wt([Ft("none"),fo]),session:P().min(1).default("isolated"),role:ye.optional(),tools:D({allow:B(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(),Ym=wt([P().min(1),D({spec:P().min(1),config:ke(P(),Fe()).default({})}).strict()]),Xm=D({identicalCalls:L().int().min(2).default(3),sameTool:L().int().min(2).optional()}).strict(),Qm=D({maxSteps:L().int().positive().default(40),noProgress:Xm.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(),eg=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(`${er.envPrefix}API_TOKEN`),allowedOrigins:B(P().min(1)).default([]),allowedHosts:B(P().min(1)).default([])}).strict(),Vk=D({apiVersion:P().min(1),id:ye.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:Am,context:Mm.prefault({}),tools:Dm.prefault({}),phases:ke(P(),jm).optional(),skills:Um.optional(),knowledge:Pm.optional(),memory:zm.optional(),sessions:Bm.optional(),channels:B(Km).default([]),delivery:qm.optional(),schedules:B(Gm).default([]),team:Zm.optional(),subagents:B(Wm).optional(),media:Jm.optional(),standIn:Hm.optional(),delegation:Vm.optional(),plugins:B(Ym).default([]),limits:Qm.prefault({}),server:eg.prefault({})}).strict(),tg={nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096},xn={nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,maxOutput:5000},Dn={vision:!0,nativeTools:!0,strictSchema:!1,thinking:"anthropic",promptCache:"none",parallelToolCalls:!0},jn="Thinking blocks must be replayed with tool results or multi-step reasoning degrades silently. Prompt caching is unavailable on Anthropic's OpenAI-compatible endpoint; through OpenRouter the chat-completions transport sends cache_control itself (`sendsCacheControl`).",Gk=[{pattern:"gpt-4o*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:128000,maxOutput:16384}},{pattern:"gpt-4.1*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:1e6,maxOutput:32768}},{pattern:"gpt-4-turbo*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:128000,maxOutput:4096}},{pattern:"gpt-3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:16385,maxOutput:4096}},{pattern:"gpt-6*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!0,contextWindow:1050000,maxOutput:128000},note:"Window and output are reported figures, unverified here. Run `model probe` or override if your endpoint says otherwise."},{pattern:"gpt-5*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!0,contextWindow:200000,maxOutput:32768},note:"Deliberately conservative on window and output. Override if your endpoint serves more."},{pattern:"o1*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o3*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o4*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},...["claude-fable-5*","claude-opus-5*","claude-opus-4-8*","claude-opus-4-7*","claude-opus-4-6*","claude-sonnet-5*","claude-sonnet-4-6*","claude-haiku-5*"].map((e)=>({pattern:e,capabilities:{...Dn,contextWindow:1e6,maxOutput:128000},note:jn})),{pattern:"claude-haiku-*",family:!0,capabilities:{...Dn,contextWindow:200000,maxOutput:64000},note:jn},{pattern:"claude-*",family:!0,capabilities:{...Dn,contextWindow:200000,maxOutput:8192},note:jn},{pattern:"nova-micro*",capabilities:{...xn,contextWindow:128000}},{pattern:"nova-lite*",capabilities:{...xn,contextWindow:300000,vision:!0}},{pattern:"nova-pro*",capabilities:{...xn,contextWindow:300000,vision:!0}},{pattern:"gemini*",family:!0,capabilities:{vision:!0,nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:1e6,maxOutput:8192}},{pattern:"glm-5.3*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:1048576,maxOutput:131072},note:"Reasoning is billed to the output budget, like the deepseek rows.",verified:"2026-10-21 via OpenRouter, provider z-ai/fp8"},{pattern:"qwen/qwen3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:262144,maxOutput:8192},note:"Reasoning is billed to the output budget, so context.reserveOutput must cover reasoning plus the reply.",verified:"2026-10-23 via OpenRouter, provider deepinfra/bf16 (published context_length 262,144)"},{pattern:"qwen3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192},note:"Served locally by Ollama, which reports no token usage unless model.<role>.streamUsage is set — token figures come from the estimator until it is. Reasoning is billed to the output budget, so context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-13 against qwen3.5:9b on localhost:11434/v1"},{pattern:"qwen*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"llama*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:128000,maxOutput:4096}},{pattern:"mistral*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"mixtral*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"deepseek-v4-pro*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Reasoning tokens are billed to the output budget. With max_tokens=16 this model returned empty content and finish_reason=length; context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-12 against api.deepseek.com/v1"},{pattern:"deepseek-v4-flash*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:1048576,maxOutput:393216},verified:"2026-08-12 against api.deepseek.com/v1 (reasoning confirmed). Measured 2026-08-25 by `model probe --window`: contextWindow 1048576 as a ceiling — the endpoint refused a 1048576-token prompt and named that number; maxOutput 393216 from a refusal naming the range [1, 393216]; automatic prompt caching confirmed at 1024 of 1115 prompt tokens with no breakpoints sent, which is why promptCache stays `none` (it describes the runtime's job, not the provider's behaviour)."},{pattern:"deepseek-v4*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Family fallback for v4 ids this registry has not seen. Assumes reasoning, because both measured v4 models emit it."},{pattern:"deepseek-reasoner*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"Not served by the account this registry was tested against. Numbers are from provider documentation and are deliberately low — override them if your endpoint serves this id."},{pattern:"deepseek-chat*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:65536,maxOutput:8192},note:"Unverified, from provider documentation."},{pattern:"deepseek-r1*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"The open-weight name for the reasoner, used by self-hosted and Ollama deployments."},{pattern:"deepseek*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192}},{pattern:"gemma*",family:!0,capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096}},{pattern:"phi*",family:!0,capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:16384,maxOutput:4096}},{pattern:"*",capabilities:tg}];var ng=/^(?:[-*+]|\d+[.)])[ \t]+\S/,rg=/\*\*(\d{4})-(\d{2})-\d{2}T/;function ig(e){let t=[],n=-1,r=(i)=>{if(n===-1)return;t.push({start:n,end:i,text:e.slice(n,i).join(`
235
- `).trimEnd()}),n=-1};for(let i=0;i<e.length;i+=1){let o=e[i]??"";if(ng.test(o)){r(i),n=i;continue}if(n===-1)continue;if(o.trim()===""||/^[ \t]/.test(o))continue;r(i)}return r(e.length),t}function Zn(e){return pu(Sm(km(e)))}function sg(e,t){let n=rg.exec(e);if(n!==null)return`${n[1]}-${n[2]}.md`;let r=t.getUTCFullYear(),i=`${t.getUTCMonth()+1}`.padStart(2,"0");return`${r}-${i}.md`}function og(e,t){let n=e.split(/\r?\n/),r=ig(n),i=[],o=r,s=e,c=Zn(s);while(c>t&&o.length>1){let l=o[0];if(l===void 0)break;i.push(l),o=o.slice(1),s=ag(n,i),c=Zn(s)}if(c<=t)return{evict:i,remaining:s,tokens:c};return{evict:i,remaining:s,tokens:c,shortfall:o.length<=1?`${c} tokens remain against a ${t}-token budget with one note left, so eviction cannot help`:`${c} tokens remain against a ${t}-token budget`}}function ag(e,t){let n=new Set;for(let r of t)for(let i=r.start;i<r.end;i+=1)n.add(i);return e.filter((r,i)=>!n.has(i)).join(`
236
- `).replace(/\n{3,}/g,`
237
-
238
- `)}async function cg(e){let t=e.tags.length===0?"":` _(${e.tags.join(", ")})_`,n=`
239
- - **${e.now.toISOString()}**${t} ${e.text}
240
- `;return await ao(e.path,n,"utf8"),await lg(e)}async function lg(e){let t=await gm(e.path,"utf8"),n=og(t,e.budget);if(n.evict.length===0)return{file:e.name,evicted:0,archives:[],...n.shortfall===void 0?{}:{shortfall:n.shortfall}};let r=new Map;for(let i of n.evict){let o=sg(i.text,e.now);r.set(o,[...r.get(o)??[],i.text])}await mm(e.archiveDir,{recursive:!0});for(let[i,o]of r)await ao(wm(e.archiveDir,i),`${o.join(`
241
- `)}
242
- `,"utf8");return await ym(e.path,n.remaining,"utf8"),{file:e.name,evicted:n.evict.length,archives:[...r.keys()].sort(),...n.shortfall===void 0?{}:{shortfall:n.shortfall}}}var cn="local",Wi="memory",Ji="notes.md",ug={spec:{slug:"now",provider:cn,summary:"Reports the current date and time.",whenToUse:"you need today's date or the current time — including to work out what 'tomorrow' or 'in three hours' means",whenNotToUse:"the person already told you the date or time; use theirs rather than replacing it with the clock",mutating:!1,tags:["read","time"],parameters:{type:"object",properties:{timezone:{type:"string",description:"IANA name such as Europe/London. Defaults to UTC."},format:{type:"string",description:"iso for a machine-readable timestamp, human for a readable one",enum:["iso","human"],default:"iso"}}}},handler(e,t){let n=t.now(),r=typeof e.timezone==="string"&&e.timezone!==""?e.timezone:"UTC";if(e.format==="human")return`${new Intl.DateTimeFormat("en-GB",{dateStyle:"full",timeStyle:"short",timeZone:r}).format(n)} (${r})`;if(r==="UTC")return n.toISOString();return`${dg(n,r)} (${r})`}};function dg(e,t){let n=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"longOffset"}).formatToParts(e),r=(o)=>n.find((s)=>s.type===o)?.value??"",i=r("timeZoneName").replace("GMT","");return`${r("year")}-${r("month")}-${r("day")}T${r("hour")}:${r("minute")}:${r("second")}${i===""?"Z":i}`}var fg={spec:{slug:"memory_write",provider:cn,summary:"Saves a short note for later recall.",whenToUse:"the person tells you something durable about themselves or their work that later conversations should know",whenNotToUse:"for anything already in this conversation, for secrets or credentials, or to store your own reasoning",mutating:!0,tags:["write","memory"],parameters:{type:"object",properties:{text:{type:"string",description:"The note, in one or two sentences."},tags:{type:"array",items:{type:"string"},description:"Optional labels."}},required:["text"]}},async handler(e,t){let n=typeof e.text==="string"?e.text.trim():"",r=Array.isArray(e.tags)?e.tags.map((l)=>String(l)):[],i=t.now().toISOString(),o=r.length===0?"":` _(${r.join(", ")})_`,s=`
243
- - **${i}**${o} ${n}
244
- `;if(t.writeNote!==void 0)return await t.writeNote(r.length===0?n:`${n} (${r.join(", ")})`);let c=await hg(n,r,s,t);if(t.shareNote===void 0)return c;return`${c} ${await t.shareNote(r.length===0?n:`${n} (${r.join(", ")})`)}`}};async function hg(e,t,n,r){let i=r.writeTarget;if(i?.mode==="refused")throw ou(i.name,i.reason??"none");if(i?.path!==void 0){if(i.budget!==void 0&&r.memoryDir!==void 0&&i.eviction==="oldest"){let s=await cg({path:i.path,name:i.name,budget:i.budget,archiveDir:r.memoryDir,text:e,tags:t,now:r.now()});if(s.shortfall!==void 0)return`Saved to ${s.file}, but it is still over budget: ${s.shortfall}. Ask the person to raise the budget or shorten the file — the agent will not load until they do.`;if(s.evicted===0)return`Saved to ${s.file}.`;return`Saved to ${s.file}. Moved ${s.evicted} older ${s.evicted===1?"note":"notes"} into ${s.archives.join(", ")}, still searchable.`}if(await Ki(i.path,n,"utf8"),i.budget!==void 0){let s=Zn(await pm(i.path,"utf8"))-i.budget;if(s>0)return`Saved to ${i.name}, which is now ${s} tokens over its ${i.budget}-token budget. The agent will not load until that is fixed: add \`eviction: oldest\` to its frontmatter so older notes move to the memory directory, or raise the budget.`}return`Saved to ${i.name}.`}let o=qi(r.dir,Wi);return await hm(o,{recursive:!0}),await Ki(qi(o,Ji),n,"utf8"),`Saved to ${Wi}/${Ji}.`}var pg=1200,mg=pg*3,gg={spec:{slug:"artifact_read",provider:cn,summary:"Reads back a tool result that compaction replaced with a pointer.",whenToUse:"a compaction marker in this conversation names an id, and you need the tool result it replaced",whenNotToUse:"for anything still written out in the conversation, or to explore — every id comes from a marker, so there is nothing to browse",mutating:!1,tags:["read","context"],parameters:{type:"object",properties:{id:{type:"string",description:"The id printed inside the compaction marker, copied character for character."},from:{type:"integer",description:"Character offset to continue from. Omit for the beginning; a truncated reply says the number to pass."}},required:["id"]}},async handler(e,t){let n=typeof e.id==="string"?e.id.trim():"",r=typeof e.from==="number"&&e.from>0?Math.floor(e.from):0;if(t.readArtifact===void 0)throw lu();let i=await t.readArtifact(n);if(i===void 0)throw uu(n);let o=i.slug===void 0?"observation":`${i.slug} observation`,s=i.content.slice(r,r+mg),c=r+s.length,l=`Compacted ${o}, ${i.tokens} tokens${r===0?"":`, from character ${r}`}:`;if(c>=i.content.length)return`${l}
245
- ${s}`;return`${l}
246
- ${s}
247
-
248
- [cut here — ${i.content.length-c} characters remain; continue with artifact_read(id, from: ${c})]`},trustOf:(e)=>fu(typeof e.id==="string"?e.id.trim():"")},yg=30,wg={spec:{slug:"memory_forget",provider:cn,summary:"Finds and deletes saved notes, and what was said in past conversations.",whenToUse:"the person asks you to forget something you noted. Call it with `query` first, show the person what matched, then call it with the `ids` they confirm",whenNotToUse:"to tidy notes nobody asked you to remove, or with `ids` you have not shown the person",mutating:!0,tags:["write","memory"],parameters:{type:"object",properties:{query:{type:"string",description:"Words every matching note or past message contains, case-insensitive. Lists matches; deletes nothing."},ids:{type:"array",items:{type:"string"},description:"Ids from a previous listing (notes and conversation messages). Deletes exactly these."}}}},async handler(e,t){let n=typeof e.query==="string"?e.query.trim():"",r=Array.isArray(e.ids)?e.ids.map((l)=>String(l).trim()).filter((l)=>l!==""):[];if(n===""===(r.length===0))throw au();if(t.forgetMemory===void 0)throw cu();let i=(l)=>l==="space"?"the team's shared memory":"your notes";if(n!==""){let l=await t.forgetMemory({query:n});if(l.notes.length===0)return`No note in ${i(l.scope)} contains "${n}".`;let a=l.notes.slice(0,yg),h=l.notes.length>a.length?`
249
- ${l.notes.length-a.length} more match; use more words to narrow it down.`:"";return[`${l.notes.length} ${l.notes.length===1?"note":"notes"} in ${i(l.scope)} ${l.notes.length===1?"matches":"match"}. Nothing is deleted yet: show these to the person, then call memory_forget with the ids they confirm.`,...a.map((f)=>`- ${f.id} (${f.source}): ${f.text}`)].join(`
250
- `)+h}let o=await t.forgetMemory({ids:r}),s=o.notes.length===0?`Nothing was deleted from ${i(o.scope)}.`:`Deleted ${o.notes.length} ${o.notes.length===1?"note":"notes"} from ${i(o.scope)}; they will not be recalled again.`,c=o.missing.length===0?"":` No note has ${o.missing.length===1?"the id":"the ids"} ${o.missing.join(", ")}: already gone, or not yours to delete here.`;return s+c}},vg=[ug,fg,wg,gg],Yk=vg.map((e)=>e.spec.slug);var po=[{path:"tools.local",means:"built-in tools: now, memory_write, memory_forget, artifact_read",agentListed:!0},{path:"tools.providers",means:"where tools come from, as a map — {system: {}} for shell and files, {web: {backend: tavily, apiKeyEnv: TAVILY_API_KEY}} for the internet. Several at once",toAgent:"A writeRoots key inside is refused",agentListed:!0},{path:"tools.pinned",means:"the tools from those providers this agent may call",agentListed:!0},{path:"tools.policy.allow",means:'rules permitting a call: "exec", or narrower like "exec(git *)". Also what lets a mutating tool run in a turn that has read untrusted content',agentListed:!0},{path:"tools.policy.deny",means:"rules refusing a call. Beats any allow rule",toAgent:"Replacing these is refused: it is the one edit whose only purpose is to remove a restriction someone set",agentListed:!0,confirm:"Deny rules are the restrictions that beat every allow rule. Replacing them removes whatever was deliberately put out of reach."},{path:"tools.policy.mode",means:"allow | ask | deny — for calls no rule mentions",agentListed:!0},{path:"tools.untrusted.onMutate",means:"refuse | confirm | allow — what happens when a tool that changes something is asked for in a turn that has read outside content",toAgent:'Cannot be set to "allow"',agentListed:!0,confirm:'Setting this to "allow" turns off the check that stops text from outside the conversation driving a tool that changes things. A fetched page that says "now delete the backups" would be acted on.'},{path:"tools.dialect",means:"nlt | native — how tool calls are written",agentListed:!0},{path:"description",means:"what this agent is for, in one line of at most 200 characters. The person's other agents see it beside this one in ask_agent",agentListed:!0},{path:"model.main.id",means:"the model this agent runs on",agentListed:!0},{path:"model.main.temperature",means:"0 to 2",agentListed:!0},{path:"model.main.maxTokens",means:"the most one reply may generate; unset lets the endpoint decide",agentListed:!1},{path:"tools.budget.max",means:"how many tools the model is shown at once, built-ins included",agentListed:!1},{path:"model.main.reasoningEffort",means:"none | minimal | low | medium | high | xhigh | max — how hard a reasoning model thinks",agentListed:!1},{path:"model.main",means:"the main model as a whole role, {api, id, baseUrl or options, apiKeyEnv, capabilities, ...}; replaces it in one write",agentListed:!1},{path:"model.<role>",means:"a named model role, {id, api or baseUrl, apiKeyEnv, ...}; a schedule or message runs on it with role: <name>",agentListed:!1},{path:"limits.maxSteps",means:"tool calls allowed in one turn",agentListed:!0},{path:"limits.toolTimeoutMs",means:"how long any single tool may take",agentListed:!0},...["static","volatile","reminder","total"].map((e)=>({path:`context.budgets.${e}`,means:`token budget for the ${e==="total"?"whole workspace":`${e} tier`}; a file over it stops the agent loading`,agentListed:!1})),{path:"limits.noProgress",means:"when a turn is stopped for going nowhere, as a map: {identicalCalls: <n, default 3>, sameTool: <n, off when absent>}",agentListed:!1},{path:"limits.noProgress.sameTool",means:"stop a turn after this many calls in a row to one tool, whatever the arguments. Absent, off",agentListed:!1},{path:"context.modelIdentity",means:"shown or hidden: whether the agent can see which model it runs on (hidden keeps tuning settable)",agentListed:!1},{path:"context.window",means:"the token budget for a whole request; unset uses the model's known window",agentListed:!1},{path:"context.observationMaxTokens",means:"how much of a tool's output reaches the model",agentListed:!0},{path:"tools.eventDetail",means:"none | redacted — whether tool events carry the call's arguments and output",agentListed:!1},{path:"context.rules.onExceed",means:"fail | warn — whether too many counted rules in the workspace refuses the load",agentListed:!1},{path:"channels",means:"how people reach this agent, as a list — [{type: telegram, id: tg, tokenEnv: TELEGRAM_BOT_TOKEN, mode: longpoll}]. The token goes in the .env",toAgent:"The token itself goes in the .env, which only a person can write. allowFrom is refused here: who may talk to you is not yours to decide",agentListed:!0},{path:"delivery",means:"where a reply goes when a turn has no origin — {default: tg}. Names a channel id, not a channel type",agentListed:!0},{path:"delivery.reply",means:"channel replies: all (every step's text, default) or final (the last step's only)",agentListed:!0},{path:"schedules",means:'what runs unattended, as a list — [{id, kind: cron|every|at, expr, task, deliver}]. expr is a 5- or 6-field cron, a duration like 15m, or an ISO instant; deliver is {channel, to} or the literal "none"',toAgent:"Only `serve` fires these; under `run` they are validated and listed and no timer starts. deliver.to is the address a reply is *sent* to — on Telegram the numeric chat id, never an @handle, which addresses a channel and not a person. It is the id inbound messages arrive on, so read it off your own session keys (tg:<id>); allowFrom holds handles and confers nothing here. Set role to name a model other than main. The whole list is replaced, so read it first",agentListed:!0},{path:"media",means:"voice notes, spoken replies and images: {transcription, speech, image}, each {provider: openai|aws, model, apiKeyEnv, options}",toAgent:"image adds image_generate after a restart; filling in the key variable is the person's",agentListed:!0},{path:"server.enabled",means:"true | false — serve the HTTP API on 127.0.0.1",toAgent:"host and tokenEnv are refused: binding anywhere reachable is not yours to decide",agentListed:!0},{path:"server.port",means:"port for the HTTP API",agentListed:!0},{path:"channels[].allowFrom",means:"who may talk to this agent through a channel. Empty or absent refuses everyone — a bot that is connected, healthy and answering nobody is almost always this",agentListed:!1,via:"config allow"},{path:"server.host",means:"the address the HTTP API binds. 127.0.0.1 is local only; anything else is reachable from the network",agentListed:!1},{path:"server.tokenEnv",means:"the env var holding the bearer token the API requires. Without it the API is unauthenticated",agentListed:!1},{path:"delegation.offer",means:`what this agent takes on when another member's agent asks it, as a map: {task: "<one line>", artifact: {type: object, properties: {...}, required: [...]}}. The agents whose delegation.to names this one are reloaded so their roster shows it`,agentListed:!1},{path:"delegation.to",means:`the other members' agents this one may ask, by id, or "*" for every agent that offers. A peer ask is one hop: the asked agent answers, and cannot ask onward`,agentListed:!1},{path:"delegation.ask",means:"true or false: this agent asks the person's other agents (ask_agent) and they may ask it. Both have to say yes; an agent assigned to nobody that says yes is a shared agent anyone's agent may ask",agentListed:!1},{path:"sessions.scope",means:"how a turn's conversation is chosen: channel-peer (one per surface, the default), owner (the owner's turns from every surface share one), or peer (owner, and every registered participant gets one too)",agentListed:!1},{path:"memory.shared",means:"read and write the memory this agent's owner's agents share (agents:<owner>). Default true; false keeps memory_write private",agentListed:!1},{path:"subagents",means:"children that run work in their own context, as a list of {name, task, tools, route?: {tools}, spawn?, model?, maxSteps?, timeoutMs?}. route runs a child for those tool calls; spawn: true lets the model start it with delegate. Each tool must be pinned, and each routed slug belongs to one child",agentListed:!1},{path:"skills.trusted",means:"the skills whose scripts may run, by name. A skill not listed is still used for its steps, and its scripts are documentation only. Absent, every skill's scripts run",agentListed:!1},{path:"tools.providers.<id>.writeRoots",means:"the directories a file tool may write to, for that provider. Nothing outside them is writable — and this binds file tools only, never exec, which carries its target inside a shell string",agentListed:!1}],Xk=po.filter((e)=>e.agentListed).map((e)=>e.path),Qk=po.filter((e)=>e.via===void 0&&!e.path.includes("<")&&!e.path.includes("[")).map((e)=>e.path);var e0=["Summarise the conversation above for your own future reference. You are writing notes to yourself, not a report for a person.","","The person's own requests are preserved verbatim below your summary, so do not restate them.","Keep: decisions taken and why, facts established by tool results, and anything still outstanding.","Drop: pleasantries, your own reasoning, and anything already superseded.","Write plain prose under 300 words. No headings, no preamble, no closing summary.","End with one line naming what this summary does not cover, so a later step knows to ask rather than assume."].join(`
251
- `);var t0=(()=>{let e=Symbol.for(`${er.slug}.liveRuntimes`),t=globalThis;return t[e]??=new Set,t[e]})();var bg="id, session_key, turn_id, role, content, tool_calls, tool_call_id, origin, tainted, created_at",n0=bg.split(", ").map((e)=>`m.${e}`).join(", ");var r0=new Set("a an and are as at be but by do does for from had has have he her his i if in is it its me my not of on or our she that the their them then there they this to was we were what when which who will with you your would could should im ive dont its ill".split(" ")),$g=65536,Eg=1000,Gi=[1000,2000,5000,15000,30000,60000],Ag=3,Og=512,Yi=60000,Ng=180000,Ig=3000,Cg=401,Pg=515,Mg={code:"whatsapp_bun_unsupported",message:"WhatsApp pairing does not complete under Bun — the socket opens and the handshake never finishes.",hint:"Measured against the same bundle: it pairs under Node in about two seconds and never under Bun. Every shipped install (npm, brew, the container) runs under Node; this process is running from a checkout with `bun run`. Use `node` — or the installed command — instead. It keeps trying regardless, in case the cause is fixed upstream."};function Xi(e){let t=e.authState?.creds;if(t===void 0)return!0;return t.registered===!0||t.account!==void 0&&t.account!==null}function Qi(){return typeof globalThis.Bun<"u"}class mo{id;type="whatsapp";limits={maxMessageChars:$g,idempotentSend:!1,attachments:!0,voiceNotes:!0,minSendIntervalMs:Eg};alwaysAllow;#e;#n;#t;#r;#o;#i;#a;#s;#c=!1;#l=0;#u=!1;#d=!0;#f=0;#p=!1;#h=new Set;#m=[];#w;#g=!1;constructor(e){this.id=e.id,this.#e=e.authDir,this.#n=e.pairWith,this.#t=e.deviceName,this.alwaysAllow=e.pairWith===void 0||e.pairWith===""?[]:[e.pairWith],this.#r=e.pairingDelayMs??Ig,this.#o=e.api}async start(e){if(this.#c)return;if(this.#c=!0,this.#a=e,Qi())e.error(Mg);this.#w=this.#v(e)}async stop(){if(!this.#c)return;this.#c=!1;try{this.#s?.end()}catch{}this.#s=void 0,this.#y?.(),this.#y=void 0,await this.#w?.catch(()=>{}),this.#w=void 0,this.#a?.status("disconnected"),this.#a=void 0}async send(e){let t=this.#s;if(t===void 0)return{ok:!1,retryable:!0,error:{code:"whatsapp_not_connected",message:`Channel "${this.id}" is not connected to WhatsApp.`,hint:"The reconnect loop keeps trying and the outbox holds this message. If it never connects, the pairing was probably revoked — check the channel's status, which carries the QR when one is waiting to be scanned."}};try{let n=e.attachment,i=(await t.sendMessage(es(e.recipient),n===void 0?{text:e.text}:n.mimeType.startsWith("audio/")?{audio:await Vi(n.path),mimetype:"audio/ogg; codecs=opus",ptt:!0}:{image:await Vi(n.path),mimetype:n.mimeType,...e.text===""?{}:{caption:e.text}}))?.key?.id;if(i!==void 0&&i!==null){if(this.#m.push(i),this.#m.length>Og)this.#m.shift()}return i===void 0||i===null?{ok:!0}:{ok:!0,providerMessageId:i}}catch(n){return{ok:!1,retryable:!0,error:{code:"whatsapp_send_failed",message:n instanceof Error?n.message:String(n),hint:"Retried, because an unclassified failure from an unofficial client is not one known to be permanent. A recipient that does not exist on WhatsApp fails this way too, and that one will not recover — check the number against `allowFrom`."}}}}async reset(){this.#_();try{this.#s?.end()}catch{}this.#s=void 0,this.#l=0,this.#a?.status("disconnected","unpaired — scan the next QR to link a device"),this.#y?.(),this.#y=void 0}async typing(e){await this.#s?.sendPresenceUpdate("composing",es(e))}async#v(e){while(this.#c&&!this.#p){try{let n=this.#o??await jg();this.#i=n,_g(this.#e,{recursive:!0,mode:448}),this.#u=this.#n!==void 0&&this.#n!=="";let r=await n.connect({authDir:this.#e,...this.#t===void 0?{}:{deviceName:this.#t},onUpdate:(i)=>this.#T(e,i),onCreds:()=>this.#A(),onMessages:(i)=>this.#$(e,i)});this.#s=r,this.#d=Xi(r),await this.#k(e,r),await this.#S()}catch(n){if(!this.#c)return;this.#b(e,n)}if(!this.#c)return;let t=this.#g;if(this.#g=!1,!t)await ts(this.#E())}}async#k(e,t){let n=this.#n;if(n===void 0||n==="")return;if(Xi(t))return;if(typeof t.requestPairingCode!=="function"){e.status("needs_input",`channel "${this.id}" is set to pair by code and this build of baileys cannot`,{kind:"qr",payload:"",expiresAt:new Date(Date.now()+Yi).toISOString()});return}try{if(await ts(this.#r),!this.#c)return;let r=await t.requestPairingCode(n);e.status("needs_input",`enter this code on WhatsApp for +${n} — Linked devices › Link with phone number`,{kind:"pairing_code",payload:r,expiresAt:new Date(Date.now()+Ng).toISOString()})}catch(r){this.#u=!1,this.#b(e,r)}}#S(){if(!this.#c)return Promise.resolve();return new Promise((e)=>{this.#y=e})}#y;#T(e,t){if(t.qr!==void 0&&t.qr!==""&&!this.#u){e.status("needs_input",`scan to pair channel "${this.id}"`,{kind:"qr",payload:t.qr,expiresAt:new Date(Date.now()+Yi).toISOString()});return}if(t.connection==="open"){this.#f=0,this.#l=0;let n=this.#s?.user;if(this.#h.clear(),n?.id!==void 0)this.#h.add(Kt(n.id));if(n?.lid!==void 0)this.#h.add(Kt(n.lid));e.status("connected","paired");return}if(t.connection==="close"){let n=t.lastDisconnect?.error?.output?.statusCode;if(n===Cg)if(this.#_(),this.#d)this.#f=0,e.status("disconnected","logged out — pairing again, scan the next QR"),e.error({code:"whatsapp_logged_out",message:`Channel "${this.id}" was logged out of WhatsApp.`,hint:"The stored session was revoked — from the phone's linked-devices screen, or by WhatsApp. The saved credentials have been deleted and a new QR follows; scan it to pair again."});else if(this.#f+=1,this.#l+=1,this.#f>=Ag)this.#p=!0,e.status("error",`pairing refused ${this.#f} times — not asking again`),e.error({code:"whatsapp_pairing_refused",message:`WhatsApp refused ${this.#f} pairing attempts for channel "${this.id}" and none completed.`,hint:Qi()?"This is what the Bun limitation looks like from the outside: a code is issued and invalidated seconds later. Pair using the npm-installed package, whose bin runs under Node, then bring the paired session back. Retrying here only spends failed pairings against the number.":this.#t!==void 0?`deviceName is set ("${this.#t}"), and some accounts refuse a non-standard device name under pairing-by-code. Remove deviceName from the channel and pair again; check the number too. Repeated failed pairings are the thing that gets an account restricted, so this stops rather than continuing.`:"Check that the number is the one WhatsApp is registered to, in digits with no +. Repeated failed pairings are the thing that gets an account restricted, so this stops rather than continuing."});else e.status("disconnected","pairing refused — trying once more");else if(n===Pg)this.#g=!0;else if(this.#l+=1,this.#l===1||this.#l%8===0)e.status("disconnected",t.lastDisconnect?.error?.message??"connection closed");this.#s=void 0,this.#y?.(),this.#y=void 0}}#$(e,t){if(t.type!=="notify")return;for(let n of t.messages){let r=Lg(n,{ownJids:this.#h,sentIds:this.#m});if(r===void 0)continue;let i=xg(n),o=yo(n),s=this.#i,c=async()=>{if(s?.download===void 0)throw Error("this Baileys build cannot download media");return s.download(n)};e.receive({...r,...i===void 0?{}:{audio:{...i,fetch:c}},...o===void 0?{}:{images:[{...o,fetch:c}]}})}}#b(e,t){if(this.#l+=1,this.#l!==1&&this.#l%8!==0)return;e.status("error",t instanceof Error?t.message:String(t)),e.error({code:"whatsapp_connect_failed",message:`Channel "${this.id}" could not connect: ${t instanceof Error?t.message:String(t)}`,hint:"The loop keeps retrying and the rest of the runtime is unaffected. If it never connects, check network access and whether the paired number is still linked in WhatsApp's linked-devices screen."})}#E(){let e=Math.min(this.#l,Gi.length-1);return Gi[e]??1000}#_(){Sg(this.#e,{recursive:!0,force:!0})}#A(){try{Hi(this.#e,448);for(let e of kg(this.#e))Hi(Tg(this.#e,e),384)}catch{}}}var Rg={ownJids:new Set,sentIds:[]};function Lg(e,t=Rg){let n=e.key?.remoteJid;if(n===null||n===void 0||n==="")return;let r=e.key?.id;if(e.key?.fromMe===!0){if(r!==null&&r!==void 0&&t.sentIds.includes(r))return;let h=Kt(n),f=e.key?.remoteJidAlt,d=f===null||f===void 0?void 0:Kt(f);if(!(t.ownJids.has(h)||d!==void 0&&t.ownJids.has(d)))return}if(n.endsWith("@g.us")||n==="status@broadcast")return;let i=e.message,o=i?.conversation??i?.extendedTextMessage?.text??i?.imageMessage?.caption??i?.videoMessage?.caption??i?.documentMessage?.caption??"";if(o.trim()===""&&(i?.audioMessage??void 0)===void 0&&yo(e)===void 0)return;let s=e.messageTimestamp,c=typeof s==="number"?s:typeof s?.toNumber==="function"?s.toNumber():void 0,l=Dg(n,e.key?.remoteJidAlt),a=e.pushName;return{...r===null||r===void 0?{}:{providerMessageId:r},peerId:l,senderHandle:vo(l),...a===null||a===void 0||a===""?{}:{senderName:a},text:o,receivedAt:new Date(c===void 0?Date.now():c*1000).toISOString()}}function xg(e){let t=e.message?.audioMessage;if(t===null||t===void 0)return;let n=wo(t.fileLength);return{mimeType:t.mimetype??"audio/ogg",...typeof t.seconds==="number"?{durationS:t.seconds}:{},...n===void 0?{}:{sizeBytes:n}}}function yo(e){let t=e.message,n=t?.documentMessage,r=t?.imageMessage??(n?.mimetype?.startsWith("image/")===!0?n:void 0);if(r===null||r===void 0)return;let i=wo(r.fileLength);return i===void 0?{}:{sizeBytes:i}}function wo(e){return typeof e==="number"?e:typeof e?.toNumber==="function"?e.toNumber():void 0}function Dg(e,t){if(e.endsWith("@s.whatsapp.net"))return e;if(t?.endsWith("@s.whatsapp.net")===!0)return t;return e}function Kt(e){let t=e.indexOf("@");if(t===-1)return e;let n=e.slice(0,t),r=n.indexOf(":");return`${r===-1?n:n.slice(0,r)}${e.slice(t)}`}function vo(e){let t=e.indexOf("@"),n=t===-1?e:e.slice(0,t),r=n.indexOf(":");return r===-1?n:n.slice(0,r)}function es(e){return e.includes("@")?e:`${vo(e)}@s.whatsapp.net`}async function jg(){let e=await import("./index-2td5h856.js"),t=e.default,n=typeof t==="function"?t.default:void 0,r=typeof t==="function"?n??t:e.makeWASocket,i=e.useMultiFileAuthState??(typeof t==="function"?t.useMultiFileAuthState:void 0),o=e.downloadMediaMessage??(typeof t==="function"?t.downloadMediaMessage:void 0);if(typeof r!=="function"||typeof i!=="function")throw Error("the installed baileys package does not export makeWASocket and useMultiFileAuthState");return{...o===void 0?{}:{download:(s)=>o(s,"buffer",{})},connect:async({authDir:s,deviceName:c,onUpdate:l,onCreds:a,onMessages:h})=>{let{state:f,saveCreds:d}=await i(s),u=r({auth:f,printQRInTerminal:!1,browser:[c??"Ubuntu","Chrome","22.04.4"],logger:Ug(),markOnlineOnConnect:!1});return u.ev.on("connection.update",l),u.ev.on("creds.update",async()=>{await d(),await a()}),u.ev.on("messages.upsert",h),u}}}function Ug(){let e=()=>{},t={level:"silent",trace:e,debug:e,info:e,warn:e,error:e,fatal:e};return t.child=()=>t,t}function ts(e){return new Promise((t)=>setTimeout(t,e))}var zg="./.whatsapp",dr=(e)=>{let t=Un(e.config,"authDir")??zg,n=Yl(t)?t:Xl(e.dir,t),r=e.config.api,i=Un(e.config,"pairWith"),o=i===void 0?void 0:i.replace(/[^0-9]/g,"");if(i!==void 0&&!/^[0-9]{6,20}$/.test(o??""))throw new zn({code:"whatsapp_pair_with_invalid",message:`Channel "${e.id}" has a pairWith that is not a WhatsApp number: "${i}".`,hint:"Write the digits with the country code, with or without a + (for example +8801711223344 or 8801711223344); spaces and dashes are normalised away. The agent still starts — a channel is optional, so this one is reported broken rather than blocking the load.",field:`channels[${e.id}].pairWith`});let s=Un(e.config,"deviceName");if(s!==void 0&&!/^[\x20-\x7e]{1,32}$/.test(s))throw new zn({code:"whatsapp_device_name_invalid",message:`Channel "${e.id}" has a deviceName outside 1-32 printable ASCII characters: "${s}".`,hint:"The deviceName is the bracket of the phone's Linked-devices label, so WhatsApp validates it: keep it 1-32 printable ASCII characters (letters, digits, spaces, punctuation). The agent still starts — a channel is optional, so this one is reported broken rather than blocking the load.",field:`channels[${e.id}].deviceName`});let c=e.config.pairingDelayMs;return new mo({id:e.id,authDir:n,...o===void 0?{}:{pairWith:o},...s===void 0?{}:{deviceName:s},...typeof c==="number"?{pairingDelayMs:c}:{},...r===void 0?{}:{api:r}})};var Fg="0.1.0",bo={name:"whatsapp",version:Fg,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["web.whatsapp.com","*.whatsapp.net"]},{kind:"fs",paths:["<agent>/.whatsapp"],mode:"write"}],setup(e){e.defineChannel("whatsapp",dr)}};function Un(e,t){let n=e[t];return typeof n==="string"&&n!==""?n:void 0}import{spawn as wy}from"node:child_process";import{readFile as Bg}from"node:fs/promises";class ln extends Error{name="CredentialsRefusedError";status;code;detail;constructor(e,t,n){super(`The credentials endpoint ${e>=500?"failed":"refused"} with status ${e}${t===void 0?"":` (${t})`}${n===void 0?"":`: ${n}`}`);this.status=e,this.code=t,this.detail=n}}var Kg=new Set(["127.0.0.1","localhost","[::1]","169.254.170.2","169.254.170.23","[fd00:ec2::23]"]),qg=300000;function hr(e,t=fetch){let n=e.AWS_CONTAINER_CREDENTIALS_FULL_URI;if(n===void 0||n==="")return;let r;try{r=new URL(n)}catch{return}if(r.protocol!=="https:"&&!(r.protocol==="http:"&&Kg.has(r.hostname)))return;let i;return async()=>{if(i?.expiration!==void 0&&i.expiration.getTime()-Date.now()>qg)return i;let o=e.AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE,s=o!==void 0&&o!==""?(await Bg(o,"utf8")).trim():e.AWS_CONTAINER_AUTHORIZATION_TOKEN,c=await t(r,{headers:s===void 0||s===""?{}:{authorization:s},signal:AbortSignal.timeout(5000)}),l=await c.text(),a={};try{let m=JSON.parse(l);if(typeof m==="object"&&m!==null)a=m}catch{}let h=(...m)=>{for(let g of m)if(typeof a[g]==="string")return a[g];return};if(c.status>=400)throw new ln(c.status,h("code","Code"),h("message","Message"));let f=h("AccessKeyId"),d=h("SecretAccessKey");if(!c.ok||f===void 0||d===void 0)throw Error(`The credentials endpoint answered ${c.status} without AccessKeyId and SecretAccessKey.`);let u=h("Token"),p=h("Expiration");return i={accessKeyId:f,secretAccessKey:d,...u===void 0?{}:{sessionToken:u},...p===void 0?{}:{expiration:new Date(p)}},i}}var Zg={ThrottlingException:429,ServiceUnavailableException:503,InternalServerException:500,ModelNotReadyException:503,ModelStreamErrorException:500,ModelTimeoutException:408},Wg=/ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|socket hang up|TimeoutError/;function Jg(e){if(typeof e!=="object"||e===null)return{name:"Error",message:String(e),status:void 0};let t=e,n=t.$metadata?.httpStatusCode;return{name:typeof t.name==="string"?t.name:"Error",message:typeof t.message==="string"?t.message:String(e),status:typeof n==="number"?n:void 0}}function Hg(e,t,n,r){let{name:i,message:o,status:s}=Jg(e),c=Zg[i];if(c!==void 0){let h=s??c;return{retryable:!0,status:h,error:new ct({code:"model_http_error",message:`Bedrock ${i} for ${t} in ${n}.`,detail:o,hint:i==="ThrottlingException"?"Bedrock is throttling this account or model. Retries were spent; raise the model's quota in Service Quotas, spread load across a cross-region inference profile (eu., us., global.), or add a fallback.":"Bedrock reported a service-side failure and retries were spent. It is usually transient; a fallback under model.<role>.fallbacks covers it.",field:r,status:h,cause:e})}}if(i==="CredentialsRefusedError"){let h=e,f=typeof h.status==="number"?h.status:403,d=typeof h.code==="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(h.code)?h.code:void 0;if(f>=500)return{retryable:!0,status:f,error:new ct({code:d??"bedrock_credentials_unavailable",message:`The AWS credentials endpoint could not issue credentials for Bedrock (${t} in ${n}): status ${f}${d===void 0?"":`, ${d}`}${typeof h.detail==="string"?` — ${h.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 ct({code:d??"bedrock_credentials_refused",message:`The AWS credentials endpoint refused to issue credentials for Bedrock (${t} in ${n}): status ${f}${d===void 0?"":`, ${d}`}${typeof h.detail==="string"?` — ${h.detail}`:""}.`,hint:"The container-credentials endpoint answered and declined: the decision of the service vending credentials (a budget or credit stop, a revoked user), not a missing configuration. Its own code is this error's code. Dispach does not retry it.",field:r,status:f,cause:e})}}let l=/responded with status: (\d{3})/.exec(o);if(i==="CredentialsProviderError"&&l!==null)return{retryable:!1,status:Number(l[1]),error:new ct({code:"bedrock_credentials_refused",message:`The AWS credentials endpoint refused to issue credentials for Bedrock (${t} in ${n}): status ${l[1]}.`,hint:"The container-credentials endpoint answered and declined, which is the endpoint's decision rather than a missing configuration — a vending service may refuse once a budget is spent. Check that service; Dispach does not retry it.",field:r,status:Number(l[1]),cause:e})};if(i==="CredentialsProviderError"||/Could not load credentials/i.test(o))return{retryable:!1,status:void 0,error:new ct({code:"bedrock_credentials_missing",message:`No AWS credentials were found for Bedrock (${t} in ${n}).`,hint:"Credentials come from the default AWS chain: AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY in the process environment, a container-credentials endpoint (AWS_CONTAINER_CREDENTIALS_FULL_URI), EKS Pod Identity, or the instance role. Never a manifest field. For a named profile, set options.profile.",field:r,cause:e})};if(i==="AccessDeniedException"||s===403)return{retryable:!1,status:403,error:new ct({code:"model_access_denied",message:`Bedrock refused ${t} in ${n}: these credentials may not invoke it.`,detail:o,hint:/being verified/i.test(o)?"The AWS account is new and AWS is still verifying it, which it says takes under two hours. Nothing in the manifest or the IAM policy changes this; retry once the account is verified.":'Either the credential is invalid or expired (Bedrock says "security token … invalid"), or it is not allowed to invoke this model. For the second, check the IAM policy grants bedrock:InvokeModelWithResponseStream on the model or inference profile, and that model access is enabled in the Bedrock console for this region. An embedder that revokes credentials as a budget stop lands here on purpose, which is why this never falls back.',field:r,status:403,cause:e})};if(i==="ResourceNotFoundException"||s===404)return{retryable:!1,status:404,error:new ct({code:"model_not_found",message:`Bedrock has no model ${t} in ${n}.`,detail:o,hint:/use case details/i.test(o)?"Anthropic models on Bedrock need a one-time use-case form per AWS account: Bedrock console → Model catalog → an Anthropic model → submit the use case details. It applies about 15 minutes after submission.":"Check the model id and region together: a cross-region profile id starts with its geography (eu., us., apac., global.), and a base model id needs on-demand access in that exact region.",field:r,status:404,cause:e})};if(Wg.test(`${i} ${o}`))return{retryable:!0,status:void 0,error:new ct({code:"model_unreachable",message:`Cannot reach Bedrock in ${n}.`,detail:o,hint:"Check outbound HTTPS to bedrock-runtime.<region>.amazonaws.com from this host; a default-deny network policy needs that endpoint listed.",field:r,cause:e})};let a=s??400;return{retryable:!1,status:a,error:new ct({code:"model_http_error",message:`Bedrock ${i} for ${t}.`,detail:o,hint:i==="ValidationException"?"Bedrock refused the request as malformed. Its own words, in `detail`, name the field; a model that does not support a feature asked for (tools, thinking, prompt caching) is the usual cause.":"Bedrock refused the request. Its own words are in `detail`.",field:r,status:a,cause:e})}}var fr={cachePoint:{type:"default"}},Vg={"image/png":"png","image/jpeg":"jpeg","image/gif":"gif","image/webp":"webp"};function _o(e){return/(^|[./])anthropic\.claude|(^|[./])amazon\.nova/.test(e)}function ko(e){let t=/anthropic\.claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d+))?/.exec(e);if(t!==null){let r=Number(t[3]??"0");return{family:t[1]??"",version:Number(t[2])+(r<100?r/10:0)}}let n=/anthropic\.claude-(\d+)(?:-(\d+))?-(opus|sonnet|haiku)/.exec(e);if(n!==null)return{family:n[3]??"",version:Number(n[1])+Number(n[2]??"0")/10};return/anthropic\.claude/.test(e)?{family:"",version:0}:void 0}function un(e){if(/(^|[./])openai\./.test(e))return"openai";let t=ko(e);if(t===void 0)return;if(t.family==="fable"||t.family==="mythos")return"adaptive";if(t.family==="haiku")return t.version>=5.5?"adaptive":"budget";return t.version>=4.7?"adaptive":"budget"}function So(e){let t=ko(e);if(t===void 0)return"disabled";if(t.family==="fable"||t.family==="mythos")return"low";if(t.family==="opus"&&t.version>=5.5)return"low";if(t.family==="sonnet"&&t.version>=5.5)return"between_tools";return"disabled"}function To(e){return un(e)==="adaptive"||/(^|[./])openai\.gpt-6/.test(e)}function Gg(e,t){let n=[];if(un(e.id)==="adaptive"&&e.reasoningEffort==="none"&&So(e.id)==="low")n.push({code:"model_thinking_always_on",message:`${e.id} cannot turn thinking off, so ${t}.reasoningEffort: none runs at low effort.`,hint:`Set ${t}.reasoningEffort: low to say so explicitly, which also silences this.`,field:`${t}.reasoningEffort`});if(To(e.id)&&(e.temperature!==void 0||e.topP!==void 0))n.push({code:"model_sampling_unsupported",message:`${e.id} does not accept temperature or topP, so ${t} sends neither.`,hint:`Remove temperature and topP from ${t}; steer this model with reasoningEffort instead.`,field:t});return n}var Yg=32768,Xg=16384,Qg={minimal:1024,low:2048,medium:8192,high:16384};function ey(e){try{let t=JSON.parse(e===""?"{}":e);return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:{value:t}}catch{return{raw:e}}}function ty(e){let t=[];for(let n of e.thinking??[])t.push(n.redacted!==void 0?{reasoningContent:{redactedContent:Uint8Array.from(Buffer.from(n.redacted,"base64"))}}:{reasoningContent:{reasoningText:{text:n.text,...n.signature===void 0?{}:{signature:n.signature}}}});if(e.content!=="")t.push({text:e.content});for(let n of e.toolCalls??[])t.push({toolUse:{toolUseId:n.id,name:n.name,input:ey(n.arguments)}});return t}function ny(e){if(e.role==="assistant")return{role:"assistant",content:ty(e)};if(e.role==="tool")return{role:"user",content:[{toolResult:{toolUseId:e.toolCallId??"",content:[{text:e.content===""?"(no output)":e.content}]}}]};let t=e.role==="system"&&e.content!==""?`<system>
252
- ${e.content}
253
- </system>`:e.content,n=t===""?[]:[{text:t}];for(let r of e.images??[])n.push({image:{format:Vg[r.mediaType],source:{bytes:Uint8Array.from(Buffer.from(r.data,"base64"))}}});return{role:"user",content:n}}function ry(e){let t=e.findIndex((i)=>i.role!=="system");if(t===-1||e[t]?.role==="user")return e;let n=e.findIndex((i)=>i.turnInput===!0);if(n===-1||n<t)return e;let r=e[n];return[...e.slice(0,t),r,...e.slice(t,n),...e.slice(n+1)]}function iy(e,t){let n=_o(e.model)&&t.capabilities?.promptCache!=="none",r=[],i=[],o=!0;for(let g of ry(e.messages)){if(o&&g.role==="system"){if(g.content!=="")r.push({text:g.content});if(n&&g.cacheBreakpoint===!0)r.push(fr);continue}o=!1;let{role:y,content:w}=ny(g);if(n&&g.cacheBreakpoint===!0&&w.length>0)w.push(fr);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 s=i.at(-1),c=/(^|[./])amazon\.nova/.test(e.model)&&(s?.content??[]).some((g)=>g.toolResult!==void 0);if(n&&s!==void 0&&!c&&s.content?.at(-1)?.cachePoint===void 0)s.content=[...s.content??[],fr];let l=un(e.model),a=e.reasoningEffort,h=l==="budget"&&a!==void 0?Qg[a==="xhigh"||a==="max"?"high":a]:void 0,f=l==="adaptive"?sy(e.model,a):void 0,d=h===void 0&&!To(e.model),u=h!==void 0?Math.max(e.maxTokens??0,h+Xg):f?.thinking===!0?e.maxTokens??Yg:e.maxTokens,p={...u===void 0?{}:{maxTokens:u},...!d||e.temperature===void 0?{}:{temperature:e.temperature},...!d||e.topP===void 0?{}:{topP:e.topP}},m=h!==void 0?{thinking:{type:"enabled",budget_tokens:h}}: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 sy(e,t){if(t===void 0)return;if(t==="none"){let n=So(e);if(n==="low")return{fields:{thinking:{type:"adaptive"},output_config:{effort:"low"}},thinking:!0};return{fields:{thinking:{type:n}},thinking:!1}}return{fields:{thinking:{type:"adaptive"},output_config:{effort:t==="minimal"?"low":t}},thinking:!0}}var oy={end_turn:"stop",stop_sequence:"stop",tool_use:"tool_calls",max_tokens:"length",model_context_window_exceeded:"length",content_filtered:"content_filter",guardrail_intervened:"content_filter",refusal:"content_filter"},ay="<thinking>",cy="</thinking>";function ly(e,t){for(let n=Math.min(t.length-1,e.length);n>0;n-=1)if(t.startsWith(e.slice(-n)))return n;return 0}class $o{#e="";#n=!1;#t=!1;push(e){let t=[],n=this.#e+e;this.#e="";for(;;){let r=this.#n?cy:ay,i=n.indexOf(r);if(i===-1){let o=ly(n,r);return this.#e=n.slice(n.length-o),t.push(...this.#r(n.slice(0,n.length-o))),t}if(t.push(...this.#r(n.slice(0,i))),this.#n=!this.#n,!this.#n)this.#t=!0;n=n.slice(i+r.length)}}flush(){let e=this.#e;return this.#e="",this.#r(e)}#r(e){if(this.#n)return e===""?[]:[{type:"reasoning",delta:e}];let t=this.#t?e.trimStart():e;if(t==="")return[];return this.#t=!1,[{type:"text",delta:t}]}}async function*uy(e,t={}){let n=new Map,r=t.thinkingTags===!0?new $o:void 0;for await(let i of e){if(i.contentBlockStart!==void 0){let c=i.contentBlockStart.start?.toolUse;if(c!==void 0)n.set(i.contentBlockStart.contentBlockIndex??0,{kind:"tool",id:c.toolUseId??"",name:c.name??"",input:""});continue}if(i.contentBlockDelta!==void 0){let c=i.contentBlockDelta.contentBlockIndex??0,l=i.contentBlockDelta.delta;if(l?.text!==void 0){if(r!==void 0)yield*r.push(l.text);else if(l.text!=="")yield{type:"text",delta:l.text}}else if(l?.toolUse!==void 0){let a=n.get(c);if(a?.kind==="tool")a.input+=l.toolUse.input??""}else if(l?.reasoningContent!==void 0){let a=n.get(c);if(a?.kind!=="reasoning")a={kind:"reasoning",text:""},n.set(c,a);let h=l.reasoningContent;if(h.text!==void 0&&h.text!=="")a.text+=h.text,yield{type:"reasoning",delta:h.text};if(h.signature!==void 0)a.signature=h.signature;if(h.redactedContent!==void 0)a.redacted=Buffer.from(h.redactedContent).toString("base64")}continue}if(i.contentBlockStop!==void 0){let c=i.contentBlockStop.contentBlockIndex??0,l=n.get(c);if(n.delete(c),l?.kind==="tool")yield{type:"tool_call",call:{id:l.id,name:l.name,arguments:l.input}};else if(l?.kind==="reasoning")yield{type:"thinking_block",block:{text:l.text,...l.signature===void 0?{}:{signature:l.signature},...l.redacted===void 0?{}:{redacted:l.redacted}}};continue}if(i.messageStop!==void 0){if(r!==void 0)yield*r.flush();let c=i.messageStop.stopReason??"end_turn";yield{type:"finish",reason:oy[c]??c};continue}let o=i.metadata?.usage;if(o!==void 0){let{cacheReadInputTokens:c,cacheWriteInputTokens:l}=o;yield{type:"usage",promptTokens:(o.inputTokens??0)+(c??0)+(l??0),completionTokens:o.outputTokens??0,...c===void 0?{}:{cachedPromptTokens:c,cacheSource:"metadata.usage.cacheReadInputTokens"},...l===void 0?{}:{cacheWriteTokens:l}};continue}let s=i.throttlingException??i.serviceUnavailableException??i.internalServerException??i.modelStreamErrorException??i.validationException;if(s!==void 0)throw s}}var dy=async(e)=>{let t=await import("./index-7zgjkbb0.js"),n=e.profile===void 0?hr(process.env):void 0,r=new t.BedrockRuntimeClient({region:e.region,maxAttempts:1,...e.profile===void 0?{}:{profile:e.profile},...n===void 0?{}:{credentials:n}});return async(i,o)=>{let s=await r.send(new t.ConverseStreamCommand(i),{abortSignal:o});if(s.stream===void 0)throw Error("Bedrock returned a ConverseStream response with no stream.");return s.stream}};function fy(e){return e instanceof Error&&/bound to a different conversation/i.test(e.message)}function hy(e){let t=!1,n=(e.messages??[]).map((r)=>{let i=(r.content??[]).filter((o)=>{let s=o.reasoningContent!==void 0;return t||=s,!s});return{...r,content:i}}).filter((r)=>r.content.length>0);return t?{...e,messages:n}:void 0}var py=/(^|[./])amazon\.nova/,my={safeParse(e){let t=typeof e==="object"&&e!==null?e:{},n=Object.keys(t).find((r)=>r!=="region"&&r!=="profile");if(n!==void 0)return{success:!1,error:{issues:[{message:`unknown option "${n}" (takes region, profile)`}]}};if(typeof t.region!=="string"||t.region==="")return{success:!1,error:{issues:[{message:"region is required, e.g. eu-west-1"}]}};if(t.profile!==void 0&&typeof t.profile!=="string")return{success:!1,error:{issues:[{message:"profile must be a string"}]}};return{success:!0,data:t}}};function gy(e,t){let n=Math.min(e.baseDelayMs*2**(t-1),e.maxDelayMs);return Math.round(n*(0.5+Math.random()/2))}function yy(e,t){return new Promise((n)=>{if(t.aborted)return n();let r=setTimeout(()=>{t.removeEventListener("abort",i),n()},e),i=()=>{clearTimeout(r),n()};t.addEventListener("abort",i,{once:!0})})}function pr(e=dy){return{optionsSchema:my,capabilities:(t,n)=>{let r=n.capabilities?.promptCache===void 0&&_o(n.id)?{...t,promptCache:"bedrock"}:t;return un(n.id)==="openai"?{...r,traceAfterInput:!0}:r},warnings:(t,n)=>Gg(t,n),create(t){let n=t.options;if(n===void 0)throw new Q({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??Ms,i;return{id:t.id,async*chat(o,s){i??=e(n);let c=await i,l=iy(o,t.config),a=!1;for(let h=1;;h+=1){let f=!1;try{for await(let d of uy(await c(l,s),{thinkingTags:py.test(t.config.id)}))f=!0,yield d;return}catch(d){if(s.aborted)return;if(!f&&!a&&fy(d)){let m=hy(l);if(m!==void 0){l=m,a=!0,t.onRetry?.({status:400,attempt:h,delayMs:0});continue}}let u=Hg(d,o.model,n.region,t.field);if(f||!u.retryable||h>=r.attempts)throw u.error;let p=gy(r,h);if(t.onRetry?.({status:u.status??0,attempt:h,delayMs:p}),await yy(p,s),s.aborted)return}}}}}}}var Eo={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",pr())}};var No=16000,vy=(e,t)=>new Promise((n,r)=>{let i=wy("ffmpeg",["-hide_banner","-loglevel","error","-i","pipe:0"].concat(["-f","s16le","-ac","1","-ar",String(No),"pipe:1"]),{stdio:["pipe","pipe","pipe"]}),o=[],s=[],c=()=>i.kill("SIGKILL");t.addEventListener("abort",c,{once:!0}),i.stdout.on("data",(l)=>o.push(l)),i.stderr.on("data",(l)=>s.push(l)),i.on("error",(l)=>{t.removeEventListener("abort",c),r(l)}),i.on("close",(l)=>{if(t.removeEventListener("abort",c),l===0)n(new Uint8Array(Buffer.concat(o)));else r(Error(Buffer.concat(s).toString("utf8").trim()||`ffmpeg exited ${l}`))}),i.stdin.on("error",()=>{}),i.stdin.end(Buffer.from(e))});function gr(e){if(e.profile!==void 0)return{profile:e.profile};let t=hr(process.env);return t===void 0?{}:{credentials:t}}var by={async transcribe(e){let t=await import("./index-pz92ksp8.js"),n=new t.TranscribeStreamingClient({region:e.region,...gr(e)});return async(r,i)=>{let o=await n.send(new t.StartStreamTranscriptionCommand(r),{abortSignal:i});if(o.TranscriptResultStream===void 0)throw Error("Transcribe returned no result stream.");return o.TranscriptResultStream}},async invoke(e){let t=await import("./index-7zgjkbb0.js"),n=new t.BedrockRuntimeClient({region:e.region,...gr(e)});return async(r,i)=>{let o=await n.send(new t.InvokeModelCommand({modelId:r.modelId,contentType:"application/json",accept:"application/json",body:r.body}),{abortSignal:i});return new TextDecoder().decode(o.body)}},async speak(e){let t=await import("./index-635wcsh1.js"),n=new t.PollyClient({region:e.region,...gr(e)});return async(r,i)=>{let o=await n.send(new t.SynthesizeSpeechCommand({Text:r.text,OutputFormat:"ogg_opus",VoiceId:r.voiceId,Engine:r.engine,...r.languageCode===void 0?{}:{LanguageCode:r.languageCode}}),{abortSignal:i});if(o.AudioStream===void 0)throw Error("Polly returned no audio.");return{bytes:await o.AudioStream.transformToByteArray(),...o.RequestCharacters===void 0?{}:{characters:o.RequestCharacters}}}},decode:vy},Ao=new Set(["region","profile","languageCode","sampleRate","voiceId","engine"]),_y={safeParse(e){let t=typeof e==="object"&&e!==null?e:{},n=(i)=>({success:!1,error:{issues:[{message:i}]}}),r=Object.keys(t).find((i)=>!Ao.has(i));if(r!==void 0)return n(`unknown option "${r}" (takes ${[...Ao].join(", ")})`);if(typeof t.region!=="string"||t.region==="")return n("region is required, e.g. eu-west-2");if(t.sampleRate!==void 0&&typeof t.sampleRate!=="number")return n("sampleRate is a number of hertz");for(let i of["voiceId","engine","languageCode"])if(t[i]!==void 0&&typeof t[i]!=="string")return n(`${i} is text, e.g. ${i==="engine"?"neural":i==="voiceId"?"Joanna":"en-GB"}`);return{success:!0,data:t}}};function ky(e){let t=e.split(";")[0]?.trim().toLowerCase()??"";if(t==="audio/ogg"||t==="audio/opus")return"ogg-opus";if(t==="audio/flac"||t==="audio/x-flac")return"flac";return}var Oo=8192;async function*Sy(e){for(let t=0;t<e.byteLength;t+=Oo)yield{AudioEvent:{AudioChunk:e.subarray(t,t+Oo)}}}function Ty(e){let[t,n]=e==="media.transcription"?["voice notes","transcribe:StartStreamTranscription"]:e==="media.speech"?["spoken replies","polly:SynthesizeSpeech"]:["image generation","bedrock:InvokeModel on the image model"];return`This agent's AWS credentials do not allow ${t}. Whoever runs the agent grants ${n} to its AWS role.`}function yr(e,t){if(e instanceof ln){let i=e.code!==void 0&&/^[a-z][a-z0-9_]{1,63}$/.test(e.code)?e.code:void 0;return new Wt({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 Wt({code:"media_provider_refused",message:`AWS refused the request (${n||"error"}): ${r}`,hint:n==="AccessDeniedException"||n==="UnrecognizedClientException"?Ty(t):n==="ValidationException"?"Nova Canvas takes a prompt of at most 1,024 characters and a size whose sides are multiples of 16 between 320 and 4096.":n==="TextLengthExceededException"?"Lower media.speech.maxCharacters; each voice note is one Polly request.":"AWS's own words are above.",field:t})}function wr(e=by){return{optionsSchema:_y,create(t){if(t.options===void 0)throw new Q({code:"media_aws_region_missing",message:`${t.field}.options.region is required for the aws provider.`,hint:"Name the region, e.g. options: { region: eu-west-2 }. Nova Canvas is in us-east-1, eu-west-1 and ap-northeast-1.",field:`${t.field}.options`});let n=t.options,r,i,o;return{async transcribe(c,l){let a=ky(c.mimeType),h=c.bytes;if(a===void 0)try{h=await e.decode(c.bytes,l)}catch(f){let d=f.code==="ENOENT";throw new Wt({code:"media_audio_unsupported",message:d?`Amazon Transcribe streaming cannot read ${c.mimeType}, and ffmpeg, which would convert it, is not installed.`:`${c.mimeType} could not be converted for Amazon Transcribe: ${f instanceof Error?f.message:String(f)}`,hint:d?"Install ffmpeg on the PATH (the container image carries it), or use the openai provider in media.transcription.":"The file is probably not audio, or is damaged. Ogg/Opus and FLAC are sent as they are.",field:`${t.field}.provider`})}r??=e.transcribe(n);try{let d=await(await r)({LanguageCode:n.languageCode??"en-US",MediaEncoding:a??"pcm",MediaSampleRateHertz:a===void 0?No:n.sampleRate??48000,AudioStream:Sy(h)},l),u=[],p;for await(let m of d)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 Wt)throw f;throw yr(f,t.field)}},async synthesize(c,l){o??=e.speak(n);try{let h=await(await o)({text:c.text,voiceId:n.voiceId??"Joanna",engine:n.engine??"neural",...n.languageCode===void 0?{}:{languageCode:n.languageCode}},l);return{bytes:h.bytes,mimeType:"audio/ogg; codecs=opus",...h.characters===void 0?{}:{characters:h.characters}}}catch(a){throw yr(a,t.field)}},async generateImage(c,l){let[a,h]=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:h}})},l)}catch(p){throw yr(p,t.field)}let d=JSON.parse(f),u=d.images?.[0];if(u===void 0)throw new Wt({code:"media_provider_empty",message:`Nova Canvas returned no image${d.error===void 0?"":`: ${d.error}`}.`,hint:"A prompt its content filter refused comes back this way. Rephrasing it is usually what works.",field:t.field});return{bytes:Buffer.from(u,"base64"),mimeType:"image/png"}}}}}}var $y="0.1.0",Io={name:"media-aws",version:$y,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["transcribestreaming.*.amazonaws.com","bedrock-runtime.*.amazonaws.com","polly.*.amazonaws.com"]}],setup(e){e.defineMediaProvider("aws",wr())}};import{mkdirSync as Ey,readFileSync as Ay,renameSync as Oy,writeFileSync as Ny}from"node:fs";import{dirname as Iy,isAbsolute as Cy,join as Co,resolve as Py}from"node:path";import{mkdirSync as iw,readFileSync as Jo,renameSync as sw,writeFileSync as ow}from"node:fs";import{dirname as aw,isAbsolute as cw,join as Uo,resolve as lw}from"node:path";var dn=1,Po="tools.cache.json";function fn(e){return Cy(e)?Co(e,V.stateDir,Po):Co(Py(e),V.stateDir,Po)}function My(e){return typeof e==="object"&&e!==null&&typeof e.slug==="string"}function Mo(e){let t={version:dn,provider:"composio",fetchedAt:"",baseUrl:"",tools:{}},n;try{n=Ay(fn(e),"utf8")}catch{return t}try{let r=JSON.parse(n);if(typeof r!=="object"||r===null)return t;let i=r;if(i.version!==dn)return t;let o={};for(let[s,c]of Object.entries(i.tools??{}))if(My(c))o[s]=c;return{version:dn,provider:"composio",fetchedAt:typeof i.fetchedAt==="string"?i.fetchedAt:"",baseUrl:typeof i.baseUrl==="string"?i.baseUrl:"",tools:o}}catch{return t}}function Ry(e,t,n,r){let i=fn(e);Ey(Iy(i),{recursive:!0});let o={version:dn,provider:"composio",fetchedAt:r().toISOString(),baseUrl:n,tools:t},s=`${i}.${process.pid}.tmp`;return Ny(s,`${JSON.stringify(o,null,2)}
254
- `,"utf8"),Oy(s,i),i}function Ro(e){return new Q({code:"composio_key_missing",message:`The Composio provider needs an API key, and ${e} is not set.`,hint:`Set ${e} in the environment, or in a .env beside the manifest. Change which variable is read with tools.providers.composio.apiKeyEnv — the manifest holds the variable's name, never the key itself.`,field:"tools.providers.composio.apiKeyEnv"})}function Ly(e,t,n){return new Q({code:"composio_schema_unsupported",message:`The Composio tool "${e}" declares "${n}" at ${t}, which this runtime's schema subset cannot express.`,hint:"Refused rather than dropped: that keyword decides which argument documents are valid, so ignoring it would hand the model a schema the endpoint disagrees with. Unpin this tool, or pin a sibling action with a flatter schema. Value constraints such as minimum and format are not affected — those are carried in the field's description.",field:"tools.pinned"})}function xy(e,t){return new Q({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 st(e,t){return new b({code:"composio_request_failed",message:`Composio answered ${e}: ${t}`,hint:e===401||e===403?"The API key was rejected. Check the value of the variable named by tools.providers.composio.apiKeyEnv — a key that works in the dashboard can still be scoped to a different project.":e===404?"The tool slug does not exist at this API version. Slugs are case-sensitive and shaped like GMAIL_SEND_EMAIL; check it against the toolkit listing.":"Transient at this status. The runtime retries the refresh after readiness and keeps serving the cached catalogue meanwhile, so an agent already running is unaffected."})}function Dy(e,t,n){return new b({code:"composio_execute_failed",message:`Composio could not run "${e}" (${t}): ${n}`,hint:"This is the tool's own failure, not a routing one — the arguments reached Composio and it refused them. A value constraint is the usual cause: this runtime carries minimum, format and pattern in the field description for the model to read, but does not enforce them locally, so an out-of-range value arrives here rather than as a repairable field error."})}function jy(e,t){return new b({code:"composio_not_connected",message:`"${e}" needs a connected ${t} account and none was found.`,hint:`Connect ${t} for this user in Composio, then set tools.providers.composio.userId to the same identifier. The tool resolves at load whether or not an account exists, because resolution reads a schema and execution needs the account — so this surfaces on first use rather than at boot.`})}function Lo(e){return new b({code:"composio_session_key_missing",message:`Searching your apps needs a Composio key, and ${e} is not set.`,hint:`Put the key in the .env beside this agent's manifest as ${e}=…, then restart. Get one from the Composio dashboard — the free tier is enough to connect an account and search the catalogue.`})}function xo(e){return new b({code:"composio_no_match",message:`No tool matched "${e}".`,hint:'Describe the action and its object in plain English — "send an email", "create a calendar event", "post a message to a channel" — rather than naming a product or a tool slug. Composio matches on the use case, not on its own names.'})}var Uy="https://backend.composio.dev/api/v3";function Do(e){return/\/v3$/.test(e)?e.replace(/\/v3$/,"/v3.1"):e}var zy=100;function ot(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=ot(ot(t)?.error),r=typeof n?.message==="string"?n.message:void 0,i=typeof n?.suggested_fix==="string"?n.suggested_fix:void 0;if(r===void 0)return e.statusText===""?"no detail":e.statusText;return i===void 0||i===""?r:`${r} — ${i}`}class Bo{#e;#n;#t;constructor(e){this.#e=e.apiKey,this.#n=go(e.baseUrl??Uy),this.#t=e.fetch??((t,n)=>globalThis.fetch(t,n))}#r(e,t){return this.#t(`${this.#n}${e}`,{method:"GET",headers:{"x-api-key":this.#e,accept:"application/json"},...t===void 0?{}:{signal:t}})}async#o(e,t){let n=await this.#r(e,t);if(!n.ok)throw st(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 st(n.status,await vt(n));let r=ot(await n.json());return typeof r?.slug==="string"?r:void 0}async slugs(e){let t=[],n;for(let r=0;r<400;r+=1){let i=new URLSearchParams({limit:String(zy)});if(n!==void 0)i.set("cursor",n);let o=await this.#o(`/tools?${i.toString()}`,e);for(let c of o.items??[])if(typeof c.slug==="string")t.push(c.slug);let s=o.next_cursor;if(s===null||s===void 0||s===""||s===n)break;n=s}return t}async execute(e,t,n,r){let i=await this.#i(`${this.#n}/tools/execute/${encodeURIComponent(e)}`,{user_id:n,arguments:t},r);if(!i.ok)throw st(i.status,await vt(i));let o=ot(await i.json())??{},s=o.successful!==!1,c=typeof o.error==="string"&&o.error!==""?o.error:void 0;return{ok:s,data:o.data??o,...c===void 0?{}:{error:c}}}#i(e,t,n){return this.#t(e,{method:"POST",headers:{"x-api-key":this.#e,"content-type":"application/json",accept:"application/json"},body:JSON.stringify(t),...n===void 0?{}:{signal:n}})}async createSession(e,t){let n=await this.#i(`${Do(this.#n)}/tool_router/session`,{user_id:e},t);if(!n.ok)throw st(n.status,await vt(n));let r=ot(await n.json())??{},i=r.session_id;if(typeof i!=="string"||i==="")throw st(n.status,"no session_id in the response body");return r}async executeMeta(e,t,n,r){let i=await this.#i(`${Do(this.#n)}/tool_router/session/${encodeURIComponent(e)}/execute_meta`,{slug:t,arguments:n},r);if(i.status===404)return{notFound:!0};if(!i.ok)throw st(i.status,await vt(i));let o=ot(await i.json())??{},s=typeof o.error==="string"&&o.error!==""?o.error:void 0;return{ok:o.successful===void 0?s===void 0:o.successful!==!1,data:o.data??o,...s===void 0?{}:{error:s}}}}function Fy(e){return io(e.input_parameters,{unsupported:(t,n)=>Ly(e.slug,t,n),rootPath:"input_parameters"})}function br(e){let t=new Set(e.tags??[]);if(t.has("destructiveHint"))return!0;return!t.has("readOnlyHint")}function Ko(e){let t=new Set(e.tags??[]);return!t.has("readOnlyHint")&&!t.has("destructiveHint")}function By(e){let t=e.replace(/\s+/g," ").trim(),n=t.search(/\.\s|\.$/);return n===-1?t:t.slice(0,n+1)}function qo(e){let t=(e.description??e.human_description??"").trim(),n=t===""?`The ${e.slug} tool.`:By(t),r=e.toolkit?.slug;return{slug:e.slug,provider:"composio",summary:n,whenToUse:t===""?`the task needs ${e.slug}`:t,mutating:br(e),tags:[...r===void 0?[]:[r],...br(e)?["write"]:["read"]],parameters:Fy(e)}}var Ky=8,jo=100,hn="composio_search",pn="composio_connect",Sr="composio_workbench",qy=[hn,pn,Sr];function Ue(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function _r(e){return Array.isArray(e)?e:[]}function je(e){return typeof e==="string"&&e!==""?e:void 0}function Zy(e){let t=e.replace(/\s+/g," ").trim();return t.length<=jo?t:`${t.slice(0,jo-1)}…`}var Zo={slug:hn,provider:"composio",summary:"Finds tools for connecting to an outside app — email, calendar, chat, issue trackers.",whenToUse:"the person wants this agent to reach one of their other accounts and no pinned tool does it. Describe the action and its object in plain English, like 'send an email' or 'create a "+"calendar event' — never a product name alone and never a tool slug. This finds the tools and "+"records their definitions; it does not run them and does not enable them.",whenNotToUse:"a pinned tool already does the job, or the person asked to read a web page — that is "+"web_fetch. This searches an app catalogue, never the web.",mutating:!1,trust:"untrusted",tags:["composio","read"],parameters:{type:"object",properties:{use_case:{type:"string",description:"What the person wants done, as an action and its object: 'send an email', 'list upcoming calendar events', 'create an issue'. Plain English, one task."}},required:["use_case"]}};function Wy(e){let t=[];for(let n of _r(e.results)){let r=Ue(n);if(r===void 0)continue;for(let i of[r.primary_tool_slugs,r.related_tool_slugs])for(let o of _r(i))if(typeof o==="string"&&!t.includes(o))t.push(o)}return t.slice(0,Ky)}function Jy(e,t){let n=[];for(let r of e){let i=t[r];if(i===void 0)continue;let o=i.description??i.human_description??"",s;try{qo(i)}catch(c){if(!_(c))throw c;s=c.message}n.push({...s===void 0?{}:{unavailable:s},slug:r,summary:o===""?"no description supplied":Zy(o),toolkit:i.toolkit?.slug??"",mutating:br(i),assumed:Ko(i)})}return n}function Hy(e){let t=[];for(let n of _r(e.toolkit_connection_statuses)){let r=Ue(n),i=je(r?.toolkit);if(i===void 0)continue;t.push({toolkit:i,connected:r?.has_active_connection===!0})}return t}function Vy(e,t,n){let r=[`Tools that can "${e}":`,""];for(let s of t){if(s.unavailable!==void 0){r.push(` n/a ${s.slug}`),r.push(` unavailable — do not pin it: ${s.unavailable}`);continue}r.push(` ${s.mutating?"write":"read "} ${s.slug}`),r.push(` ${s.summary}`)}if(t.some((s)=>s.assumed))r.push(""),r.push("Some of those are marked write because they say nothing either way, not because they are known to change things. Composio leaves a third of its catalogue unannotated and the safe reading is the one taken here.");let i=n.filter((s)=>!s.connected).map((s)=>s.toolkit),o=n.filter((s)=>s.connected).map((s)=>s.toolkit);if(r.push(""),o.length>0)r.push(`Already connected: ${o.join(", ")}.`);if(i.length>0)r.push(`Not connected yet: ${i.join(", ")}. Call composio_connect for each before these tools can run.`);if(r.push(""),r.push("These are not enabled yet. To enable them, add the slugs you need to tools.pinned with "+"config_set — their definitions are already saved, so no other setup is needed. "+"config_set says which become usable in this conversation; the rest work from the person's next message, with no restart. Pin only what the task needs."),t.some((s)=>s.unavailable!==void 0))r.push("Those marked n/a cannot be loaded by this runtime as Composio describes them today; a pinned one is left out with a warning. Choose another tool, or tell the person it is unavailable.");return r.join(`
255
- `)}function Gy(e){return{spec:Zo,handler:async(t,n)=>{let r=String(t.use_case??"").trim(),i=await e.call("COMPOSIO_SEARCH_TOOLS",{queries:[{use_case:r}],session:{generate_id:!0}},n.signal);if(!i.ok)return`The search failed: ${i.error??"no detail supplied"}`;let o=Ue(i.data)??{},s=Wy(o);if(s.length===0)throw xo(r);let c=await e.fetchSchemas(s,n.signal),l=Jy(s,c);if(l.length===0)throw xo(r);return Vy(r,l,Hy(o))}}}var Wo={slug:pn,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 kr(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(Ue(e)??{})){let r=kr(n,t+1);if(r!==void 0)return r}return}function Yy(e,t){let n=Ue(Ue(t.results)?.[e]),r=je(n?.status)?.toLowerCase(),i=je(n?.redirect_url)??kr(t.results)??kr(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})`}. ${je(t.message)??"No detail was supplied."}`;return[`To connect ${e}, the person needs to open this and sign in:`,"",` ${i}`,"","Give them that address and stop — this agent cannot complete a sign-in on their behalf, and "+"the connection is not usable until they have. When they say it is done, the account stays connected for future sessions with no further sign-in."].join(`
256
- `)}function Xy(e){return{spec:Wo,handler:async(t,n)=>{let r=String(t.toolkit??"").trim().toLowerCase(),i=await e.call("COMPOSIO_MANAGE_CONNECTIONS",{toolkits:[r]},n.signal);if(!i.ok)return`Could not start the connection for ${r}: ${i.error??"no detail supplied"}`;return Yy(r,Ue(i.data)??{})}}}var Qy={slug:Sr,provider:"composio",summary:"Runs Python in a Composio-hosted sandbox, for reshaping large tool output.",whenToUse:"a tool returned more data than is worth reading in full and it needs filtering, counting or reshaping first. The sandbox keeps its files and variables for the rest of the task.",whenNotToUse:"the work belongs on this machine — that is exec, which the permission rules can actually "+"constrain. This runs somewhere else, under no rule written here.",mutating:!0,trust:"untrusted",tags:["composio","write"],parameters:{type:"object",properties:{code:{type:"string",description:"Python to run in the sandbox. Print what should come back."}},required:["code"]}},ew="code_to_execute";function tw(e){let t=Ue(e);if(t===void 0)return typeof e==="string"?e:JSON.stringify(e,null,2);let n=[],r=je(t.stdout),i=je(t.stderr),o=je(t.error),s=je(t.results);if(r!==void 0)n.push(r.trimEnd());if(s!==void 0)n.push(s.trimEnd());if(i!==void 0)n.push(`stderr:
257
- ${i.trimEnd()}`);if(o!==void 0)n.push(`error:
258
- ${o.trimEnd()}`);return n.length===0?"The code ran and printed nothing.":n.join(`
259
- `)}function nw(e){return{spec:Qy,handler:async(t,n)=>{let r=await e.call("COMPOSIO_REMOTE_WORKBENCH",{[ew]:String(t.code??"")},n.signal);if(!r.ok)return`The workbench failed: ${r.error??"no detail supplied"}`;return tw(r.data)}}}function rw(e){return{[hn]:Gy(e),[pn]:Xy(e),[Sr]:nw(e)}}var zo="composio.session.json";function Ho(e){return cw(e)?Uo(e,V.stateDir,zo):Uo(lw(e),V.stateDir,zo)}function uw(e,t){let n;try{n=Jo(Ho(e),"utf8")}catch{return}try{let i=JSON.parse(n)?.sessions;if(typeof i!=="object"||i===null)return;let o=i[t];return typeof o==="string"&&o!==""?o:void 0}catch{return}}function dw(e,t,n){let r=Ho(e);iw(aw(r),{recursive:!0});let i={};try{let l=JSON.parse(Jo(r,"utf8"))?.sessions;if(typeof l==="object"&&l!==null){for(let[a,h]of Object.entries(l))if(typeof h==="string")i[a]=h}}catch{i={}}let o={sessions:{...i,[t]:n}},s=`${r}.${process.pid}.tmp`;return ow(s,`${JSON.stringify(o,null,2)}
260
- `,"utf8"),sw(s,r),r}var fw="COMPOSIO_API_KEY";class Vo{id="composio";#e;#n;#t;#r;#o;#i;#a;#s;#c;#l=[];#u=[];#d;constructor(e){this.#e=e.dir,this.#n=e.userId??"default",this.#t=e.now??(()=>new Date),this.#i=e.apiKeyEnv??fw,this.#a=e.personal??!0;let t=e.env[this.#i];this.#r=e.baseUrl??"https://backend.composio.dev/api/v3",this.#o=t===void 0||t===""?void 0:new Bo({apiKey:t,baseUrl:this.#r,...e.fetch===void 0?{}:{fetch:e.fetch}});let n=Mo(this.#e);this.#s=n.tools,this.#c=n.fetchedAt}async resolve(e){let t=[],n=[],r=[],i=rw(this.#p());for(let o of e){let s=i[o];if(s!==void 0){t.push(s);continue}let c=this.#s[o];if(c===void 0)continue;let l;try{l=qo(c)}catch(a){if(!_(a))throw a;r.push({slug:o,detail:a.toDetail()});continue}if(Ko(c))n.push(o);t.push(this.#h(l))}if(this.#l=n,this.#u=r,!this.#a)return t;return t.map((o)=>({...o,spec:{...o.spec,personal:!0}}))}refused(){return this.#u}async list(){return[...qy,...Object.keys(this.#s)]}async available(){return[{slug:hn,summary:Zo.summary},{slug:pn,summary:Wo.summary}]}uncached(e){return e.filter((t)=>this.#s[t]===void 0)}explainUnresolved(e){if(Object.keys(this.#s).length>0||e.length===0)return;return xy(e,fn(this.#e))}describe(){return{cached:Object.keys(this.#s).length,fetchedAt:this.#c,cachePath:fn(this.#e),assumedMutating:this.#l}}async refresh(e,t){let n=this.#o;if(n===void 0)throw Ro(this.#i);let r={},i=[],o=[];for(let c of e){let l=await n.tool(c,t);if(l===void 0){i.push(c);continue}r[c]=l;let a=this.#s[c];if(a===void 0||JSON.stringify(a)!==JSON.stringify(l))o.push(c)}this.#s={...this.#s,...r};let s=Ry(this.#e,this.#s,this.#r,this.#t);return this.#c=Mo(this.#e).fetchedAt,{fetched:Object.keys(r).length,missing:i,changed:o,cachePath:s}}async#f(e,t=!1){let n=this.#o;if(n===void 0)throw Lo(this.#i);if(!t){let i=this.#d??uw(this.#e,this.#n);if(i!==void 0)return this.#d=i,i}let r=await n.createSession(this.#n,e);return this.#d=r.session_id,dw(this.#e,this.#n,r.session_id),r.session_id}#p(){return{call:async(e,t,n)=>{let r=this.#o;if(r===void 0)throw Lo(this.#i);let i=await this.#f(n),o=await r.executeMeta(i,e,t,n);if("notFound"in o){i=await this.#f(n,!0);let s=await r.executeMeta(i,e,t,n);if("notFound"in s)return{ok:!1,data:{},error:"the session could not be opened"};o=s}return o},fetchSchemas:async(e,t)=>{await this.refresh(e,t);let n={};for(let r of e){let i=this.#s[r];if(i!==void 0)n[r]=i}return n}}}#h(e){return{spec:e,handler:async(t,n)=>{let r=this.#o;if(r===void 0)throw Ro(this.#i);let i=await r.execute(e.slug,t,this.#n,n.signal);if(!i.ok){let o=i.error??"no detail supplied";if(/connected account|not connected|no connection/i.test(o)){let s=e.tags[0]??"the toolkit";throw jy(e.slug,s)}throw Dy(e.slug,200,o)}return typeof i.data==="string"?i.data:JSON.stringify(i.data,null,2)}}}}var Fo=["apiKeyEnv","userId","baseUrl","personal"];function vr(e,t){let n=e[t];if(n===void 0)return;if(typeof n!=="string"||n==="")throw new Q({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 Tr(e){let t=Object.keys(e.config).filter((s)=>!Fo.includes(s));if(t.length>0)throw new Q({code:"composio_config_unknown",message:`tools.providers.composio has ${t.length===1?"a key":"keys"} the Composio provider does not read: ${t.join(", ")}.`,hint:`Accepted keys are ${Fo.join(", ")}. Refused rather than ignored, because a setting that looks applied and is not is worse than a rejected manifest.`,field:"tools.providers.composio"});let n=vr(e.config,"apiKeyEnv"),r=vr(e.config,"userId"),i=vr(e.config,"baseUrl"),o=e.config.personal;if(o!==void 0&&typeof o!=="boolean")throw new Q({code:"composio_config_invalid",message:"tools.providers.composio.personal must be true or false.",hint:"Leave it out to keep the default, true: every tool acts as the agent's owner. Write false only for a Composio entity a whole team shares on purpose.",field:"tools.providers.composio.personal"});return new Vo({dir:e.dir,env:e.env,...n===void 0?{}:{apiKeyEnv:n},...r===void 0?{}:{userId:r},...i===void 0?{}:{baseUrl:i},...o===void 0?{}:{personal:o}})}var hw="0.1.0",Go={name:"composio",version:hw,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["backend.composio.dev"]},{kind:"env",vars:["COMPOSIO_API_KEY"]},{kind:"fs",paths:["<state>/composio"],mode:"write"}],setup(e){e.defineToolProvider("composio",Tr)}};import{mkdirSync as pw,readFileSync as mw,renameSync as gw,writeFileSync as yw}from"node:fs";import{dirname as ww,join as vw,resolve as bw}from"node:path";var na=1;function Er(e){return vw(bw(e),V.stateDir,"mcp.cache.json")}function _w(e){try{let t=JSON.parse(mw(Er(e),"utf8"));if(t.version!==na||typeof t.servers!=="object")return{};let n={};for(let[r,i]of Object.entries(t.servers??{}))if(typeof i?.url==="string"&&Array.isArray(i.tools))n[r]=i;return n}catch{return{}}}function kw(e,t){let n=Er(e);pw(ww(n),{recursive:!0});let r=`${n}.partial`;return yw(r,`${JSON.stringify({version:na,servers:t},null,2)}
261
- `),gw(r,n),n}var ra="tools.providers.mcp";function we(e,t,n=ra){return new Q({code:"mcp_config_invalid",message:e,hint:t,field:n})}function Sw(e,t,n){return new Q({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 Tw(e,t,n){return new b({code:"mcp_header_env_missing",message:`The MCP server "${e}" needs the ${t} header from ${n}, which is not set.`,hint:`Set ${n} in the environment or in the .env beside the manifest. The manifest names the variable (${ra}.servers.${e}.headersEnv), never the value.`})}function ia(e,t,n){return new b({code:"mcp_request_failed",message:`The MCP server "${e}" at ${t} did not answer: ${n}`,hint:"Check the server is running and reachable from this host (a loopback URL means the same machine or pod). If it needs a token, headersEnv names the variable that holds it. An agent keeps serving the tools it cached; only calls fail while the server is down."})}function $w(e,t,n){return new b({code:"mcp_tool_failed",message:`The MCP tool "${t}" on "${e}" reported an error: ${n}`,hint:"The server's own words above say what went wrong. If they say the failure is temporary, retry up to twice. Otherwise a tool outside the server's allowlist, a missing upstream credential or an invalid argument are the usual causes, and retrying the same call will not fix those."})}var Yo="2025-06-18";class sa{#e;#n;#t;#r;#o=1;constructor(e){this.#e=e,this.#n=e.fetch??((t,n)=>fetch(t,n))}async listTools(e){let t=[],n;for(let r=0;r<100;r+=1){let i=await this.#i("tools/list",n===void 0?{}:{cursor:n},{},e);for(let o of i.tools??[])if(typeof o?.name==="string")t.push(o);if(n=i.nextCursor,n===void 0||n==="")return t}return t}async callTool(e,t,n,r){return await this.#i("tools/call",{name:e,arguments:t},n,r)}async#i(e,t,n,r){await this.#a(r);let i=await this.#c(e,t,n,r);if(i.status!==404||this.#t===void 0)return this.#u(i,e);return this.#t=void 0,await this.#a(r),this.#u(await this.#c(e,t,n,r),e)}#a(e){if(this.#t!==void 0)return Promise.resolve();return this.#r??=this.#s(e).finally(()=>{this.#r=void 0}),this.#r}async#s(e){let t=await this.#c("initialize",{protocolVersion:Yo,capabilities:{},clientInfo:{name: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":Yo,...this.#t===void 0||this.#t===""?{}:{"mcp-session-id":this.#t},...this.#e.headers(),...t},body:JSON.stringify(e),signal:n===void 0?r:AbortSignal.any([n,r])})}catch(i){throw this.#d(r.aborted?`no response within ${this.#e.timeoutMs} ms`:i instanceof Error?i.message:String(i))}}async#u(e,t){let n=await e.text();if(!e.ok)throw this.#d(`${t} answered ${e.status}: ${n.slice(0,300)}`);let i=(e.headers.get("content-type")??"").includes("text/event-stream")?Ew(n):[n];for(let o of i){let s;try{s=JSON.parse(o)}catch{continue}if(s.error!==void 0)throw this.#d(`${t} failed (${s.error.code??"?"}): ${s.error.message??"no message"}`);if(s.result!==void 0)return s.result}throw this.#d(`${t} returned no JSON-RPC result`)}#d(e){return ia(this.#e.server,this.#e.url,e)}}function Ew(e){let t=[];for(let n of e.split(/\r?\n\r?\n/)){let r=n.split(/\r?\n/).filter((i)=>i.startsWith("data:")).map((i)=>i.slice(5).replace(/^ /,""));if(r.length>0)t.push(r.join(`
262
- `))}return t}var mn="__";function bt(e,t){return`${e}${mn}${t.replace(/[^A-Za-z0-9_-]/g,"_")}`}function Aw(e){let t=e.annotations;return t?.readOnlyHint!==!0||t.destructiveHint===!0}function Ow(e){let t=e.replace(/\s+/g," ").trim(),n=t.search(/\.\s|\.$/);return n===-1?t:t.slice(0,n+1)}function oa(e,t){let n=(t.description??t.title??"").trim();return n===""?`The ${t.name} tool on ${e}.`:Ow(n)}function Nw(e,t,n){let r=bt(e,t.name),i=(t.description??t.title??"").trim(),o=Aw(t);return{slug:r,provider:"mcp",summary:oa(e,t),whenToUse:i===""?`the task needs ${t.name} from ${e}`:i,mutating:o,tags:[e,o?"write":"read"],...n===void 0?{}:{policyArg:n},parameters:io(t.inputSchema,{untyped:"object",rootPath:"inputSchema",unsupported:(s,c)=>we(`The MCP tool "${r}" declares "${c}" at ${s}, which this runtime's schema subset cannot express.`,"Refused rather than dropped: that keyword decides which arguments are valid, so ignoring it would hand the model a schema the server disagrees with. Unpin this tool, or ask the server for a flatter one.","tools.pinned")})}}var Xo=["url","headersEnv","participantHeader","turnHeader","policyArgs","timeoutMs","personal"],Qo=30000,Iw=40;function $r(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ea(e,t,n){if(e===void 0)return{};let r=$r(e),i=r===void 0?void 0:Object.entries(r),o=i?.every(([,s])=>typeof s==="string"&&(n===void 0||n.test(s)));if(i===void 0||o!==!0)throw we(`${t} must map names to ${n===void 0?"strings":"environment variable names"}.`,n===void 0?"Write it as a map, e.g. { invoke_tool: toolName }.":"Write it as { Authorization: TRACKER_MCP_TOKEN }: the header name, then the variable holding its value. A value never goes in the manifest.",t);return Object.fromEntries(i)}function Cw(e){let t=Object.keys(e).filter((r)=>r!=="servers");if(t.length>0)throw we(`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=$r(e.servers);if(n===void 0||Object.keys(n).length===0)throw we("tools.providers.mcp names no servers.","Add servers.<name>.url, e.g. servers: { tracker: { url: http://127.0.0.1:3000/mcp } }.","tools.providers.mcp.servers");return Object.entries(n).map(([r,i])=>{let o=`tools.providers.mcp.servers.${r}`;if(!/^[a-z][a-z0-9-]{0,23}$/.test(r))throw we(`The MCP server name "${r}" is not usable in a tool slug.`,"Use lowercase letters, digits and hyphens, starting with a letter, at most 24 characters. It prefixes every tool: tracker → tracker__search_tools.",o);let s=$r(i)??{},c=Object.keys(s).filter((d)=>!Xo.includes(d));if(c.length>0)throw we(`${o} has keys the MCP provider does not read: ${c.join(", ")}.`,`Accepted keys are ${Xo.join(", ")}.`,o);let l;try{l=new URL(String(s.url))}catch{throw we(`${o}.url is not a URL.`,"Give the server's Streamable HTTP endpoint, e.g. http://127.0.0.1:3000/mcp.",`${o}.url`)}if(l.protocol!=="http:"&&l.protocol!=="https:")throw we(`${o}.url is ${l.protocol} — only HTTP servers are supported.`,"Streamable HTTP is the one transport this provider speaks. A stdio server needs an HTTP front (most servers have an MCP_TRANSPORT=http mode).",`${o}.url`);if(l.username!==""||l.password!=="")throw we(`${o}.url carries a credential.`,"A manifest never holds a secret. Put it in an env var and name it in headersEnv, e.g. { Authorization: TRACKER_MCP_TOKEN }.",`${o}.url`);let a=s.timeoutMs===void 0?Qo:s.timeoutMs;if(typeof a!=="number"||!Number.isInteger(a)||a<=0)throw we(`${o}.timeoutMs must be a positive whole number of milliseconds.`,`Omit it for ${Qo} ms.`,`${o}.timeoutMs`);let h=s.participantHeader;if(h!==void 0&&typeof h!=="string")throw we(`${o}.participantHeader must be a header name.`,"e.g. X-Acting-Participant. Each call then carries the id of the person the turn acts for, and none on a schedule or peer-agent turn.",`${o}.participantHeader`);let f=s.turnHeader;if(f!==void 0&&(typeof f!=="string"||!/^[A-Za-z0-9-]+$/.test(f)))throw we(`${o}.turnHeader must be a header name.`,"e.g. X-Dispach-Turn. Each call then carries the turn id there, and the call id in <name>-Call.",`${o}.turnHeader`);if(s.personal!==void 0&&typeof s.personal!=="boolean")throw we(`${o}.personal must be true or false.`,"true when the server acts as the agent's owner (their mailbox, their account), so only the owner's turns get its tools.",`${o}.personal`);return{name:r,url:l.toString(),...s.personal===!0?{personal:!0}:{},...f===void 0?{}:{turnHeader:f},headersEnv:ea(s.headersEnv,`${o}.headersEnv`,/^[A-Za-z_][A-Za-z0-9_]*$/),...h===void 0?{}:{participantHeader:h},policyArgs:ea(s.policyArgs,`${o}.policyArgs`),timeoutMs:a}})}function ta(e){let t=(e.content??[]).map((n)=>n.type==="text"&&typeof n.text==="string"?n.text:`[${n.type} content omitted]`);if(t.length>0)return t.join(`
263
- `);return e.structuredContent===void 0?"(no content)":JSON.stringify(e.structuredContent,null,2)}class aa{id="mcp";#e;#n;#t;#r;#o=new Map;#i;constructor(e){this.#e=e.dir,this.#n=e.env,this.#t=new Map(e.servers.map((t)=>[t.name,t])),this.#r=e.fetch,this.#i=_w(e.dir)}#a(e){let t=this.#i[e.name];return t===void 0||t.url!==e.url?void 0:t.tools}async resolve(e){let t=[],n=[];for(let r of this.#t.values())for(let i of this.#a(r)??[]){let o=bt(r.name,i.name);if(!e.includes(o))continue;try{t.push(this.#l(r,i))}catch(s){if(!_(s))throw s;n.push({slug:o,detail:s.toDetail()})}}return this.#s=n,t}refused(){return this.#s}#s=[];async list(){return[...this.#t.values()].flatMap((e)=>(this.#a(e)??[]).map((t)=>bt(e.name,t.name)))}async available(){let e=[];for(let t of this.#t.values())for(let n of this.#a(t)??[]){if(e.length>=Iw)return e;e.push({slug:bt(t.name,n.name),summary:oa(t.name,n)})}return e}explainUnresolved(e){let t=new Set,n=[];for(let r of e){let i=this.#t.get(r.split(mn)[0]??"");if(i===void 0||!r.includes(mn))continue;if(this.#a(i)!==void 0)continue;t.add(i.name),n.push(r)}return n.length===0?void 0:Sw([...t],n,Er(this.#e))}async refresh(e,t){let n={...this.#i},r=[],i=[],o=0;for(let l of this.#t.values())try{let a=await this.#c(l).listTools(t),h=new Map((this.#a(l)??[]).map((f)=>[f.name,JSON.stringify(f)]));for(let f of a){let d=bt(l.name,f.name);if(!e.includes(d))continue;if(o+=1,h.get(f.name)!==JSON.stringify(f))i.push(d)}n[l.name]={url:l.url,fetchedAt:new Date().toISOString(),tools:a}}catch(a){r.push({server:l,detail:a instanceof Error?a.message:String(a)})}if(this.#i=n,kw(this.#e,n),r.length>0)throw ia(r.map((l)=>l.server.name).join(", "),r.map((l)=>l.server.url).join(", "),r.map((l)=>l.detail).join("; "));let s=new Set(await this.list()),c=e.filter((l)=>this.#t.has(l.split(mn)[0]??"")&&!s.has(l));return{fetched:o,missing:c,changed:i}}#c(e){let t=this.#o.get(e.name);if(t===void 0)t=new sa({server:e.name,url:e.url,timeoutMs:e.timeoutMs,...this.#r===void 0?{}:{fetch:this.#r},headers:()=>{let n={};for(let[r,i]of Object.entries(e.headersEnv)){let o=this.#n[i];if(o===void 0||o==="")throw Tw(e.name,r,i);n[r]=o}return n}}),this.#o.set(e.name,t);return t}#l(e,t){return{spec:{...Nw(e.name,t,e.policyArgs[t.name]),...e.personal===!0?{personal:!0}:{}},handler:async(n,r)=>{let i=r.actingParticipant,o={...e.participantHeader===void 0||i==null?{}:{[e.participantHeader]:i.id},...e.turnHeader===void 0?{}:{[e.turnHeader]:r.turnId,...r.callId===void 0?{}:{[`${e.turnHeader}-Call`]:r.callId}}},s=await this.#c(e).callTool(t.name,n,o,r.signal);if(s.isError===!0)throw $w(e.name,t.name,ta(s));return ta(s)}}}}function Ar(e,t){return new aa({dir:e.dir,env:e.env,servers:Cw(e.config),...t===void 0?{}:{fetch:t}})}var Pw="0.1.0",ca={name:"mcp",version:Pw,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["<tools.providers.mcp.servers.*.url>"]},{kind:"fs",paths:["<state>/mcp.cache.json"],mode:"write"}],setup(e){e.defineToolProvider("mcp",(t)=>Ar(t))}};import{readFile as Mw}from"node:fs/promises";import{join as Rw}from"node:path";import{tmpdir as Yw}from"node:os";import{join as Xw}from"node:path";import{mkdir as hv,realpath as pv,rm as pa,stat as mv}from"node:fs/promises";import{isAbsolute as gv,resolve as Pr}from"node:path";import{open as Ma}from"node:fs/promises";import{existsSync as kv,realpathSync as Sv}from"node:fs";import{homedir as ga}from"node:os";import{isAbsolute as La,relative as Tv,resolve as _t,sep as $v}from"node:path";import{spawn as Cv}from"node:child_process";import{open as Pv,readFile as Mv}from"node:fs/promises";import{mkdir as eb,readFile as Fa,realpath as tb,stat as Ba,writeFile as Ka}from"node:fs/promises";import{dirname as nb,isAbsolute as rb,resolve as ba}from"node:path";import{isAbsolute as ib,relative as sb,resolve as ob,sep as qa}from"node:path";import{readFile as yb}from"node:fs/promises";import{readdir as wb}from"node:fs/promises";import{join as vb,relative as bb,sep as Sa}from"node:path";import{statSync as Nb}from"node:fs";import{mkdir as Ib,rm as Oa}from"node:fs/promises";import{delimiter as Cb,join as Cr}from"node:path";function Lw(){return new b({code:"exec_command_empty",message:"exec was called with no command.",hint:"Put the whole shell command in the command field, exactly as it would be typed at a prompt — for example `ls -la` or `npm test`."})}function xw(e,t){return new Q({code:"exec_workdir_missing",message:`The directory to run in does not exist: ${e}`,hint:t?"This is where a previous exec call left the shell, and it has since been removed or renamed. The remembered directory has been cleared, so the next call starts from the agent's own directory; pass workdir to choose a different one.":"workdir must name a directory that already exists. A relative path is resolved against the directory the last exec call ended in, the way a shell would.",field:"workdir"})}function Dw(e,t){return new b({code:"exec_pty_unavailable",message:`A terminal was requested and this machine cannot provide one: ${t}`,hint:`pty: true allocates a terminal with the system \`script\` command, which is missing or unusable on this ${e} host. Refused rather than quietly falling back to a pipe: the fallback would run the command with no terminal while the observation claimed otherwise, and a program that checks isatty() would take the other branch with nothing reporting it. Re-run with pty omitted if the command does not need one.`,field:"pty"})}function la(e,t){return new b({code:"exec_spawn_failed",message:`The shell could not be started for: ${e}`,hint:`The operating system refused before the command ran, so nothing was executed: ${t}. This is a failure of the host rather than of the command — check that /bin/sh exists and that the directory is readable.`})}function jw(){return new b({code:"file_path_empty",message:"A file tool was called with no path.",hint:"Give the path field a value — either absolute, or relative to the current working directory, which is wherever the last exec call left it."})}function Na(e){return new b({code:"file_missing",message:`There is no file at ${e}.`,hint:"Check the path against what glob returns rather than guessing at it. A relative path is resolved against the current working directory, which starts at the agent's own directory and moves when a shell command changes it.",field:"path"})}function Uw(e,t,n){return new b({code:"file_too_large",message:`${e} is ${t} bytes, over the ${n}-byte limit for reading.`,hint:"Use grep to find the part that matters and read around it with offset and limit, rather than pulling the whole file into the conversation.",field:"path"})}function zw(e,t){return new b({code:"file_is_binary",message:`${e} is not a text file (${t} bytes).`,hint:"Refused rather than decoded: a binary rendered as text is thousands of meaningless tokens and no information. If something about the file is needed — its type, its size, what it contains — a shell command that inspects it will answer better.",field:"path"})}function Fw(e,t){return new b({code:"file_secret",message:`Refused to read ${e}: ${t}.`,hint:"Credentials are never read into a conversation. If a task needs a key, it is configured by name in the manifest and the tool that needs it reads it; ask the person rather than looking for the value."})}function Bw(e,t){return new b({code:"file_protected",message:`${e} cannot be written: ${t}.`,hint:"This is a standing rule and no permission setting overrides it — a rule that authorised writing to the agent's own definition would be a rule authorising its own replacement. Say what change was wanted and let the person make it themselves.",field:"path"})}function Kw(e,t){let n=t.length>120?`${t.slice(0,120)}…`:t;return new b({code:"file_edit_no_match",message:`That text does not appear in ${e}: ${JSON.stringify(n)}`,hint:"The match is exact, including indentation and line breaks. Read the file and copy the text out of it rather than reconstructing it from memory — nothing was changed, so the file is still as it was.",field:"find"})}function qw(e,t){return new b({code:"file_edit_ambiguous",message:`That text appears ${t} times in ${e}, so it does not identify one place.`,hint:"Nothing was changed: picking one of several matches would be a guess, and a wrong guess reports success while editing the wrong line. Include a surrounding line or two to make it unique, or pass all: true if every occurrence should change.",field:"find"})}function Zw(e,t){return new b({code:"grep_pattern_invalid",message:`That is not a valid regular expression: ${e}`,hint:`${t}. Refused rather than searched literally — a literalised pattern finds nothing and returns an empty result, which reads as "it is not there" instead of "the pattern was wrong". Escape any regex character meant literally, such as a dot or a bracket.`,field:"pattern"})}function Ww(e,t){return new b({code:"file_outside_root",message:`${e} is outside the directories this agent may change.`,hint:`Writable: ${t.join(", ")}. Everything else is read-only by default — an agent that has misunderstood a request cannot damage anything while misunderstanding it. To work somewhere else, the person you work for adds it to tools.providerConfig.writeRoots in agent.yaml; nothing said in a conversation can add one. Reading outside these directories is allowed and unaffected.`,field:"path"})}function Jw(e,t){return new b({code:"file_read_outside_root",message:`${e} is outside the directories this agent may read.`,hint:`Readable: ${t.join(", ")}. Reads are confined on this agent (tools.providers.system.confineReads), so other agents' files and the rest of the machine are out of reach. A person can add a directory with writeRoots; nothing said in a conversation can.`,field:"path"})}function Ia(e,t){return new b({code:"config_read_failed",message:`This agent's configuration could not be read from ${e}.`,hint:`${t}. The agent is running, so the file existed at boot — it has been moved or its permissions have changed since.`})}function Hw(e,t){return new b({code:"config_path_unknown",message:`"${e}" is not a setting config_set will change.`,hint:`Settable: ${t.join(", ")}. Deliberately a list rather than anything the schema accepts: a tool that can write any field can write the ones that decide what it is allowed to do, and the list is where that judgement lives. Call config_read with no path to see each one explained.`,field:"path"})}function Vw(e,t){return new b({code:"config_value_unreadable",message:`That value could not be read: ${JSON.stringify(e)}`,hint:`${t}. Write it the way it would appear in the file — a bare word, a number, or a list as ["a", "b"]. Refused rather than guessed at, because guessing is how tools.pinned becomes a list of single characters.`,field:"value"})}function ua(e,t,n){return new b({code:"config_invalid",message:`Setting ${e} to ${JSON.stringify(t)} would produce a configuration that does not load: ${n}`,hint:"Nothing was written, so the agent is unchanged and still starts. An invalid manifest is not a failure that shows up now — it is one that shows up at the next boot, by which time the change looks like it succeeded.",field:"value"})}function da(e,t){return new b({code:"config_refused",message:`${e} cannot be changed from inside a conversation: ${t}.`,hint:"No permission rule overrides this, and asking again will not change it. Every other setting can be changed — including enabling a tool or adding a permission rule, which is what this tool is for. Name the exact line you would have added and let the person put it in themselves.",field:"path"})}function Gw(e){return new b({code:"exec_too_many_background",message:`${e.length} commands are already running in the background, which is the limit.`,hint:`Wait for one to finish, or stop one yourself. Already running: ${e.map((t)=>t.length>60?`${t.slice(0,57)}...`:t).join("; ")}. A command that outruns its timeout is left running rather than discarded, so a loop that starts one per attempt reaches this quickly — which is the point of the limit.`})}var Ce="system";function Lr(){return Xw(Yw(),`${V.slug}-${Ce}`)}var Qw=aA.filter((e)=>e.agentListed),fa="(hidden by the operator)",ev=new Set(["id","api","baseurl","options","apikeyenv"]),tv=new Set(["model","provider","baseurl","options","apikeyenv"]);function Or(e){return e.getIn(["context","modelIdentity"])==="hidden"}function yn(e,t){let n=e.map((r)=>r.toLowerCase());if(n[0]==="model"&&n.slice(2).some((r)=>ev.has(r)))return fa;if(n[0]==="media"&&n[2]!==void 0&&tv.has(n[2]))return fa;if(Array.isArray(t))return t.map((r,i)=>yn([...e,String(i)],r));if(typeof t==="object"&&t!==null)return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,yn([...e,r],i)]));return t}function ha(e,t){let n=e.toLowerCase(),r="who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line",i="where the API listens, and what authenticates it, is not yours to decide — the same reason writeRoots is refused. Enabling it on 127.0.0.1 is settable; binding anywhere reachable is a person's call",o="widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(n.split(".").includes("writeroots"))return"widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";if(n.startsWith("tools.providers")&&ve(t,"writeroots"))return"widening where you may write is not yours to do. Asked to create a file, an agent granted itself the whole home directory and then wrote there — which is what this refusal exists to prevent";let s="what your commands can see of the environment is not yours to widen. The scrub keeps the runtime's credentials out of anything you run; a person lists a variable your commands need",c="where a provider sends its requests, and so its credentials, is not yours to decide. A person sets a provider's baseUrl";if(n.startsWith("tools.providers")&&n.split(".").includes("baseurl"))return c;if(n.startsWith("tools.providers")&&ve(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"&&ve(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")&&ve(t,"confinereads"))return a;let h="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 h;if(n.startsWith("tools.providers")&&ve(t,"personal"))return h;if(n.startsWith("tools.providers")&&n.split(".").includes("env"))return s;if(n.startsWith("tools.providers")&&ve(t,"env"))return s;if(n.split(".").includes("allowfrom"))return"who is allowed to talk to you is not yours to decide. It is the inbound gate, so an agent that could widen it could be talked into widening it by the very message it is reading — put the handle in agent.yaml yourself; a refused message prints the exact line";if(n==="channels"&&ve(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"&&(ve(t,"host")||ve(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 ve(e,t){if(Array.isArray(e))return e.some((n)=>ve(n,t));if(typeof e!=="object"||e===null)return!1;return Object.entries(e).some(([n,r])=>n.toLowerCase()===t||ve(r,t))}function Ca(e){return e.file??Rw(e.agentDir,"agent.yaml")}var nv={slug:"config_read",provider:Ce,summary:"Reads this agent's own configuration and lists what can be changed in it.",whenToUse:"you need to know how you are configured, or what would have to change for you to do something you currently cannot — which tool to enable, which permission rule to add",whenNotToUse:"for anything that is not your own configuration; an ordinary file is file_read. You do not need to read it before every answer, only when the question is about how you are set up",mutating:!1,trust:"trusted",trustReason:"The manifest is the runtime's own file, written and validated by the runtime. Fencing it would put a warning about strangers around the agent's own settings.",policyArg:"path",tags:["read","config"],parameters:{type:"object",properties:{path:{type:"string",description:"A single setting, such as tools.pinned. Omit to see the whole configuration and every setting that can be changed."}}}},rv={slug:"config_set",provider:Ce,summary:"Changes one setting in this agent's own configuration.",whenToUse:"the person asks you to change how you are configured, or asks you to do something that needs a tool or permission you do not have and tells you to go ahead and enable it",whenNotToUse:"on your own initiative. Say what you would change and why, and let them ask — and never to remove a restriction someone set, which is refused anyway. The change takes effect when the agent next starts, not in this conversation",mutating:!0,trust:"trusted",trustReason:"It reports the old and new value of one setting the runtime just validated, and nothing else.",policyArg:"path",tags:["write","config"],parameters:{type:"object",properties:{path:{type:"string",description:"The setting, as a dotted path: tools.pinned, tools.policy.allow, model.main.temperature. config_read with no path lists them."},value:{type:"string",description:'The new value, written the way it would appear in the file: a bare word, a number, or a list as ["a", "b"]. Replaces what is there.'}},required:["path","value"]}};function iv(e){try{return co(e)}catch(t){throw Vw(e,t instanceof Error?t.message:String(t))}}function sv(e){return async(t)=>{let n=Ca(e),r;try{r=await Mw(n,"utf8")}catch(c){throw Ia(n,String(c))}let i=typeof t.path==="string"?t.path.trim():"";if(i!==""){let c=X(r),l=c.getIn(i.split("."),!1);if(l===void 0)return`${i} is not set in this configuration. It can be — see config_read with no path for the full list.`;let a=Ot(l)||Nt(l)?l.toJS(c):l,h=Or(c)?yn(i.split("."),a):a;return`${i}:
264
- ${Bn(h).trimEnd()}`}let o=X(r),s=Qw.map((c)=>{let l=o.getIn(c.path.split("."),!1),a=Ot(l)||Nt(l)?l.toJS(o):l,h=Or(o)?yn(c.path.split("."),a):a,f=h===void 0||h===null?"(not set)":Array.isArray(h)?`[${h.map((u)=>typeof u==="object"&&u!==null?JSON.stringify(u):String(u)).join(", ")}]`:Bn(h).trim(),d=c.toAgent===void 0?c.means:`${c.means}. ${c.toAgent}`;return`- ${c.path} = ${f}
265
- ${d}`}).join(`
266
- `);return[`This agent is ${o.get("name")??o.get("id")}, configured at ${n}.`,"","Settings config_set can change, with their current values:",s,"",...ov(o),"Anything not on this list is not settable from a conversation. A change takes effect when the agent next starts, not in the current conversation.","","Some edits are refused whatever the rules say. Removing a check: replacing tools.policy.deny, or setting tools.untrusted.onMutate to allow. Deciding reach: a writeRoots list anywhere, the system provider's env, any provider's baseUrl or personal flag, a channel's allowFrom, and server.host or server.tokenEnv. Enabling a capability is what a person asks you for; where you may write, who may talk to you, and what address you listen on are theirs — name what you need and why, and let them add it.","",...Or(o)?[]:[`The whole file, comments and all, is at ${n} — read it with file_read if that tool is enabled, or ask the person to open it.`]].join(`
267
- `)}}function ov(e){let t=(r)=>{let i=e.getIn(r,!1),o=Ot(i)||Nt(i)?i.toJS(e):i;if(Array.isArray(o))return o.map(String);return typeof o==="string"&&o!==""?[o]:[]},n=[["context.soul.file",t(["context","soul","file"])],["context.static",t(["context","static"])],["context.files",t(["context","files"])],["context.volatile",t(["context","volatile"])],["context.reminder",t(["context","reminder"])]].filter(([,r])=>r.length>0).map(([r,i])=>`- ${r} = [${i.join(", ")}]`);if(n.length===0)return[];return["Context files (read-only here). These files are loaded into my instructions every turn, under their names, so I never need to read them; volatile ones only in private conversations:",...n,""]}function av(e){return async(t,n)=>{let r=Ca(e),i=typeof t.path==="string"?t.path.trim():"",o=typeof t.value==="string"?t.value:String(t.value??""),s=ha(i);if(s!==void 0)throw da(i,s);if(!Ai.includes(i))throw Hw(i,Ai);let c=iv(o),l=ha(i,c);if(l!==void 0)throw da(i,l);let a;try{a=await Rs({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 Ia(r,String(u.cause??u.message));if(_(u)&&u.code==="manifest_edit_invalid"){let p=u.message.slice(u.message.indexOf(": ")+2);throw ua(i,o,p)}if(_(u))throw ua(i,o,`${u.message} ${u.hint??""}`.trim());throw u}let h=a.before!==void 0,f=i==="tools.pinned"&&Array.isArray(c)&&n.pinTools!==void 0?await n.pinTools(c.map(String)):void 0,d=f===void 0?"The configuration still validates. This takes effect when the agent next starts — nothing in the current conversation changes, so do not try the new tool yet.":f.length>0?`The configuration still validates. Usable now, in this conversation: ${f.join(", ")}. Anything else listed here works from the person's next message, once the agent reloads after this turn.`:"The configuration still validates. The new tools work from the person's next message: the agent reloads once this turn ends, with no restart. Tell them it is ready for their next message; do not try the tool in this turn.";return[`Set ${i} in ${r}.`,h?`It was: ${Bn(a.before).trim()}`:"It was not set before.",`It is now: ${Bn(c).trim()}`,"",d,...cv(a.manifest,c)].join(`
268
- `)}}function cv(e,t){if(!ve(t,"tokenenv")&&!ve(t,"apikeyenv"))return[];let n=new Set;for(let r of e.channels??[]){let i=r.tokenEnv;if(typeof i==="string"&&i!=="")n.add(i)}if(n.size===0)return[];return["",`This will NOT start until ${[...n].join(" and ")} ${n.size===1?"is":"are"} set in the .env beside the manifest — the value is read at boot, and a missing one fails the load rather than the first message. You cannot write that file; it is protected because it holds every secret here. Tell the person the variable name and where it goes.`]}function lv(e){return[{spec:nv,handler:sv(e)},{spec:rv,handler:av(e)}]}var uv=["PATH","HOME","USER","LOGNAME","SHELL","LANG","LANGUAGE","TZ","TERM","TMPDIR"],dv=/^[A-Za-z_][A-Za-z0-9_]*$/;function fv(e){if(e===void 0||e==="inherit")return"inherit";if(e==="scrub")return{scrub:!0,pass:[]};if(Array.isArray(e)&&e.every((t)=>typeof t==="string"&&dv.test(t)))return{scrub:!0,pass:e};throw new Q({code:"system_env_invalid",message:`tools.providers.system.env is ${JSON.stringify(e)}, which is none of inherit, scrub or a list of variable names.`,hint:"Write `env: scrub` to give commands only PATH, HOME, the locale and the like, or `env: [GITHUB_TOKEN]` to scrub and pass those names too. Omit it (or `inherit`) to keep handing commands the whole environment.",field:"tools.providers.system.env"})}function Pa(e,t){if(t==="inherit")return e;let n=new Set([...uv,...t.pass]);return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)||r.startsWith("LC_")))}var yv=6000,wv=3000,ma=1500,vv=new TextDecoder("utf-8");async function Nr(e,t,n){let r=await Ma(e,"r");try{let i=new Uint8Array(n),{bytesRead:o}=await r.read(i,0,n,t);return vv.decode(i.subarray(0,o))}finally{await r.close()}}async function Ra(e){let t=await Ma(e,"r"),n;try{n=(await t.stat()).size}finally{await t.close()}if(n<=yv)return{head:Jt(await Nr(e,0,n)),tail:"",bytes:n,spilled:!1};return{head:Jt(await Nr(e,0,wv)),tail:Jt(await Nr(e,n-ma,ma)),bytes:n,spilled:!0}}function bv(e){return e.replace(/^(?:\^[A-Z?]\s*)+/,"")}function _v(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Ev(e){if(e==="~")return ga();return e.startsWith("~/")?_t(ga(),e.slice(2)):e}var Av="workspace";function Ov(e,t=[],n=!1){let r=_t(e),i=_t(r,Av);return{primary:kv(i)?i:r,extra:t.map((o)=>La(o)?_t(o):_t(r,o)),confineReads:n}}function ya(e){try{return Sv(e)}catch{return e}}function xa(e,t){if(!t.confineReads)return;let n=ya(e);if(kt(t).some((r)=>Da(n,ya(r))))return;throw Jw(e,kt(t))}function Da(e,t){if(e===t)return!0;let n=Tv(t,e);return n!==""&&!n.startsWith(`..${$v}`)&&n!==".."&&!La(n)}function kt(e){return[e.primary,...e.extra]}function Nv(e,t){return kt(t).some((n)=>Da(e,n))}function Iv(e,t){let n=e.extra.length===0?"":` Also writable: ${e.extra.join(", ")}.`;if(t==="read")return e.confineReads?` Relative paths are resolved against ${e.primary}. Only ${kt(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 xr(e,t,n,r=e.mutating?"write":"read"){let i={...e.parameters.properties};for(let o of n){let s=i[o];if(s===void 0)continue;i[o]={...s,description:`${s.description??""}${Iv(t,r)}`}}return{...e,parameters:{...e.parameters,properties:i}}}var Je=new Map,Rv=8;function Lv(){return[...Je.entries()].map(([e,t])=>({pid:e,...t})).sort((e,t)=>t.since-e.since)}function xv(){let e=[];for(let[t,n]of Je)try{process.kill(-t,"SIGTERM"),e.push(`${t} (${n.command})`)}catch{}return Je.clear(),e}function Dv(){for(let e of[...Je.keys()])try{process.kill(e,0)}catch{Je.delete(e)}}var jv=250,wa=2000,Uv=new Set(["sleep","git","ssh","scp","sudo","su","doas"]);function zv(e){for(let t of e.split(/\s+/)){if(/^[A-Za-z_]\w*=/.test(t))continue;return t.replace(/^.*\//,"").toLowerCase()}return""}function Fv(e){let t=Ts(e);if(t.length===0)return!1;return t.every((n)=>!Uv.has(zv(n)))}function ja(e){return`'${e.replaceAll("'","'\\''")}'`}function Bv(e,t){return[e,"__code=$?",`{ printf '%s\\n' "$__code"; pwd; } > ${ja(t)} 2>/dev/null`,"exit $__code"].join(`
269
- `)}function Kv(e,t,n=process.platform){if(!t)return{file:"/bin/sh",args:["-c",e],env:{}};if(n==="linux")return{file:"script",args:["-qec",`/bin/sh -c ${ja(e)}`,"/dev/null"],env:{SHELL:"/bin/sh"}};return{file:"script",args:["-q","/dev/null","/bin/sh","-c",e],env:{SHELL:"/bin/sh"}}}function gn(e,t){let n=e.pid;if(n===void 0)return;try{process.kill(-n,t)}catch{}}async function qv(e){try{let[t,n]=(await Mv(e,"utf8")).split(`
270
- `),r=Number.parseInt(t??"",10),i=n?.trim();return{...Number.isNaN(r)?{}:{code:r},...i===void 0||i===""?{}:{cwd:i}}}catch{return{}}}async function Ua(e){if(Dv(),Je.size>=Rv)throw Gw(Lv().map((a)=>a.command));let t=Bv(e.command,e.statusPath),{file:n,args:r,env:i}=Kv(t,e.pty),o=await Pv(e.outPath,"w"),s;try{s=Cv(n,r,{cwd:e.cwd,env:{...e.env,...i},stdio:["ignore",o.fd,o.fd],detached:!0})}catch(a){throw await o.close(),la(e.command,String(a))}let c=await new Promise((a,h)=>{let f=!1,d=!1,u=setTimeout(m,e.background?jv:e.timeoutMs),p=(y)=>{if(f)return;f=!0,clearTimeout(u),e.signal.removeEventListener("abort",g),a(y)};function m(){if(e.background||Fv(e.command)){if(s.unref(),s.pid!==void 0)Je.set(s.pid,{command:e.command,since:Date.now(),outPath:e.outPath});p({ending:"backgrounded",...s.pid===void 0?{}:{pid:s.pid}});return}d=!0,gn(s,"SIGTERM"),setTimeout(()=>gn(s,"SIGKILL"),wa).unref?.()}function g(){gn(s,"SIGTERM"),setTimeout(()=>gn(s,"SIGKILL"),wa).unref?.()}e.signal.addEventListener("abort",g,{once:!0}),s.on("error",(y)=>{if(f)return;f=!0,clearTimeout(u),e.signal.removeEventListener("abort",g),h(e.pty&&Zv(y)?Dw(process.platform,String(y)):la(e.command,String(y)))}),s.on("exit",(y,w)=>{p({ending:d?"killed":"finished",...y===null?{}:{code:y},...w===null?{}:{killedBy:w},...s.pid===void 0?{}:{pid:s.pid}})})}).finally(()=>o.close()),l=await qv(e.statusPath);return{...c,...l.code===void 0?{}:{code:l.code},...l.cwd===void 0?{}:{cwdAfter:l.cwd}}}function Zv(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}var wn=120000,za=600000,Wv=5000,Jv={slug:"exec",provider:Ce,summary:"Runs a shell command on this computer and returns what it printed.",whenToUse:"you need to do something on this machine that no other tool covers — run a build or a test suite, use a command-line program, inspect what is running, or move and archive files in bulk",whenNotToUse:"reading one file, writing one file, or finding files by name or content — use file_read, file_write, glob and grep instead. They are more reliable and their targets can be checked against the permission rules; a path buried in a shell string cannot be",mutating:!0,trust:"untrusted",policyArg:"command",tags:["write","system","shell"],parameters:{type:"object",properties:{command:{type:"string",description:"The command, exactly as it would be typed at a shell prompt. Set environment variables inline (VAR=value command) rather than expecting them to survive from an earlier call."},workdir:{type:"string",description:"Directory to run in. Relative paths are resolved against wherever the previous command ended up. Defaults to that directory, so a cd carries over."},timeoutMs:{type:"integer",description:`How long to wait, in milliseconds. Default ${wn}, maximum ${za}.`,default:wn},pty:{type:"boolean",description:"Give the command a terminal. Needed only by programs that behave differently without one, such as those that ask for a password or draw a progress display.",default:!1},background:{type:"boolean",description:"Start it and return immediately instead of waiting. Use for something long-running like a dev server; the output keeps accumulating in a file whose path is reported.",default:!1}},required:["command"]}};function Hv(e,t){let n=e===void 0||e<=0?wn:e,r=Math.min(n,za),i=t-Wv;return Math.max(1,Math.min(r,i>0?i:Math.floor(t*0.8)))}function va(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function Vv(e,t){let n=Lr();return{out:Pr(n,`${e.turnId}-${t}.log`),status:Pr(n,`${e.turnId}-${t}.status`)}}function Gv(e){return async(t,n)=>{let r=typeof t.command==="string"?t.command.trim():"";if(r==="")throw Lw();let i=e.sessions.lastCwd(n.sessionKey),o=i??e.roots.primary,s=typeof t.workdir==="string"?t.workdir.trim():"",c=s===""?o:gv(s)?s:Pr(o,s),l;try{if(l=await pv(c),!(await mv(l)).isDirectory())throw Error("not a directory")}catch{let w=s===""&&i!==void 0;if(w)e.sessions.forget(n.sessionKey);throw xw(c,w)}let a=Hv(va(t.timeoutMs),n.deadlineMs),h=va(t.timeoutMs),f=h!==void 0&&h!==wn&&a<h,d=t.background===!0,u=Lr();await hv(u,{recursive:!0});let p=Vv(n,Yv(r,n.turnId)),m=await Ua({command:r,cwd:l,env:e.env,timeoutMs:a,pty:t.pty===!0,background:d,signal:n.signal,outPath:p.out,statusPath:p.status});if(m.cwdAfter!==void 0)e.sessions.remember(n.sessionKey,m.cwdAfter);let g=await Ra(p.out),y=t.pty===!0?{...g,head:bv(g.head)}:g;if(await pa(p.status,{force:!0}),!y.spilled&&m.ending!=="backgrounded")await pa(p.out,{force:!0});return Xv({command:r,cwd:l,run:m,observation:y,clamped:f,timeoutMs:a,path:p.out})}}function Yv(e,t){let n=2166136261;for(let r of[e,t])for(let i=0;i<r.length;i+=1)n^=r.charCodeAt(i),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}function Xv(e){let t=[];if(e.clamped)t.push(`The requested timeout was longer than allowed, so this ran with ${e.timeoutMs} ms.`);if(e.run.ending==="backgrounded")return t.push(`Still running${e.run.pid===void 0?"":` as process ${e.run.pid}`}. It was left alone rather than stopped, and keeps writing to ${e.path}; read that file to see how far it has got. Nothing here is its final result.`),[...t,Ir("Output so far",e.observation.head)].join(`
271
-
272
- `);if(e.run.ending==="killed")t.push(`Stopped after ${e.timeoutMs} ms without finishing, and everything it started was stopped with it. Whatever it had already done still happened.`);else if(e.run.code!==void 0&&e.run.code!==0)t.push(`Failed with exit code ${e.run.code}.`);else if(e.run.killedBy!==void 0)t.push(`Ended on signal ${e.run.killedBy}.`);if(e.run.cwdAfter!==void 0&&e.run.cwdAfter!==e.cwd)t.push(`The working directory is now ${e.run.cwdAfter}, and the next exec call starts there.`);let n=e.run.ending==="killed"||(e.run.code??0)!==0,r=[];if(e.observation.spilled){if(t.push(`Output was ${_v(e.observation.bytes)}, too much to include. All of it is in ${e.path}; what follows is the ${n?"start and end":"start"}.`),r.push(Ir("First part of the output",e.observation.head)),n)r.push(Ir("End of the output",e.observation.tail))}else if(e.observation.head.trim()!=="")r.push(e.observation.head.trimEnd());else if(t.length===0)return"The command finished successfully and printed nothing.";return[...t,...r].join(`
273
-
274
- `)}function Ir(e,t){return`${e}:
275
- ${t.trimEnd()}`}function Qv(e){return{spec:xr(Jv,e.roots,["command","workdir"],"shell"),handler:Gv(e)}}var ab=["agent.yaml","agent.yml","SOUL.md","SOUL.compact.md","AGENTS.md","POLICY.md","REMINDER.md"],Za=[".ssh",".aws",".kube",".gnupg",".docker"],Wa=/^(?:\.env(\..+)?|\.netrc|\.npmrc|\.pypirc|id_[a-z0-9]+|.*\.pem|.*\.key)$/i;function Ja(e){return e.split(qa).filter((t)=>t!=="")}function Mr(e){let t=Ja(e),n=t[t.length-1]??"";for(let r of Za)if(t.includes(r))return`${r}/ holds credentials`;if(Wa.test(n))return`${n} holds secrets — the manifest names environment variables, and their values are not the agent's`;if(t[0]==="proc"&&(n==="environ"||n==="cmdline"))return`${e} is a process's environment, which holds this runtime's secrets`;return}function cb(e,t){let n=Ja(e),r=n[n.length-1]??"";for(let c of Za)if(n.includes(c))return`${c}/ holds credentials, and nothing under it is writable by an agent`;if(Wa.test(r))return`${r} holds secrets — the manifest names environment variables, and their values are not the agent's to edit`;let i=ob(t.agentDir),o=sb(i,e);if(o!==""&&!o.startsWith("..")&&!ib(o)){let c=o.split(qa),l=c[c.length-1]??"";if(ab.includes(l))return`${o} is part of this agent's own definition — who it is, what it does, or what it is permitted to do — and it is not editable from inside a turn`;if(c[0]?.startsWith(".")===!0)return`${o} is runtime state this agent depends on`}for(let c of t.extra??[])if(e.includes(c)||r===c)return`${r} is listed in tools.providerConfig.protect`;return}var _a=2000000,Rr=400;function lb(e){return e.subarray(0,8000).includes(0)}var ub={slug:"file_read",provider:Ce,summary:"Reads a file and returns its contents.",whenToUse:"you need to see what is in a file — its code, its configuration, its text — before answering about it or changing it",whenNotToUse:"you are looking for which files exist or which ones mention something; that is glob and grep. Never read a file by running cat through the shell",mutating:!1,trust:"untrusted",policyArg:"path",policyArgIsPath:!0,tags:["read","file"],parameters:{type:"object",properties:{path:{type:"string",description:"The file, absolute or relative to the current working directory."},offset:{type:"integer",description:"First line to return, counting from 1. Use for a long file."},limit:{type:"integer",description:`How many lines to return. Defaults to ${Rr}.`,default:Rr}},required:["path"]}},db={slug:"file_write",provider:Ce,summary:"Writes a file, creating any folders it needs, and replaces it if it already exists.",whenToUse:"you are creating a new file, or replacing one whose whole contents you are producing. Folders in the path are created for you, so this needs no separate step and no shell",whenNotToUse:"you are changing part of an existing file — that is file_edit, which cannot silently destroy the rest of it",mutating:!0,trust:"trusted",trustReason:"It reports what it wrote — the path, the line count — and never any of the content, so nothing from the file reaches the model through it.",policyArg:"path",policyArgIsPath:!0,tags:["write","file"],parameters:{type:"object",properties:{path:{type:"string",description:"The file, absolute or relative to the current working directory."},content:{type:"string",description:"The complete new contents."}},required:["path","content"]}},fb={slug:"file_edit",provider:Ce,summary:"Replaces an exact piece of text in a file, leaving the rest untouched.",whenToUse:"you are changing part of a file you have already read — a line, a block, a value — and everything else should stay as it is",whenNotToUse:"you have not read the file in this conversation, or you are writing the whole thing; guessing at text that is already there fails rather than damaging the file, but it still wastes the step",mutating:!0,trust:"trusted",trustReason:"It reports which occurrence changed and how long the file now is, never the text on either side of the change.",policyArg:"path",policyArgIsPath:!0,tags:["write","file"],parameters:{type:"object",properties:{path:{type:"string",description:"The file, absolute or relative to the current working directory."},find:{type:"string",description:"The exact text to replace, copied from the file including its indentation. It must appear exactly once unless all is true."},replace:{type:"string",description:"What to put in its place."},all:{type:"boolean",description:"Replace every occurrence instead of requiring exactly one.",default:!1}},required:["path","find","replace"]}};function vn(e,t,n,r){let i=Ev(typeof e==="string"?e.trim():"");if(i==="")throw jw();let o=t.lastCwd(n)??r;return rb(i)?ba(i):ba(o,i)}function Ha(e,t){if(!Nv(e,t.roots))throw Ww(e,kt(t.roots));let n=cb(e,{agentDir:t.agentDir,...t.protect===void 0?{}:{extra:t.protect}});if(n!==void 0)throw Bw(e,n)}function ka(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function hb(e){return async(t,n)=>{let r=vn(t.path,e.sessions,n.sessionKey,e.roots.primary);xa(r,e.roots);let i=Mr(await tb(r).catch(()=>r))??Mr(r);if(i!==void 0)throw Fw(r,i);let o;try{o=(await Ba(r)).size}catch{throw Na(r)}if(o>_a)throw Uw(r,o,_a);let s=await Fa(r);if(lb(s))throw zw(r,o);let l=Jt(s.toString("utf8")).split(`
276
- `),a=Math.max(1,ka(t.offset)??1),h=Math.max(1,ka(t.limit)??Rr),f=l.slice(a-1,a-1+h);if(f.length===0)return`${r} has ${l.length} lines, so there is nothing at line ${a}.`;let d=f.join(`
277
- `),u=a-1+f.length;if(a===1&&u>=l.length)return d;return`Lines ${a}-${u} of ${l.length} in ${r}:
278
- ${d}`}}function pb(e){return async(t,n)=>{let r=vn(t.path,e.sessions,n.sessionKey,e.roots.primary);Ha(r,e);let i=typeof t.content==="string"?t.content:String(t.content??""),o=await Ba(r).then(()=>!0,()=>!1);await eb(nb(r),{recursive:!0}),await Ka(r,i,"utf8");let s=i===""?0:i.split(`
279
- `).length;return`${o?"Replaced":"Created"} ${r} — ${s} line${s===1?"":"s"}, ${i.length} characters.`}}function mb(e){return async(t,n)=>{let r=vn(t.path,e.sessions,n.sessionKey,e.roots.primary);Ha(r,e);let i=typeof t.find==="string"?t.find:"",o=typeof t.replace==="string"?t.replace:"",s;try{s=await Fa(r,"utf8")}catch{throw Na(r)}let c=i===""?0:s.split(i).length-1;if(c===0)throw Kw(r,i);if(c>1&&t.all!==!0)throw qw(r,c);let l=t.all===!0?s.split(i).join(o):s.replace(i,o);await Ka(r,l,"utf8");let a=t.all===!0?c:1;return`Edited ${r} — replaced ${a} occurrence${a===1?"":"s"}. The file is now ${l.split(`
280
- `).length} lines.`}}function gb(e){let t=(n)=>xr(n,e.roots,["path"]);return[{spec:t(ub),handler:hb(e)},{spec:t(db),handler:pb(e)},{spec:t(fb),handler:mb(e)}]}var _b=new Set(["node_modules",".git",".hg",".svn","dist","build","out",".next",".turbo",".cache","coverage","__pycache__",".venv","venv","target","vendor"]);function Va(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n]??"";if(r==="*"){if(e[n+1]==="*"){if(e[n+2]==="/"){t+="(?:.*/)?",n+=2;continue}t+=".*",n+=1;continue}t+="[^/]*";continue}if(r==="?"){t+="[^/]";continue}t+=r.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${t}$`)}function kb(e){return Sa==="/"?e:e.split(Sa).join("/")}async function Ga(e,t){let n=[],r=[e];while(r.length>0){let i=r.shift();if(i===void 0)break;let o;try{o=await wb(i,{withFileTypes:!0})}catch{continue}for(let s of o){let c=vb(i,s.name);if(s.isDirectory()){if(_b.has(s.name))continue;if(t.hidden!==!0&&s.name.startsWith("."))continue;r.push(c);continue}if(!s.isFile())continue;if(t.hidden!==!0&&s.name.startsWith("."))continue;let l=kb(bb(e,c));if(t.accept!==void 0&&!t.accept(l))continue;if(n.length>=t.limit)return{files:n,truncated:!0};n.push(l)}}return{files:n,truncated:!1}}var Ta=200,$a=100,Sb=1e6,Tb={slug:"glob",provider:Ce,summary:"Finds files whose path matches a pattern.",whenToUse:"you need to know which files exist, or where a file is, when you know something about its name — every test file, every yaml, anything under a directory",whenNotToUse:"you know what a file is called and want to see it, which is file_read; or you are searching for text inside files, which is grep",mutating:!1,trust:"untrusted",policyArg:"pattern",tags:["read","file","search"],parameters:{type:"object",properties:{pattern:{type:"string",description:"A path pattern. * matches within one directory, ** matches across directories — for example **/*.test.ts or src/**/index.*"},path:{type:"string",description:"Directory to search under. Defaults to the current directory."},hidden:{type:"boolean",description:"Include files and directories whose name begins with a dot.",default:!1}},required:["pattern"]}},$b={slug:"grep",provider:Ce,summary:"Finds lines in files that match a regular expression.",whenToUse:"you need to find where something is written — a function name, a setting, a phrase — without knowing which file it is in",whenNotToUse:"you are looking for files by name, which is glob; or you already know the file, in which case read it. Never run grep or rg through the shell",mutating:!1,trust:"untrusted",policyArg:"pattern",tags:["read","file","search"],parameters:{type:"object",properties:{pattern:{type:"string",description:"A regular expression, matched against each line."},path:{type:"string",description:"Directory to search under. Defaults to the current directory."},glob:{type:"string",description:"Only search files whose path matches this, for example **/*.ts. Searches everything if omitted."},ignoreCase:{type:"boolean",description:"Match regardless of case.",default:!1}},required:["pattern"]}};function Ya(e,t,n){let r=typeof e.path==="string"&&e.path.trim()!==""?e.path:".",i=vn(r,t.sessions,n,t.roots.primary);return xa(i,t.roots),i}function Eb(e){return async(t,n)=>{let r=typeof t.pattern==="string"?t.pattern.trim():"",i=Ya(t,e,n.sessionKey),o=Va(r),s=await Ga(i,{limit:Ta,...t.hidden===!0?{hidden:!0}:{},accept:(l)=>o.test(l)});if(s.files.length===0)return`No file under ${i} matches ${r}. Directories like node_modules, .git and dist are never searched${t.hidden===!0?"":", and dot-files are skipped unless hidden is true"}.`;return`${s.truncated?`The first ${s.files.length} of more than ${Ta} matches for ${r} under ${i} — narrow the pattern to see the rest:`:`${s.files.length} match${s.files.length===1?"":"es"} for ${r} under ${i}:`}
281
- ${s.files.join(`
282
- `)}`}}function Ab(e){return async(t,n)=>{let r=typeof t.pattern==="string"?t.pattern:"",i=Ya(t,e,n.sessionKey),o;try{o=new RegExp(r,t.ignoreCase===!0?"i":"")}catch(d){throw Zw(r,String(d))}let s=typeof t.glob==="string"&&t.glob.trim()!==""?Va(t.glob.trim()):void 0,c=await Ga(i,{limit:5000,...s===void 0?{}:{accept:(d)=>s.test(d)}}),l=[],a=0,h=!1;for(let d of c.files){if(l.length>=$a){h=!0;break}if(Mr(`${i}/${d}`)!==void 0)continue;let u;try{let m=await yb(`${i}/${d}`);if(m.length>Sb||m.subarray(0,8000).includes(0))continue;u=m.toString("utf8")}catch{continue}a+=1;let p=u.split(`
283
- `);for(let m=0;m<p.length;m+=1){let g=p[m]??"";if(!o.test(g))continue;if(l.length>=$a){h=!0;break}let y=g.length>300?`${g.slice(0,300)}…`:g;l.push(`${d}:${m+1}: ${Jt(y).trim()}`)}}if(l.length===0)return`Nothing under ${i} matches ${r}${s===void 0?"":` in files matching ${String(t.glob)}`}. ${a} file${a===1?"":"s"} were searched; node_modules, .git, dist and dot-files are skipped.`;return`${h?`The first ${l.length} matches for ${r} under ${i} — there are more, so narrow the pattern or pass a glob:`:`${l.length} match${l.length===1?"":"es"} for ${r} under ${i}, across ${a} file${a===1?"":"s"} searched:`}
284
- ${l.join(`
285
- `)}`}}function Ob(e){let t=(n)=>xr(n,e.roots,["path"]);return[{spec:t(Tb),handler:Eb(e)},{spec:t($b),handler:Ab(e)}]}class Xa{#e=new Map;lastCwd(e){return this.#e.get(e)}remember(e,t){this.#e.set(e,t)}forget(e){this.#e.delete(e)}}function Ea(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}class Qa{id=Ce;#e=new Xa;#n;constructor(e){let t=Ov(e.dir,e.writeRoots??[],e.confineReads===!0),n={sessions:this.#e,agentDir:e.dir,roots:t,...e.protect===void 0?{}:{protect:e.protect}};this.#n=[Qv({sessions:this.#e,env:e.env,roots:t}),...gb(n),...Ob({sessions:this.#e,roots:t}),...lv({agentDir:e.dir,...e.providers===void 0?{}:{providers:e.providers},...e.mediaProviders===void 0?{}:{mediaProviders:e.mediaProviders}})]}available(){return Promise.resolve(this.#n.map((e)=>({slug:e.spec.slug,summary:e.spec.summary})))}resolve(e){let t=new Set(e.map(Ea));return Promise.resolve(this.#n.filter((n)=>t.has(Ea(n.spec.slug))))}stop(){return Promise.resolve(xv())}list(){return Promise.resolve(this.#n.map((e)=>e.spec.slug))}}var Aa=["protect","writeRoots","env","confineReads"];function Dr(e,t){let n=Object.keys(e.config).filter((c)=>!Aa.includes(c));if(n.length>0)throw new Q({code:"system_config_unknown",message:`tools.providerConfig has ${n.length===1?"a key":"keys"} the system provider does not read: ${n.join(", ")}.`,hint:`Accepted keys are ${Aa.join(", ")} — extra paths the file tools refuse to write, and extra directories they may write. Refused rather than ignored, because a protection that looks applied and is not is worse than a rejected manifest.`,field:"tools.providerConfig"});let r=e.config.protect,i=e.config.writeRoots,o=e.config.confineReads;if(o!==void 0&&typeof o!=="boolean")throw new Q({code:"system_config_invalid",message:"tools.providers.system.confineReads must be true or false.",hint:"true confines file_read, glob and grep to the agent's directory and its writeRoots; false, or leaving it out, keeps reads unconfined as before.",field:"tools.providers.system.confineReads"});let s=fv(e.config.env);return t?.(s),new Qa({env:Pa(e.env,s),dir:e.dir,...e.providers===void 0?{}:{providers:e.providers},...e.mediaProviders===void 0?{}:{mediaProviders:e.mediaProviders},...Array.isArray(r)?{protect:r.map((c)=>String(c))}:{},...Array.isArray(i)?{writeRoots:i.map((c)=>String(c))}:{},...o===!0?{confineReads:!0}:{}})}function Pb(e){return`'${e.replaceAll("'","'\\''")}'`}class bn{#e;#n;constructor(e){this.#e=e.env,this.#n=e.policy??(()=>"inherit")}has(e){let t=this.#e.PATH??process.env.PATH??"";for(let n of t.split(Cb)){if(n==="")continue;try{let r=Nb(Cr(n,e));if(r.isFile()&&(r.mode&73)!==0)return!0}catch{}}return!1}async run(e){let t=Lr();await Ib(t,{recursive:!0});let n=Mb([e.command,...e.args].join(" ")),r=Cr(t,`skill-${n}.out`),i=Cr(t,`skill-${n}.status`),o=[e.command,...e.args].map(Pb).join(" "),s=await Ua({command:o,cwd:e.cwd,env:Pa(this.#e,this.#n()),timeoutMs:e.timeoutMs,pty:!1,background:!1,signal:e.signal,outPath:r,statusPath:i}),c=await Ra(r);if(await Oa(i,{force:!0}),!c.spilled&&s.ending!=="backgrounded")await Oa(r,{force:!0});let l=s.ending==="killed"||s.ending==="backgrounded",a=c.spilled?`${c.head}
286
-
287
- … ${c.bytes} bytes in total; the rest is at ${r}
288
-
289
- ${c.tail}`:c.head;return{ok:s.ending==="finished"&&s.code===0,output:s.ending==="backgrounded"?`${a}
290
-
291
- Still running past ${e.timeoutMs} ms, left going rather than discarded. Output continues to accumulate at ${r}.`:a,...s.code===void 0?{}:{code:s.code},timedOut:l}}}function Mb(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}var Rb="0.1.0",ec={name:"system",version:Rb,dispachApi:"^0.2",permissions:[{kind:"exec",commands:["*"]},{kind:"fs",paths:["<workspace>"],mode:"write"}],setup(e){let t="inherit";e.defineToolProvider("system",(n)=>Dr(n,(r)=>{t=r})),e.defineScriptRunner(new bn({env:e.env,policy:()=>t}))}};import{lookup as t_}from"node:dns/promises";function tc(e,t){return new b({code:"web_url_unparseable",message:`That is not a URL: ${JSON.stringify(e)}`,hint:`${t}. Give a complete absolute URL including the scheme — https://example.com/page, not example.com/page. Parsed with the standard URL parser rather than a pattern, so what is accepted here is exactly what a browser would accept.`,field:"url"})}function Lb(e){return new b({code:"web_scheme_refused",message:`${e} URLs are not fetchable.`,hint:"Only http and https. This tool reaches the public web and nothing else — a file:// URL reads the disk, which is file_read's job and subject to its rules, and the other schemes reach services that were never designed to be spoken to by an HTTP client.",field:"url"})}function xb(){return new b({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 jr(e,t,n,r,i){let o=t===e?t:`${e} → ${t}`;return new b({code:"web_address_refused",message:`${o} is ${n}${r===void 0?"":` (${r})`} and will not be fetched${i>0?`, reached by redirect ${i}`:""}.`,hint:"This is a standing rule with no setting that overrides it. Addresses off the public internet — loopback, link-local, private and carrier-grade NAT ranges — include the cloud metadata endpoint and every service on this machine, so a page that can make this tool fetch one is a page that can read them. Nothing was requested. If the page is genuinely public, check the hostname.",field:"url"})}function _n(e,t){return new b({code:"web_host_refused",message:`${e} is not a public hostname: ${t}.`,hint:"Nothing was requested. This tool reaches the public web; names that only resolve inside this machine or this network are refused before any lookup happens.",field:"url"})}function nc(e,t){return new b({code:"web_host_unresolvable",message:`${e} could not be resolved: ${t}`,hint:"Refused rather than handed to the HTTP client anyway. The address check happens on what DNS returns, so a name that will not resolve here cannot be checked — and fetching it regardless would mean the one request nobody looked at is the one that failed the lookup. Check the spelling of the host.",field:"url"})}function rc(e,t){return new b({code:"web_request_failed",message:`The request to ${e} did not complete: ${t}`,hint:"The address passed every check, so this is the network or the far end rather than a refusal. Worth one retry if it reads like a timeout; not worth retrying if the host is simply gone.",field:"url"})}function uc(e,t,n){return new b({code:"web_status_failed",message:`${e} answered ${t}${n===""?"":` ${n}`}.`,hint:`${t===404?"The page is not there — check the URL against a search result rather than guessing at the path.":t===403||t===401?"The page requires credentials or refuses automated clients. There is no setting that supplies either; treat the page as unavailable and say so.":"A server-side failure. One retry is reasonable; a second is not."}`,field:"url"})}function ic(e,t){return new b({code:"web_too_many_redirects",message:`${e} redirected more than ${t} times.`,hint:"Followed manually and re-checked at every hop, which is why the count is low — a redirect chain is the standard way to get a checked URL to end up somewhere unchecked. A chain this long is a redirect loop or a tracker, not a page.",field:"url"})}function Db(e,t){return new b({code:"web_content_unusable",message:`${e} returned ${t}, which has no text to extract.`,hint:"Refused rather than decoded: a binary rendered as text is thousands of meaningless tokens and no information. This tool reads HTML, plain text, JSON and similar. PDF and image extraction are deliberately not in scope.",field:"url"})}function jb(e,t){return new Q({code:"web_search_key_missing",message:`The ${e} search backend needs ${t} and it is not set.`,hint:`Set ${t} in the .env beside agent.yaml, or in the environment. The manifest names the variable and never holds the key — a manifest with a literal key fails validation.`,field:"tools.providers.web.apiKeyEnv"})}function Ub(e,t,n){return new b({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 Oe(e,t){return new Q({code:"web_config_invalid",message:`tools.providers.web.${e} ${t}`,hint:"Refused rather than defaulted around: a search backend silently different from the one configured returns different results with nothing reporting why.",field:`tools.providers.web.${e}`})}function zb(e){return new Q({code:"web_firecrawl_key_missing",message:`Firecrawl needs ${e} and it is not set.`,hint:`Set ${e} in the .env beside agent.yaml, or in the environment (or ${e}_FILE naming a file that holds it). tools.providers.web.firecrawl.apiKeyEnv names a different variable if you need one.`,field:"tools.providers.web.firecrawl.apiKeyEnv"})}function Fb(e,t,n){return new b({code:t===402?"web_firecrawl_credits":"web_firecrawl_failed",message:`Firecrawl ${e} answered ${t}: ${n}`,hint:t===402?"The Firecrawl account is out of credits. Nothing here can fix that; say so rather than trying another page.":t===401||t===403?"The Firecrawl key was rejected. Check the value of the variable named in tools.providers.web.firecrawl.apiKeyEnv.":t===429?"Rate limited by Firecrawl. Wait before the next call; nothing in the manifest raises it.":"A failure at Firecrawl rather than in the request. The page may block its crawler; try another source."})}var sc=["tavily","brave","exa","firecrawl"];function te(e,t){return typeof e==="object"&&e!==null?e[t]:void 0}function _e(e){return typeof e==="string"?e:""}function Sn(e){return Array.isArray(e)?e:[]}var Bb={id:"tavily",defaultKeyEnv:"TAVILY_API_KEY",defaultBase:"https://api.tavily.com",unit:"credits",request(e,t,n,r){return{url:`${r}/search`,init:{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({query:e,max_results:t,search_depth:"basic",include_answer:!1})}}},read(e){return Sn(te(e,"results")).map((t)=>({title:_e(te(t,"title")),url:_e(te(t,"url")),snippet:_e(te(t,"content"))}))}},Kb={id:"brave",defaultKeyEnv:"BRAVE_API_KEY",defaultBase:"https://api.search.brave.com/res/v1",unit:"requests",request(e,t,n,r){let i=new URL(`${r}/web/search`);return i.searchParams.set("q",e),i.searchParams.set("count",String(t)),{url:i.href,init:{method:"GET",headers:{accept:"application/json","x-subscription-token":n}}}},read(e){return Sn(te(te(e,"web"),"results")).map((t)=>({title:_e(te(t,"title")),url:_e(te(t,"url")),snippet:_e(te(t,"description"))}))}},qb={id:"exa",defaultKeyEnv:"EXA_API_KEY",defaultBase:"https://api.exa.ai",unit:"requests",request(e,t,n,r){return{url:`${r}/search`,init:{method:"POST",headers:{"x-api-key":n,"content-type":"application/json"},body:JSON.stringify({query:e,numResults:t,contents:{text:{maxCharacters:400}}})}}},read(e){return Sn(te(e,"results")).map((t)=>({title:_e(te(t,"title")),url:_e(te(t,"url")),snippet:_e(te(t,"text"))||_e(te(t,"snippet"))}))}},Zb={id:"firecrawl",defaultKeyEnv:"FIRECRAWL_API_KEY",defaultBase:"https://api.firecrawl.dev/v2",unit:"credits",request(e,t,n,r){return{url:`${r}/search`,init:{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({query:e,limit:t})}}},read(e){return Sn(te(te(e,"data"),"web")).map((t)=>({title:_e(te(t,"title")),url:_e(te(t,"url")),snippet:_e(te(t,"description"))}))},units(e){let t=te(e,"creditsUsed");return typeof t==="number"&&Number.isFinite(t)?t:1}},Wb={tavily:Bb,brave:Kb,exa:qb,firecrawl:Zb};function dc(e){return Wb[e]}async function Jb(e,t){let n=t.statusText;try{let r=await t.text();if(r!=="")n=r.length>300?`${r.slice(0,300)}…`:r}catch{}throw Ub(e,t.status,n)}var Hb=["script","style","noscript","template","svg","canvas","iframe","head"],Vb=/<\/?(?:p|div|br|hr|section|article|header|footer|nav|aside|main|h[1-6]|li|tr|td|th|blockquote|pre|figcaption|dt|dd)\b[^>]*>/gi,Gb={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",hellip:"…",mdash:"—",ndash:"–",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",times:"×",middot:"·",bull:"•",copy:"©",reg:"®",trade:"™",deg:"°",eacute:"é",egrave:"è",agrave:"à",ccedil:"ç",uuml:"ü",ouml:"ö",auml:"ä"};function fc(e){return e.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]{1,31});/g,(t,n)=>{if(n.startsWith("#")){let r=n.startsWith("#x")||n.startsWith("#X")?Number.parseInt(n.slice(2),16):Number.parseInt(n.slice(1),10);if(!Number.isFinite(r)||r<0||r>1114111)return t;if(r>=55296&&r<=57343)return t;return String.fromCodePoint(r)}return Gb[n.toLowerCase()]??t})}function Yb(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(e);if(t===null)return;let n=hc(fc(t[1]??""));return n===""?void 0:n}function Xb(e){let t=e;for(let n of Hb)t=t.replace(new RegExp(`<${n}\\b[^>]*>[\\s\\S]*?</${n}>`,"gi")," "),t=t.replace(new RegExp(`<${n}\\b[^>]*>[\\s\\S]*$`,"i")," ");return t=Zr(t," "),t=t.replace(Vb,`
292
- `),t=t.replace(/<[^>]*>/g," "),t=fc(t),t.split(`
293
- `).map((n)=>hc(n)).filter((n,r,i)=>n!==""||(i[r-1]??"")!=="").join(`
294
- `).trim()}function hc(e){return e.replace(/\s+/g," ").trim()}function Qb(e,t){let n=t.split(";")[0]?.trim().toLowerCase()??"";if(n.includes("html")||n.includes("xml")){let r=Yb(e);return{text:Xb(e),...r===void 0?{}:{title:r}}}return{text:e.trim()}}function e_(e){let t=e.split(";")[0]?.trim().toLowerCase()??"";if(t==="")return!0;if(t.startsWith("text/"))return!0;return/^application\/(?:json|xml|xhtml\+xml|ld\+json|rss\+xml|atom\+xml|javascript|x-ndjson)$/.test(t)}var n_=new Set(["http:","https:"]),r_=[".local",".localhost",".internal",".intranet",".lan",".home.arpa"];function pc(e){let t=e.trim();if(t==="")throw tc(e,"the value is empty");try{return new URL(t)}catch(n){throw tc(e,n instanceof Error?n.message:String(n))}}function i_(e){if(!n_.has(e.protocol))throw Lb(e.protocol.replace(":",""));if(e.username!==""||e.password!=="")throw xb();let t=e.hostname.toLowerCase();if(t==="")throw _n(e.href,"there is no host in the URL");if(t==="localhost")throw _n(t,"it is this machine by definition");for(let r of r_)if(t.endsWith(r))throw _n(t,`${r} names are resolved on the local network, not the internet`);let n=t.startsWith("[")?"":t;if(n!==""&&!n.includes(".")&&mr(t)===void 0)throw _n(t,"a name with no dot in it is completed by the local search domain")}async function mc(e,t,n=0){i_(e);let r=e.hostname.toLowerCase(),i=mr(r);if(i!==void 0){if(i.kind!=="public")throw jr(r,r,i.kind,i.range,n);return}let o;try{o=await t(r)}catch(s){throw nc(r,s instanceof Error?s.message:String(s))}if(o.length===0)throw nc(r,"it has no addresses");for(let{address:s}of o){let c=mr(s);if(c===void 0)throw jr(r,s,"an address this cannot classify",void 0,n);if(c.kind!=="public")throw jr(r,s,c.kind,c.range,n)}}var s_=async(e)=>(await t_(e,{all:!0,verbatim:!0})).map((n)=>({address:n.address})),Tt="web",gc=2000000,Ur=6000,kn=5,o_=3000,a_=20000,yc={slug:"web_fetch",provider:Tt,summary:"Reads one web page and returns its text.",whenToUse:"you have a specific URL — from the person, from a search result, from a document — and need what is actually on that page rather than what you remember about it",whenNotToUse:"you do not have a URL yet, which is web_search; the address is on this machine or this network, which is refused; or you want a file from disk, which is file_read",mutating:!1,trust:"untrusted",policyArg:"url",tags:["read","web"],parameters:{type:"object",properties:{url:{type:"string",description:"The complete address of one page, including https://. Public internet only — addresses on this machine or this network are refused."}},required:["url"]}};function c_(e){return{spec:yc,handler:u_(e)}}function l_(e){let t=Math.max(1000,e-o_);return Math.min(a_,t)}function u_(e){let t=e.maxBytes??gc;return async(n,r)=>{let i=String(n.url??""),o=pc(i),s=new AbortController,c=()=>{s.abort()};r.signal.addEventListener("abort",c,{once:!0});let l=setTimeout(c,l_(r.deadlineMs));try{for(let a=0;a<=kn;a+=1){await mc(o,e.lookup,a);let h;try{h=await e.fetch(o.href,{method:"GET",redirect:"manual",signal:s.signal,headers:{"user-agent":e.userAgent,accept:"text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5","accept-language":"en"}})}catch(w){throw rc(o.href,w instanceof Error?w.message:String(w))}let f=h.headers.get("location");if(d_(h.status)&&f!==null){if(await h.body?.cancel().catch(()=>{return}),a===kn)throw ic(i,kn);try{o=new URL(f,o)}catch{throw rc(o.href,`it redirected to an unusable address: ${f}`)}continue}if(!h.ok)throw await h.body?.cancel().catch(()=>{return}),uc(o.href,h.status,h.statusText);let d=h.headers.get("content-type")??"";if(!e_(d))throw await h.body?.cancel().catch(()=>{return}),Db(o.href,d.split(";")[0]?.trim()??"binary");let{text:u,read:p,capped:m}=await f_(h,t),{title:g,text:y}=Qb(u,d);return wc({url:o.href,requested:i,...g===void 0?{}:{title:g},text:y,read:p,capped:m,hops:a})}throw ic(i,kn)}finally{clearTimeout(l),r.signal.removeEventListener("abort",c)}}}function d_(e){return e===301||e===302||e===303||e===307||e===308}async function f_(e,t){let n=e.body;if(n===null)return{text:"",read:0,capped:!1};let r=n.getReader(),i=new TextDecoder("utf-8"),o=[],s=0,c=!1;try{for(;;){let{done:l,value:a}=await r.read();if(l)break;if(a===void 0)continue;if(s+=a.byteLength,s>=t){let h=a.byteLength-(s-t);o.push(i.decode(a.subarray(0,Math.max(0,h)),{stream:!0})),c=!0;break}o.push(i.decode(a,{stream:!0}))}}finally{await r.cancel().catch(()=>{return})}return o.push(i.decode()),{text:o.join(""),read:Math.min(s,t),capped:c}}function wc(e){let t=[];if(t.push(e.url),e.hops>0&&e.url!==e.requested)t.push(`redirected from ${e.requested} (${e.hops} hop${e.hops===1?"":"s"})`);if(e.title!==void 0)t.push(`title: ${e.title}`);let n=e.text,r=!1;if(n.length>Ur)n=n.slice(0,Ur),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 ${Ur.toLocaleString("en-US")} characters are shown`);if(i.length>0)t.push(`incomplete: ${i.join("; ")}`);return t.push(""),t.push(n===""?"(the page has no readable text)":n),t.join(`
295
- `)}var h_="https://api.firecrawl.dev/v2",zr=3000,vc=60000,p_=2000,m_=12000,g_=6000,bc=5,_c=20,kc=100,Sc=500;function W(e,t){return typeof e==="object"&&e!==null?e[t]:void 0}function me(e){if(typeof e==="string")return e;if(Array.isArray(e)&&typeof e[0]==="string")return e[0];return""}function Fr(e,t){let n=W(e,"creditsUsed");return typeof n==="number"&&Number.isFinite(n)?n:t}async function St(e,t,n,r,i){let o=e.env[e.config.apiKeyEnv]??"";if(o==="")throw zb(e.config.apiKeyEnv);let s=await e.fetch(`${e.config.baseUrl??h_}${n}`,{method:r.method,headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},...r.body===void 0?{}:{body:JSON.stringify(r.body)},signal:i});if(!s.ok){let c=s.statusText;try{let l=await s.text(),a=me(W(y_(l),"error"));c=a!==""?a:l.length>300?`${l.slice(0,300)}…`:l}catch{}throw Fb(t,s.status,c)}return await s.json()}function y_(e){try{return JSON.parse(e)}catch{return}}function Br(e,t){let n=new AbortController,r=()=>n.abort();e.signal.addEventListener("abort",r,{once:!0});let i=setTimeout(r,Math.min(t,Math.max(1000,e.deadlineMs-zr)));return{signal:n.signal,done:()=>{clearTimeout(i),e.signal.removeEventListener("abort",r)}}}async function Kr(e,t){let n=pc(e);return await mc(n,t.lookup),n}function w_(e){return{spec:yc,handler:async(n,r)=>{let i=String(n.url??""),o=await Kr(i,e),s=Math.max(1000,Math.min(e.config.timeoutMs??vc,r.deadlineMs-2*zr)),{signal:c,done:l}=Br(r,s+zr);try{let a=await St(e,"scrape","/scrape",{method:"POST",body:{url:o.href,formats:["markdown"],onlyMainContent:e.config.onlyMainContent,timeout:s,...e.config.maxAgeMs===void 0?{}:{maxAge:e.config.maxAgeMs}}},c);r.meter?.({provider:"firecrawl",operation:"scrape",unit:"credits",units:Fr(a,1)});let h=W(a,"data"),f=W(h,"metadata"),d=W(f,"statusCode"),u=me(W(f,"url"))||me(W(f,"sourceURL"))||o.href;if(typeof d==="number"&&d>=400)throw uc(u,d,me(W(f,"error")));let p=me(W(f,"title")),m=me(W(h,"markdown"));return wc({url:u,requested:i,...p===""?{}:{title:p},text:m,read:m.length,capped:!1,hops:u===o.href?0:1})}finally{l()}}}}var v_={slug:"web_map",provider:Tt,summary:"Lists the page addresses on one website, optionally filtered by a phrase.",whenToUse:"you need to find the right page on a site you already know — its documentation, pricing, a changelog — before reading it with web_fetch",whenNotToUse:"you do not know the site yet, which is web_search; you already have the page's address, which is web_fetch; or you need the pages' text, which is web_crawl",mutating:!1,trust:"untrusted",policyArg:"url",tags:["read","web"],parameters:{type:"object",properties:{url:{type:"string",description:"The site's address, including https://. Public internet only."},search:{type:"string",description:"A word or phrase the addresses should relate to. Leave it out to list them all."},limit:{type:"integer",description:`How many addresses to return, 1 to ${Sc}.`,default:kc}},required:["url"]}};function b_(e){return{spec:v_,handler:async(n,r)=>{let i=await Kr(String(n.url??""),e),o=String(n.search??"").trim(),s=Tc(n.limit,kc,Sc),{signal:c,done:l}=Br(r,vc);try{let a=await St(e,"map","/map",{method:"POST",body:{url:i.href,limit:s,...o===""?{}:{search:o}}},c);r.meter?.({provider:"firecrawl",operation:"map",unit:"credits",units:Fr(a,1)});let h=(Array.isArray(W(a,"links"))?W(a,"links"):[]).map((m)=>typeof m==="string"?{url:m,title:""}:{url:me(W(m,"url")),title:me(W(m,"title"))}).filter((m)=>m.url!=="").slice(0,s);if(h.length===0)return`No addresses found on ${i.host}${o===""?"":` for ${JSON.stringify(o)}`}. The site may block crawlers or publish no sitemap; web_fetch on its home page is the other way in.`;let f=[],d=0;for(let m of h){let g=m.title===""?m.url:`${m.url} — ${m.title}`;if(d+g.length>g_)break;f.push(g),d+=g.length+1}let u=`${h.length} address${h.length===1?"":"es"} on ${i.host}${o===""?"":` for ${JSON.stringify(o)}`}:`,p=f.length<h.length?[`incomplete: only the first ${f.length} are shown; narrow it with search`]:[];return[u,...p,"",...f].join(`
296
- `)}finally{l()}}}}var __={slug:"web_crawl",provider:Tt,summary:"Reads several pages of one website, following its links, and returns their text.",whenToUse:"the answer is spread over a section of one site — a documentation chapter, a set of policy pages — and reading the pages one at a time would take many calls",whenNotToUse:"one page is enough, which is web_fetch; you only need the addresses, which is web_map; or you do not know the site, which is web_search. Each page costs, so keep the limit small",mutating:!1,trust:"untrusted",policyArg:"url",tags:["read","web"],parameters:{type:"object",properties:{url:{type:"string",description:"Where to start, including https://. Only pages on this site are read."},limit:{type:"integer",description:`How many pages to read, 1 to ${_c}.`,default:bc},includePaths:{type:"array",items:{type:"string"},description:"Only follow addresses whose path matches one of these regular expressions, such as ^/docs/. Leave it out to follow any page on the site."}},required:["url"]}};function k_(e){return{spec:__,handler:async(n,r)=>{let i=await Kr(String(n.url??""),e),o=Tc(n.limit,bc,_c),s=Array.isArray(n.includePaths)?n.includePaths.map((h)=>String(h)).filter((h)=>h!==""):[],{signal:c,done:l}=Br(r,Number.POSITIVE_INFINITY),a="";try{let h=await St(e,"crawl","/crawl",{method:"POST",body:{url:i.href,limit:o,...s.length===0?{}:{includePaths:s},scrapeOptions:{formats:["markdown"],onlyMainContent:e.config.onlyMainContent,...e.config.maxAgeMs===void 0?{}:{maxAge:e.config.maxAgeMs}}}},c);a=me(W(h,"id"));let f={};while(!c.aborted){if(await S_(p_,c),c.aborted)break;try{f=await St(e,"crawl",`/crawl/${encodeURIComponent(a)}`,{method:"GET"},c)}catch(w){if(c.aborted)break;throw w}let y=me(W(f,"status"));if(y==="completed"||y==="failed")break}let d=me(W(f,"status")),u=(Array.isArray(W(f,"data"))?W(f,"data"):[]).map((y)=>({url:me(W(W(y,"metadata"),"sourceURL"))||me(W(W(y,"metadata"),"url")),markdown:me(W(y,"markdown"))})).filter((y)=>y.markdown!=="");if(r.meter?.({provider:"firecrawl",operation:"crawl",unit:"credits",units:Fr(f,u.length)}),d!=="completed"&&a!=="")await St(e,"crawl",`/crawl/${encodeURIComponent(a)}`,{method:"DELETE"},AbortSignal.timeout(5000)).catch(()=>{return});if(u.length===0)return d==="failed"?`The crawl of ${i.href} failed and read no pages. Try web_fetch on the page itself.`:`The crawl of ${i.href} read no pages in time. Try a smaller limit, or web_fetch on the page itself.`;let p=Math.floor(m_/u.length),m=u.map((y)=>{let w=y.markdown.length>p?`${y.markdown.slice(0,p).trimEnd()}
297
- …(cut)`:y.markdown;return`## ${y.url}
298
-
299
- ${w}`}),g=[];if(d!=="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(`
300
-
301
- `)].join(`
302
- `)}finally{l()}}}}function Tc(e,t,n){let r=typeof e==="number"?e:Number(e);if(!Number.isFinite(r))return t;return Math.min(n,Math.max(1,Math.trunc(r)))}function S_(e,t){return new Promise((n)=>{if(t.aborted)return n();let r=setTimeout(()=>{t.removeEventListener("abort",i),n()},e),i=()=>{clearTimeout(r),n()};t.addEventListener("abort",i,{once:!0})})}var $c=5,Ec=10,oc=300,T_=3000,$_=15000,E_={slug:"web_search",provider:Tt,summary:"Searches the web and returns titles, addresses and short extracts.",whenToUse:"you need something current, something you are unsure about, or a page whose address you do not know — prices, news, documentation, whether a thing still exists",whenNotToUse:"you already have the URL, which is web_fetch; the answer is in a file or in this conversation; or you want to find a tool rather than a page, which this cannot do",mutating:!1,trust:"untrusted",policyArg:"query",tags:["read","web","search"],parameters:{type:"object",properties:{query:{type:"string",description:"What to search for, written the way you would type it into a search box. Keywords work better than a full sentence."},maxResults:{type:"integer",description:`How many results to return, 1 to ${Ec}.`,default:$c}},required:["query"]}};function A_(e){return{spec:E_,handler:O_(e)}}function O_(e){let t=dc(e.backend);return async(n,r)=>{let i=String(n.query??"").trim();if(i==="")return"No query was given, so nothing was searched for. Call this again with the words you want to look up.";let o=e.env[e.apiKeyEnv]??"";if(o==="")throw jb(t.id,e.apiKeyEnv);let s=N_(n.maxResults),{url:c,init:l}=t.request(i,s,o,e.baseUrl??t.defaultBase),a=new AbortController,h=()=>{a.abort()};r.signal.addEventListener("abort",h,{once:!0});let f=setTimeout(h,Math.min($_,Math.max(1000,r.deadlineMs-T_)));try{let d=await e.fetch(c,{...l,signal:a.signal});if(!d.ok)await Jb(t.id,d);let u=await d.json();return r.meter?.({provider:t.id,operation:"search",unit:t.unit,units:t.units?.(u)??1}),I_(i,t.read(u).slice(0,s))}finally{clearTimeout(f),r.signal.removeEventListener("abort",h)}}}function N_(e){let t=typeof e==="number"?e:Number(e);if(!Number.isFinite(t))return $c;return Math.min(Ec,Math.max(1,Math.trunc(t)))}function I_(e,t){if(t.length===0)return`No results for ${JSON.stringify(e)}. The search ran and came back empty — a narrower or differently worded query may find something, but do not assume the subject does not exist.`;let n=t.map((r,i)=>{let o=r.snippet.length>oc?`${r.snippet.slice(0,oc).trimEnd()}…`:r.snippet;return[`${i+1}. ${r.title===""?"(untitled)":r.title}`,` ${r.url}`,...o===""?[]:[` ${o.replace(/\s+/g," ")}`]].join(`
303
- `)});return[`${t.length} result${t.length===1?"":"s"} for ${JSON.stringify(e)}:`,"",...n].join(`
304
- `)}var C_="dispach-agent/0.1 (+https://github.com/moeen-mahmud/dispach)";function ac(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}class Ac{id=Tt;#e;constructor(e){let t=e.backend??"tavily",n=dc(t),r=e.fetch??((o,s)=>fetch(o,s)),i=e.lookup??s_;this.#e=[A_({backend:t,apiKeyEnv:e.apiKeyEnv??n.defaultKeyEnv,...e.baseUrl===void 0?{}:{baseUrl:e.baseUrl},env:e.env,fetch:r}),...e.firecrawl===void 0?[c_({lookup:i,fetch:r,maxBytes:e.maxBytes??gc,userAgent:C_})]:(()=>{let o={config:e.firecrawl,env:e.env,fetch:r,lookup:i};return[w_(o),k_(o),b_(o)]})()]}available(){return Promise.resolve(this.#e.map((e)=>({slug:e.spec.slug,summary:e.spec.summary})))}resolve(e){let t=new Set(e.map(ac));return Promise.resolve(this.#e.filter((n)=>t.has(ac(n.spec.slug))))}list(){return Promise.resolve(this.#e.map((e)=>e.spec.slug))}}var cc=["backend","apiKeyEnv","baseUrl","maxBytes","firecrawl"],lc=["apiKeyEnv","baseUrl","onlyMainContent","maxAge","timeoutMs"];function Wr(e){let t=Object.keys(e.config).filter((c)=>!cc.includes(c));if(t.length>0)throw new Q({code:"web_config_unknown",message:`The web provider's configuration has ${t.length===1?"a key":"keys"} it does not read: ${t.join(", ")}.`,hint:`Accepted keys are ${cc.join(", ")}. Refused rather than ignored, because a setting that looks applied and is not is worse than a rejected manifest. There is deliberately no setting that permits private addresses.`,field:"tools.providers.web"});let n=e.config.backend;if(n!==void 0&&!sc.includes(String(n)))throw Oe("backend",`must be one of ${sc.join(", ")} — got ${JSON.stringify(n)}.`);let r=e.config.apiKeyEnv;if(r!==void 0&&(typeof r!=="string"||r===""))throw Oe("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 Oe("maxBytes","must be a number of at least 1000.");let o=Oc(e.config.baseUrl,"baseUrl"),s=P_(e.config.firecrawl,n==="firecrawl",typeof r==="string"?r:void 0,o);return new Ac({env:e.env,...o===void 0?{}:{baseUrl:o},...s===void 0?{}:{firecrawl:s},...n===void 0?{}:{backend:String(n)},...typeof r==="string"?{apiKeyEnv:r}:{},...typeof i==="number"?{maxBytes:i}:{}})}function P_(e,t,n,r){if(e===void 0&&!t)return;let i=typeof e==="object"&&e!==null?e:{};if(e!==void 0&&(typeof e!=="object"||e===null||Array.isArray(e)))throw Oe("firecrawl","must be a map, e.g. `firecrawl: {}` for the defaults.");let o=Object.keys(i).find((u)=>!lc.includes(u));if(o!==void 0)throw Oe(`firecrawl.${o}`,`is not a setting. Accepted: ${lc.join(", ")}.`);let s=i.apiKeyEnv;if(s!==void 0&&(typeof s!=="string"||s===""))throw Oe("firecrawl.apiKeyEnv","must be the non-empty name of an environment variable.");let c=i.onlyMainContent;if(c!==void 0&&typeof c!=="boolean")throw Oe("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 Oe(`firecrawl.${u}`,`must be a number of milliseconds from ${p} to ${m}.`);return g},h=Oc(i.baseUrl,"firecrawl.baseUrl")??(t?r:void 0),f=l("maxAge",0,2592000000),d=l("timeoutMs",1000,300000);return{apiKeyEnv:typeof s==="string"?s:t&&n!==void 0?n:"FIRECRAWL_API_KEY",onlyMainContent:c??!0,...h===void 0?{}:{baseUrl:h},...f===void 0?{}:{maxAgeMs:f},...d===void 0?{}:{timeoutMs:d}}}function Oc(e,t){if(e===void 0)return;let n;try{n=new URL(String(e))}catch{throw Oe(t,`is not a URL: ${JSON.stringify(e)}.`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw Oe(t,"must be an http or https address.");if(n.username!==""||n.password!=="")throw Oe(t,"must not carry credentials. The key travels in the request's own header, from apiKeyEnv.");return n.href.replace(/\/+$/,"")}var M_="0.1.0",Nc={name:"web",version:M_,dispachApi:"^0.2",permissions:[{kind:"network",hosts:["*"]}],setup(e){e.defineToolProvider("web",Wr)}};var ae={composio:Tr,mcp:(e)=>Ar(e),system:Dr,web:Wr},be={"bedrock-converse":pr()},Ee={aws:wr()};function pe(){return new bn({env:process.env})}var xS=Object.keys(ae),Ie={teams:Nn,slack:En,telegram:Pn,whatsapp:dr},DS=Object.keys(Ie),Qe={"@dispach/channel-a2a":Yr,"@dispach/channel-teams":di,"@dispach/channel-slack":ni,"@dispach/channel-telegram":yi,"@dispach/channel-whatsapp":bo,"@dispach/media-aws":Io,"@dispach/model-bedrock":Eo,"@dispach/tools-composio":Go,"@dispach/tools-mcp":ca,"@dispach/tools-system":ec,"@dispach/tools-web":Nc},qr=Object.keys(Qe);
305
- export{ae,be,Ee,pe,Ie,Qe,qr};
306
-
307
- //# debugId=A066D4EC68222AFD64756E2164756E21
308
- //# sourceMappingURL=index-n197qdw1.js.map