alchemylab-opencode 2.0.1 → 2.0.4

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 (232) hide show
  1. package/NODE_COMPAT.md +8 -1
  2. package/dist/20260127222353_familiar_lady_ursula-YYOFSQD5.js +18 -0
  3. package/dist/20260211171708_add_project_commands-3GKQTPBZ.js +18 -0
  4. package/dist/20260213144116_wakeful_the_professor-ROO7OAVL.js +18 -0
  5. package/dist/20260225215848_workspace-V2OZTNFF.js +18 -0
  6. package/dist/20260227213759_add_session_workspace_id-GVDWAXKM.js +18 -0
  7. package/dist/20260228203230_blue_harpoon-Z5QP2II5.js +18 -0
  8. package/dist/20260303231226_add_workspace_fields-QOVAFN7W.js +18 -0
  9. package/dist/20260309230000_move_org_to_state-RQURSDZD.js +18 -0
  10. package/dist/20260312043431_session_message_cursor-VBISKDXL.js +18 -0
  11. package/dist/20260323234822_events-PILJHLNA.js +18 -0
  12. package/dist/20260410174513_workspace-name-63YCZ5NS.js +18 -0
  13. package/dist/20260413175956_chief_energizer-NMAZYGDO.js +18 -0
  14. package/dist/20260423070820_add_icon_url_override-RAJCVNEP.js +18 -0
  15. package/dist/20260427172553_slow_nightmare-ULYYZLR4.js +18 -0
  16. package/dist/20260428004200_add_session_path-U4WO2TGE.js +18 -0
  17. package/dist/20260501142318_next_venus-6BCYATSC.js +18 -0
  18. package/dist/20260504145000_add_sync_owner-RGVHV6LN.js +18 -0
  19. package/dist/20260507164347_add_workspace_time-GE6UHNPM.js +18 -0
  20. package/dist/{20260510033149_session_usage-UGBVOXZB.js → 20260510033149_session_usage-7XHCFVKY.js} +5 -1
  21. package/dist/20260511000411_data_migration_state-2EGZKFLB.js +18 -0
  22. package/dist/20260511173437_session-metadata-K322YY33.js +18 -0
  23. package/dist/20260601010001_normalize_storage_paths-VZDTY366.js +18 -0
  24. package/dist/{20260225215848_workspace-ZMSOZSPA.js → 20260601202201_amazing_prowler-YT6PLK3L.js} +5 -1
  25. package/dist/{20260228203230_blue_harpoon-IW3Z4TQZ.js → 20260602002951_lowly_union_jack-6VLQTBVB.js} +5 -1
  26. package/dist/20260602182828_add_project_directories-TVSRD25A.js +18 -0
  27. package/dist/20260603001617_session_message_projection_indexes-PHKTF6HK.js +18 -0
  28. package/dist/{20260622170816_reset_v2_session_state-5JPHJTZG.js → 20260603040000_session_message_projection_order-7RTV2POG.js} +5 -1
  29. package/dist/20260603141458_session_input_inbox-RSBWABG7.js +18 -0
  30. package/dist/20260603160727_jittery_ezekiel_stane-DXBLLRVV.js +18 -0
  31. package/dist/20260604172448_event_sourced_session_input-H6Z3JEBD.js +18 -0
  32. package/dist/20260605003541_add_session_context_snapshot-6FDPM2TK.js +18 -0
  33. package/dist/20260605042240_add_context_epoch_agent-C2OF2UKR.js +18 -0
  34. package/dist/20260611035744_credential-YNZ47FSH.js +18 -0
  35. package/dist/20260611192811_lush_chimera-E357VI6P.js +18 -0
  36. package/dist/20260612174303_project_dir_strategy-VUGGK42O.js +18 -0
  37. package/dist/20260622142730_simplify_session_context_epoch-UYGXZ5BX.js +18 -0
  38. package/dist/20260622170816_reset_v2_session_state-EILLPCJQ.js +18 -0
  39. package/dist/20260622202450_simplify_session_input-Y65GDGBO.js +18 -0
  40. package/dist/NodeSdk-AGMQWBHH.js +18 -0
  41. package/dist/anthropic-45OFTLAW.js +18 -0
  42. package/dist/anthropic-FVULF7C3.js +18 -0
  43. package/dist/app-runtime-LDQWNGWP.js +18 -0
  44. package/dist/chunk-2JE3QYG6.js +18 -0
  45. package/dist/chunk-2MRHL4B2.js +18 -0
  46. package/dist/chunk-4GJE6OMN.js +190 -0
  47. package/dist/chunk-4MBUHJHY.js +22 -0
  48. package/dist/chunk-5BLZCAU6.js +55 -0
  49. package/dist/chunk-7XX6TY62.js +259 -0
  50. package/dist/chunk-ANF3QA3Z.js +48 -0
  51. package/dist/chunk-AZUMH3TO.js +18 -0
  52. package/dist/chunk-B74WSFN4.js +878 -0
  53. package/dist/chunk-BQ4IEPN3.js +19 -0
  54. package/dist/chunk-CYRZU5QM.js +33 -0
  55. package/dist/chunk-DADVNQTM.js +1490 -0
  56. package/dist/chunk-DO2UZ6NY.js +18 -0
  57. package/dist/chunk-DWEYXIQI.js +780 -0
  58. package/dist/chunk-EK6FQQHY.js +20 -0
  59. package/dist/chunk-ELPXQ32J.js +90 -0
  60. package/dist/chunk-FGLPSSRK.js +19 -0
  61. package/dist/chunk-FOHYZ7MJ.js +55 -0
  62. package/dist/chunk-FV7U6PVP.js +18 -0
  63. package/dist/chunk-FYYAOZPU.js +18 -0
  64. package/dist/chunk-G7PFO5HG.js +920 -0
  65. package/dist/chunk-GDWO6EXN.js +22 -0
  66. package/dist/chunk-GW3ZRKAI.js +20 -0
  67. package/dist/chunk-IYUSBBGY.js +35 -0
  68. package/dist/chunk-JPOFLMNH.js +18 -0
  69. package/dist/{chunk-VURLSDCB.js → chunk-K5LKDIVU.js} +4 -0
  70. package/dist/chunk-KS4WLVK5.js +19 -0
  71. package/dist/chunk-LIXP4TPL.js +18 -0
  72. package/dist/chunk-LSC4RT5V.js +36 -0
  73. package/dist/chunk-M5A6NFHQ.js +28 -0
  74. package/dist/chunk-M6E6KNLV.js +30 -0
  75. package/dist/chunk-MLFZXUGQ.js +18 -0
  76. package/dist/chunk-NDI67DRG.js +31 -0
  77. package/dist/chunk-NGT6LCW6.js +18 -0
  78. package/dist/chunk-OCWGUTZJ.js +36 -0
  79. package/dist/chunk-OGDRUXMJ.js +18 -0
  80. package/dist/chunk-OGJKLJC7.js +29 -0
  81. package/dist/chunk-OT2YNR56.js +19 -0
  82. package/dist/chunk-OUVSKG2H.js +19 -0
  83. package/dist/chunk-P5RLCJUV.js +18 -0
  84. package/dist/chunk-Q3WIUQXB.js +18 -0
  85. package/dist/{20260227213759_add_session_workspace_id-ROENWPKA.js → chunk-QCRIXKIC.js} +5 -1
  86. package/dist/chunk-QD24DLUD.js +18 -0
  87. package/dist/chunk-R2GWBJEP.js +18 -0
  88. package/dist/chunk-RPAXSOGH.js +18 -0
  89. package/dist/chunk-TK5R7QUN.js +18 -0
  90. package/dist/chunk-TNQWZFIZ.js +28 -0
  91. package/dist/chunk-UCLPBO4I.js +18 -0
  92. package/dist/chunk-UPEPL4I2.js +18 -0
  93. package/dist/chunk-V6FDDNGV.js +117 -0
  94. package/dist/chunk-V6HERYFV.js +18 -0
  95. package/dist/chunk-V7XKKJ7X.js +24 -0
  96. package/dist/chunk-VHDYUBBS.js +23 -0
  97. package/dist/chunk-VWLJXTZ5.js +18 -0
  98. package/dist/chunk-VXAPFOIL.js +22 -0
  99. package/dist/chunk-WKZYINC7.js +29 -0
  100. package/dist/chunk-WPMP2ZFE.js +40 -0
  101. package/dist/chunk-WRTNIOI3.js +18 -0
  102. package/dist/chunk-X5F46HR5.js +18 -0
  103. package/dist/chunk-XPS7TQZG.js +22 -0
  104. package/dist/chunk-YJPP6IQ3.js +23 -0
  105. package/dist/chunk-ZYQWFC55.js +22 -0
  106. package/dist/code-mode-YYOGD36U.js +502 -0
  107. package/dist/copilot-provider-QVMLQZZC.js +18 -0
  108. package/dist/dist-5NQOHNPL.js +18 -0
  109. package/dist/dist-7CT3XCNN.js +32 -0
  110. package/dist/dist-CL46WFZG.js +18 -0
  111. package/dist/{20260605042240_add_context_epoch_agent-W6IQYZXE.js → dist-CYBRID2F.js} +5 -1
  112. package/dist/dist-HXJTF22W.js +32 -0
  113. package/dist/dist-JFXI53ZF.js +22 -0
  114. package/dist/dist-KBYKWVT5.js +22 -0
  115. package/dist/dist-KM5HCPZX.js +35 -0
  116. package/dist/dist-KTNLTEHB.js +18 -0
  117. package/dist/dist-KZ5R5QM5.js +24 -0
  118. package/dist/dist-NLXUYBW7.js +32 -0
  119. package/dist/dist-O4DF72J2.js +22 -0
  120. package/dist/dist-PH4MEGVR.js +22 -0
  121. package/dist/{20260511000411_data_migration_state-FB4LBFSE.js → dist-QJPOJCLB.js} +5 -1
  122. package/dist/dist-QYH62TCJ.js +22 -0
  123. package/dist/{20260303231226_add_workspace_fields-OUVZMNAG.js → dist-RIC4WKHC.js} +5 -1
  124. package/dist/dist-T776XKTM.js +22 -0
  125. package/dist/dist-TCE5MKZQ.js +23 -0
  126. package/dist/dist-TH2Q44RX.js +50 -0
  127. package/dist/dist-VV5FV5RT.js +101 -0
  128. package/dist/dist-XAFENVUS.js +22 -0
  129. package/dist/dist-XPFB35TX.js +32 -0
  130. package/dist/dist-YUH4RKR5.js +28 -0
  131. package/dist/dist-es-43ZM44MP.js +18 -0
  132. package/dist/dist-es-6PLFRCS4.js +18 -0
  133. package/dist/dist-es-G5UIJOU7.js +26 -0
  134. package/dist/{20260428004200_add_session_path-LGW75WYA.js → dist-es-HYIIGUNX.js} +5 -1
  135. package/dist/dist-es-L2GU465G.js +18 -0
  136. package/dist/dist-es-LSR2QCFZ.js +18 -0
  137. package/dist/dist-es-RGEIM2BP.js +18 -0
  138. package/dist/dist-es-SITTNOGV.js +18 -0
  139. package/dist/dist-es-W5GYOX6F.js +18 -0
  140. package/dist/esm-NN5W7YCL.js +18 -0
  141. package/dist/esm-XWJSHYHG.js +18 -0
  142. package/dist/getMachineId-bsd-L5I5TZ5I.js +18 -0
  143. package/dist/getMachineId-darwin-YB7KG37W.js +19 -0
  144. package/dist/getMachineId-linux-EL47KXX7.js +18 -0
  145. package/dist/getMachineId-unsupported-QOWPEBPN.js +18 -0
  146. package/dist/getMachineId-win-HCRYRDFJ.js +18 -0
  147. package/dist/lib-ZP7Q6A3E.js +199 -0
  148. package/dist/loadCognitoIdentity-EWT55EI7.js +18 -0
  149. package/dist/loadSso-AGOUE6RL.js +18 -0
  150. package/dist/{20260213144116_wakeful_the_professor-ZVDD54AK.js → loadSts-RH5L3PIX.js} +5 -1
  151. package/dist/mantle-IJXDXT4M.js +25 -0
  152. package/dist/mime-types-46EO4HOZ.js +18 -0
  153. package/dist/multipart-parser-KZWMKXA4.js +19 -0
  154. package/dist/{20260211171708_add_project_commands-GDOHPDPF.js → open-7KXTRM37.js} +5 -1
  155. package/dist/openai-ZOJI6I5R.js +18 -0
  156. package/dist/p-map-CYL6ILJW.js +18 -0
  157. package/dist/photon-W56QZY4L.js +18 -0
  158. package/dist/{20260423070820_add_icon_url_override-X5SHFGTI.js → pkce-VT4ITJTB.js} +5 -1
  159. package/dist/{pty.node-Y3N2XKYG.js → pty.node-IWULXXG6.js} +5 -1
  160. package/dist/run.js +5 -1
  161. package/dist/serve.js +143 -1
  162. package/dist/server-LVIHYOCY.js +21 -0
  163. package/dist/session-6OPJNJMK.js +18 -0
  164. package/dist/signin-OCIW23YM.js +18 -0
  165. package/dist/src-3NCXEROI.js +18 -0
  166. package/dist/src-LXWGIUZH.js +18 -0
  167. package/dist/src-WDYKISPD.js +20 -0
  168. package/dist/src-YAAFIGTW.js +18 -0
  169. package/dist/sso-oidc-OMMKINFE.js +18 -0
  170. package/dist/sts-MWK22JIX.js +18 -0
  171. package/dist/token-QPO3OAGS.js +18 -0
  172. package/dist/token-util-YGPCEEPO.js +18 -0
  173. package/dist/unified-W3ZKZ4HG.js +18 -0
  174. package/dist/worktree-32M5MTFE.js +18 -0
  175. package/package.json +40 -40
  176. package/postinstall.cjs +4 -2
  177. package/dist/20260127222353_familiar_lady_ursula-KV747FJX.js +0 -14
  178. package/dist/20260309230000_move_org_to_state-NOXAPU5V.js +0 -14
  179. package/dist/20260312043431_session_message_cursor-DJ4T3T4R.js +0 -14
  180. package/dist/20260323234822_events-72GIKJ2A.js +0 -14
  181. package/dist/20260410174513_workspace-name-JXSWFBJN.js +0 -14
  182. package/dist/20260413175956_chief_energizer-4HEWZ6U3.js +0 -14
  183. package/dist/20260427172553_slow_nightmare-PS5T2AH2.js +0 -14
  184. package/dist/20260501142318_next_venus-J3TLVXZ6.js +0 -14
  185. package/dist/20260504145000_add_sync_owner-3R52GB4C.js +0 -14
  186. package/dist/20260507164347_add_workspace_time-JHDRCZAR.js +0 -14
  187. package/dist/20260511173437_session-metadata-T2XHGWHS.js +0 -14
  188. package/dist/20260601010001_normalize_storage_paths-5MAY5GT3.js +0 -14
  189. package/dist/20260601202201_amazing_prowler-PET224YG.js +0 -14
  190. package/dist/20260602002951_lowly_union_jack-PG6XDMGL.js +0 -14
  191. package/dist/20260602182828_add_project_directories-ZCH2ACGG.js +0 -14
  192. package/dist/20260603001617_session_message_projection_indexes-XVLJTUF2.js +0 -14
  193. package/dist/20260603040000_session_message_projection_order-XG6RACZQ.js +0 -14
  194. package/dist/20260603141458_session_input_inbox-K2VQ7V6E.js +0 -14
  195. package/dist/20260603160727_jittery_ezekiel_stane-WKJLRDO7.js +0 -14
  196. package/dist/20260604172448_event_sourced_session_input-NTXOECR7.js +0 -14
  197. package/dist/20260605003541_add_session_context_snapshot-DXMQEXMT.js +0 -14
  198. package/dist/20260611035744_credential-XTMSYTJD.js +0 -14
  199. package/dist/20260611192811_lush_chimera-XPLIQMJD.js +0 -14
  200. package/dist/20260612174303_project_dir_strategy-FR2NGQKK.js +0 -14
  201. package/dist/20260622142730_simplify_session_context_epoch-NTQZR3RE.js +0 -14
  202. package/dist/20260622202450_simplify_session_input-2EXF2HMV.js +0 -14
  203. package/dist/app-runtime-HQBOCDV5.js +0 -14
  204. package/dist/chunk-4FEBIOI5.js +0 -865
  205. package/dist/chunk-4K2RXRZL.js +0 -14
  206. package/dist/chunk-4RFMKEKM.js +0 -1455
  207. package/dist/chunk-BM2C7NHL.js +0 -41
  208. package/dist/chunk-MKEMZFJI.js +0 -393
  209. package/dist/chunk-OMDJ6ZZ2.js +0 -684
  210. package/dist/chunk-OWMG4NNF.js +0 -186
  211. package/dist/chunk-QRABYJKL.js +0 -14
  212. package/dist/chunk-RHIWAYN5.js +0 -14
  213. package/dist/chunk-Z5TLIUAI.js +0 -28
  214. package/dist/code-mode-7BQJUARW.js +0 -40
  215. package/dist/copilot-provider-TX4YFKJZ.js +0 -14
  216. package/dist/photon-VQS5F5BI.js +0 -14
  217. package/dist/server-BFUQR7MX.js +0 -17
  218. package/dist/session-6RNXZNG6.js +0 -14
  219. package/dist/worktree-QHQHX3SG.js +0 -14
  220. package/patches/@ai-sdk%2Famazon-bedrock@4.0.166.patch +0 -164
  221. package/patches/@ai-sdk%2Fanthropic@3.0.111.patch +0 -528
  222. package/patches/@ai-sdk%2Fgoogle@3.0.73.patch +0 -69
  223. package/patches/@ai-sdk%2Fgroq@3.0.31.patch +0 -79
  224. package/patches/@ai-sdk%2Fmistral@3.0.51.patch +0 -714
  225. package/patches/@ai-sdk%2Fopenai-compatible@2.0.41.patch +0 -39
  226. package/patches/@ai-sdk%2Fopenai@3.0.88.patch +0 -280
  227. package/patches/@ai-sdk%2Fxai@3.0.139.patch +0 -296
  228. package/patches/@modelcontextprotocol%2Fsdk@1.29.0.patch +0 -647
  229. package/patches/@npmcli%2Fagent@4.0.2.patch +0 -13
  230. package/patches/effect@4.0.0-beta.83.patch +0 -57
  231. package/patches/gcp-metadata@8.1.2.patch +0 -14
  232. package/patches/pacote@21.5.0.patch +0 -18
@@ -0,0 +1,878 @@
1
+ // Built by esbuild from opencode-server source
2
+ if (typeof globalThis.Bun === 'undefined') {
3
+ globalThis.Bun = {
4
+ version: '0.0.0-node-compat',
5
+ stdin: { async text() { const chunks = []; for await (const c of process.stdin) chunks.push(c); return Buffer.concat(chunks).toString(); } },
6
+ which(cmd) { try { return require('child_process').execFileSync('which', [cmd], { encoding: 'utf8' }).trim(); } catch { return null; } },
7
+ };
8
+ }
9
+ if (typeof globalThis.__name === 'undefined') { globalThis.__name = (t, n) => { Object.defineProperty(t, 'name', { value: n, configurable: true }); return t; }; }
10
+ if (typeof globalThis.__export === 'undefined') { globalThis.__export = (t, a) => { for (const k in a) Object.defineProperty(t, k, { get: a[k], enumerable: true }); }; }
11
+ import { createRequire as __alchemyCreateRequire } from 'node:module';
12
+ const require = __alchemyCreateRequire(import.meta.url);
13
+ import { fileURLToPath as __alchemyFileURLToPath } from 'node:url';
14
+ import { dirname as __alchemyDirname } from 'node:path';
15
+ const __alchemy_filename = __alchemyFileURLToPath(import.meta.url);
16
+ const __alchemy_dirname = __alchemyDirname(__alchemy_filename);
17
+
18
+ import{c as kp}from"./chunk-GW3ZRKAI.js";import{$a as wp,Aa as Ro,Da as Q,Fa as _p,Ha as vp,Ka as Sp,_ as Qa,_a as gn,aa as ap,b as de,ba as mn,bb as bp,ca as hn,ha as Nt,ia as yp,k as vs,kb as Xt,mb as oc,u as Yt,wa as zr,xa as mr}from"./chunk-DWEYXIQI.js";import{q as hp,r as gp}from"./chunk-WKZYINC7.js";import{a as ec,b as Ss,d as cp,f as v,g as lp,h as ce,i as fe,j as dp,k as up,l as xe,m as $,n as T,o as Te,p as Se,q as tc,r as rc,s as he,t as at,u as M,v as ke,w as pp,x as nc,y as fp,z as mp}from"./chunk-WPMP2ZFE.js";import{f as _s}from"./chunk-R2GWBJEP.js";import{Aa as zt,Ae as Ee,Ea as Lu,Fa as Uu,Ga as Vu,Ha as Fu,Ia as Hu,Ja as et,Ka as mt,La as K,Ma as ve,Pa as Wa,Uc as Xu,Vc as Ya,Zc as Qu,_c as ep,b as Au,bd as Xa,c as Mu,cd as Ne,db as Po,eb as Zu,fa as zu,ge as Ie,ha as ft,hb as Ku,he as Bt,ia as pr,ib as Gu,ja as Qe,jb as Ba,je as Dt,ke as X,la as Du,lb as Mr,lc as Ju,le as Jt,mb as se,mc as fr,nb as ht,oa as _e,ob as Wu,pa as Me,pc as ae,q as be,qa as Nu,qb as Ja,qc as O_,qe as tp,r as Mt,rc as Yu,re as rp,sa as ju,se as np,tb as Bu,va as qu,vb as ys,x as De,xe as op,ya as pn,ye as ip,za as fn,ze as sp}from"./chunk-7XX6TY62.js";import{Bc as He,Bf as a,Ig as Tu,Tc as V,Xa as Ga,aa as pt,bb as te,bi as ur,dc as pe,jd as xo,lc as Wt,nb as dr,ni as Ou,pj as f,rg as gs,zd as Ar}from"./chunk-ELPXQ32J.js";import{a as i,d as O,e as H,g as Ka}from"./chunk-2MRHL4B2.js";var yi=O(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.regexpCode=le.getEsmExportName=le.getProperty=le.safeStringify=le.stringify=le.strConcat=le.addCodeArg=le.str=le._=le.nil=le._Code=le.Name=le.IDENTIFIER=le._CodeOrName=void 0;var hi=class{static{i(this,"_CodeOrName")}};le._CodeOrName=hi;le.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Hr=class extends hi{static{i(this,"Name")}constructor(e){if(super(),!le.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};le.Name=Hr;var St=class extends hi{static{i(this,"_Code")}constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Hr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};le._Code=St;le.nil=new St("");function Bm(t,...e){let r=[t[0]],n=0;for(;n<e.length;)ml(r,e[n]),r.push(t[++n]);return new St(r)}i(Bm,"_");le._=Bm;var fl=new St("+");function Jm(t,...e){let r=[gi(t[0])],n=0;for(;n<e.length;)r.push(fl),ml(r,e[n]),r.push(fl,gi(t[++n]));return Hk(r),new St(r)}i(Jm,"str");le.str=Jm;function ml(t,e){e instanceof St?t.push(...e._items):e instanceof Hr?t.push(e):t.push(Gk(e))}i(ml,"addCodeArg");le.addCodeArg=ml;function Hk(t){let e=1;for(;e<t.length-1;){if(t[e]===fl){let r=Zk(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}i(Hk,"optimize");function Zk(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Hr||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Hr))return`"${t}${e.slice(1)}`}i(Zk,"mergeExprItems");function Kk(t,e){return e.emptyStr()?t:t.emptyStr()?e:Jm`${t}${e}`}i(Kk,"strConcat");le.strConcat=Kk;function Gk(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:gi(Array.isArray(t)?t.join(","):t)}i(Gk,"interpolate");function Wk(t){return new St(gi(t))}i(Wk,"stringify");le.stringify=Wk;function gi(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}i(gi,"safeStringify");le.safeStringify=gi;function Bk(t){return typeof t=="string"&&le.IDENTIFIER.test(t)?new St(`.${t}`):Bm`[${t}]`}i(Bk,"getProperty");le.getProperty=Bk;function Jk(t){if(typeof t=="string"&&le.IDENTIFIER.test(t))return new St(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}i(Jk,"getEsmExportName");le.getEsmExportName=Jk;function Yk(t){return new St(t.toString())}i(Yk,"regexpCode");le.regexpCode=Yk});var yl=O(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.ValueScope=rt.ValueScopeName=rt.Scope=rt.varKinds=rt.UsedValueState=void 0;var tt=yi(),hl=class extends Error{static{i(this,"ValueError")}constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ys;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ys||(rt.UsedValueState=Ys={}));rt.varKinds={const:new tt.Name("const"),let:new tt.Name("let"),var:new tt.Name("var")};var Xs=class{static{i(this,"Scope")}constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof tt.Name?e:this.name(e)}name(e){return new tt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};rt.Scope=Xs;var Qs=class extends tt.Name{static{i(this,"ValueScopeName")}constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,tt._)`.${new tt.Name(r)}[${n}]`}};rt.ValueScopeName=Qs;var Xk=(0,tt._)`\n`,gl=class extends Xs{static{i(this,"ValueScope")}constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Xk:tt.nil}}get(){return this._scope}name(e){return new Qs(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,c=(n=r.key)!==null&&n!==void 0?n:r.ref,l=this._values[s];if(l){let p=l.get(c);if(p)return p}else l=this._values[s]=new Map;l.set(c,o);let d=this._scope[s]||(this._scope[s]=[]),u=d.length;return d[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,tt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=tt.nil;for(let c in e){let l=e[c];if(!l)continue;let d=n[c]=n[c]||new Map;l.forEach(u=>{if(d.has(u))return;d.set(u,Ys.Started);let p=r(u);if(p){let m=this.opts.es5?rt.varKinds.var:rt.varKinds.const;s=(0,tt._)`${s}${m} ${u} = ${p};${this.opts._n}`}else if(p=o?.(u))s=(0,tt._)`${s}${p}${this.opts._n}`;else throw new hl(u);d.set(u,Ys.Completed)})}return s}};rt.ValueScope=gl});var B=O(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.or=J.and=J.not=J.CodeGen=J.operators=J.varKinds=J.ValueScopeName=J.ValueScope=J.Scope=J.Name=J.regexpCode=J.stringify=J.getProperty=J.nil=J.strConcat=J.str=J._=void 0;var re=yi(),It=yl(),Sr=yi();Object.defineProperty(J,"_",{enumerable:!0,get:i(function(){return Sr._},"get")});Object.defineProperty(J,"str",{enumerable:!0,get:i(function(){return Sr.str},"get")});Object.defineProperty(J,"strConcat",{enumerable:!0,get:i(function(){return Sr.strConcat},"get")});Object.defineProperty(J,"nil",{enumerable:!0,get:i(function(){return Sr.nil},"get")});Object.defineProperty(J,"getProperty",{enumerable:!0,get:i(function(){return Sr.getProperty},"get")});Object.defineProperty(J,"stringify",{enumerable:!0,get:i(function(){return Sr.stringify},"get")});Object.defineProperty(J,"regexpCode",{enumerable:!0,get:i(function(){return Sr.regexpCode},"get")});Object.defineProperty(J,"Name",{enumerable:!0,get:i(function(){return Sr.Name},"get")});var na=yl();Object.defineProperty(J,"Scope",{enumerable:!0,get:i(function(){return na.Scope},"get")});Object.defineProperty(J,"ValueScope",{enumerable:!0,get:i(function(){return na.ValueScope},"get")});Object.defineProperty(J,"ValueScopeName",{enumerable:!0,get:i(function(){return na.ValueScopeName},"get")});Object.defineProperty(J,"varKinds",{enumerable:!0,get:i(function(){return na.varKinds},"get")});J.operators={GT:new re._Code(">"),GTE:new re._Code(">="),LT:new re._Code("<"),LTE:new re._Code("<="),EQ:new re._Code("==="),NEQ:new re._Code("!=="),NOT:new re._Code("!"),OR:new re._Code("||"),AND:new re._Code("&&"),ADD:new re._Code("+")};var rr=class{static{i(this,"Node")}optimizeNodes(){return this}optimizeNames(e,r){return this}},_l=class extends rr{static{i(this,"Def")}constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?It.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Wn(this.rhs,e,r)),this}get names(){return this.rhs instanceof re._CodeOrName?this.rhs.names:{}}},ea=class extends rr{static{i(this,"Assign")}constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof re.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Wn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof re.Name?{}:{...this.lhs.names};return ra(e,this.rhs)}},vl=class extends ea{static{i(this,"AssignOp")}constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Sl=class extends rr{static{i(this,"Label")}constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},wl=class extends rr{static{i(this,"Break")}constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},bl=class extends rr{static{i(this,"Throw")}constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},kl=class extends rr{static{i(this,"AnyCode")}constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Wn(this.code,e,r),this}get names(){return this.code instanceof re._CodeOrName?this.code.names:{}}},_i=class extends rr{static{i(this,"ParentNode")}constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(Qk(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Gr(e,r.names),{})}},nr=class extends _i{static{i(this,"BlockNode")}render(e){return"{"+e._n+super.render(e)+"}"+e._n}},El=class extends _i{static{i(this,"Root")}},Gn=class extends nr{static{i(this,"Else")}};Gn.kind="else";var Zr=class t extends nr{static{i(this,"If")}constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Gn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Ym(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Wn(this.condition,e,r),this}get names(){let e=super.names;return ra(e,this.condition),this.else&&Gr(e,this.else.names),e}};Zr.kind="if";var Kr=class extends nr{static{i(this,"For")}};Kr.kind="for";var xl=class extends Kr{static{i(this,"ForLoop")}constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Wn(this.iteration,e,r),this}get names(){return Gr(super.names,this.iteration.names)}},Pl=class extends Kr{static{i(this,"ForRange")}constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?It.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ra(super.names,this.from);return ra(e,this.to)}},ta=class extends Kr{static{i(this,"ForIter")}constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Wn(this.iterable,e,r),this}get names(){return Gr(super.names,this.iterable.names)}},vi=class extends nr{static{i(this,"Func")}constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};vi.kind="func";var Si=class extends _i{static{i(this,"Return")}render(e){return"return "+super.render(e)}};Si.kind="return";var Rl=class extends nr{static{i(this,"Try")}render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Gr(e,this.catch.names),this.finally&&Gr(e,this.finally.names),e}},wi=class extends nr{static{i(this,"Catch")}constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};wi.kind="catch";var bi=class extends nr{static{i(this,"Finally")}render(e){return"finally"+super.render(e)}};bi.kind="finally";var Il=class{static{i(this,"CodeGen")}constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
19
+ `:""},this._extScope=e,this._scope=new It.Scope({parent:e}),this._nodes=[new El]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new _l(e,s,n)),s}const(e,r,n){return this._def(It.varKinds.const,e,r,n)}let(e,r,n){return this._def(It.varKinds.let,e,r,n)}var(e,r,n){return this._def(It.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new ea(e,r,n))}add(e,r){return this._leafNode(new vl(e,J.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new kl(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,re.addCodeArg)(r,o));return r.push("}"),new re._Code(r)}if(e,r,n){if(this._blockNode(new Zr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Zr(e))}else(){return this._elseNode(new Gn)}endIf(){return this._endBlockNode(Zr,Gn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new xl(e),r)}forRange(e,r,n,o,s=this.opts.es5?It.varKinds.var:It.varKinds.let){let c=this._scope.toName(e);return this._for(new Pl(s,c,r,n),()=>o(c))}forOf(e,r,n,o=It.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let c=r instanceof re.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,re._)`${c}.length`,l=>{this.var(s,(0,re._)`${c}[${l}]`),n(s)})}return this._for(new ta("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?It.varKinds.var:It.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,re._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new ta("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Kr)}label(e){return this._leafNode(new Sl(e))}break(e){return this._leafNode(new wl(e))}return(e){let r=new Si;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Si)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Rl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new wi(s),r(s)}return n&&(this._currNode=o.finally=new bi,this.code(n)),this._endBlockNode(wi,bi)}throw(e){return this._leafNode(new bl(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=re.nil,n,o){return this._blockNode(new vi(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(vi)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Zr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};J.CodeGen=Il;function Gr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}i(Gr,"addNames");function ra(t,e){return e instanceof re._CodeOrName?Gr(t,e.names):t}i(ra,"addExprNames");function Wn(t,e,r){if(t instanceof re.Name)return n(t);if(!o(t))return t;return new re._Code(t._items.reduce((s,c)=>(c instanceof re.Name&&(c=n(c)),c instanceof re._Code?s.push(...c._items):s.push(c),s),[]));function n(s){let c=r[s.str];return c===void 0||e[s.str]!==1?s:(delete e[s.str],c)}function o(s){return s instanceof re._Code&&s._items.some(c=>c instanceof re.Name&&e[c.str]===1&&r[c.str]!==void 0)}}i(Wn,"optimizeExpr");function Qk(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}i(Qk,"subtractNames");function Ym(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,re._)`!${Cl(t)}`}i(Ym,"not");J.not=Ym;var eE=Xm(J.operators.AND);function tE(...t){return t.reduce(eE)}i(tE,"and");J.and=tE;var rE=Xm(J.operators.OR);function nE(...t){return t.reduce(rE)}i(nE,"or");J.or=nE;function Xm(t){return(e,r)=>e===re.nil?r:r===re.nil?e:(0,re._)`${Cl(e)} ${t} ${Cl(r)}`}i(Xm,"mappend");function Cl(t){return t instanceof re.Name?t:(0,re._)`(${t})`}i(Cl,"par")});var oe=O(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.checkStrictMode=Y.getErrorPath=Y.Type=Y.useFunc=Y.setEvaluated=Y.evaluatedPropsToName=Y.mergeEvaluated=Y.eachItem=Y.unescapeJsonPointer=Y.escapeJsonPointer=Y.escapeFragment=Y.unescapeFragment=Y.schemaRefOrVal=Y.schemaHasRulesButRef=Y.schemaHasRules=Y.checkUnknownRules=Y.alwaysValidSchema=Y.toHash=void 0;var me=B(),oE=yi();function iE(t){let e={};for(let r of t)e[r]=!0;return e}i(iE,"toHash");Y.toHash=iE;function sE(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(th(t,e),!rh(e,t.self.RULES.all))}i(sE,"alwaysValidSchema");Y.alwaysValidSchema=sE;function th(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||ih(t,`unknown keyword: "${s}"`)}i(th,"checkUnknownRules");Y.checkUnknownRules=th;function rh(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}i(rh,"schemaHasRules");Y.schemaHasRules=rh;function aE(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}i(aE,"schemaHasRulesButRef");Y.schemaHasRulesButRef=aE;function cE({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,me._)`${r}`}return(0,me._)`${t}${e}${(0,me.getProperty)(n)}`}i(cE,"schemaRefOrVal");Y.schemaRefOrVal=cE;function lE(t){return nh(decodeURIComponent(t))}i(lE,"unescapeFragment");Y.unescapeFragment=lE;function dE(t){return encodeURIComponent(Tl(t))}i(dE,"escapeFragment");Y.escapeFragment=dE;function Tl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}i(Tl,"escapeJsonPointer");Y.escapeJsonPointer=Tl;function nh(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}i(nh,"unescapeJsonPointer");Y.unescapeJsonPointer=nh;function uE(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}i(uE,"eachItem");Y.eachItem=uE;function Qm({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,c,l)=>{let d=c===void 0?s:c instanceof me.Name?(s instanceof me.Name?t(o,s,c):e(o,s,c),c):s instanceof me.Name?(e(o,c,s),s):r(s,c);return l===me.Name&&!(d instanceof me.Name)?n(o,d):d}}i(Qm,"makeMergeEvaluated");Y.mergeEvaluated={props:Qm({mergeNames:i((t,e,r)=>t.if((0,me._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,me._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,me._)`${r} || {}`).code((0,me._)`Object.assign(${r}, ${e})`))}),"mergeNames"),mergeToName:i((t,e,r)=>t.if((0,me._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,me._)`${r} || {}`),Ol(t,r,e))}),"mergeToName"),mergeValues:i((t,e)=>t===!0?!0:{...t,...e},"mergeValues"),resultToName:oh}),items:Qm({mergeNames:i((t,e,r)=>t.if((0,me._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,me._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),"mergeNames"),mergeToName:i((t,e,r)=>t.if((0,me._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,me._)`${r} > ${e} ? ${r} : ${e}`)),"mergeToName"),mergeValues:i((t,e)=>t===!0?!0:Math.max(t,e),"mergeValues"),resultToName:i((t,e)=>t.var("items",e),"resultToName")})};function oh(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,me._)`{}`);return e!==void 0&&Ol(t,r,e),r}i(oh,"evaluatedPropsToName");Y.evaluatedPropsToName=oh;function Ol(t,e,r){Object.keys(r).forEach(n=>t.assign((0,me._)`${e}${(0,me.getProperty)(n)}`,!0))}i(Ol,"setEvaluated");Y.setEvaluated=Ol;var eh={};function pE(t,e){return t.scopeValue("func",{ref:e,code:eh[e.code]||(eh[e.code]=new oE._Code(e.code))})}i(pE,"useFunc");Y.useFunc=pE;var $l;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})($l||(Y.Type=$l={}));function fE(t,e,r){if(t instanceof me.Name){let n=e===$l.Num;return r?n?(0,me._)`"[" + ${t} + "]"`:(0,me._)`"['" + ${t} + "']"`:n?(0,me._)`"/" + ${t}`:(0,me._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,me.getProperty)(t).toString():"/"+Tl(t)}i(fE,"getErrorPath");Y.getErrorPath=fE;function ih(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}i(ih,"checkStrictMode");Y.checkStrictMode=ih});var or=O(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});var Ke=B(),mE={data:new Ke.Name("data"),valCxt:new Ke.Name("valCxt"),instancePath:new Ke.Name("instancePath"),parentData:new Ke.Name("parentData"),parentDataProperty:new Ke.Name("parentDataProperty"),rootData:new Ke.Name("rootData"),dynamicAnchors:new Ke.Name("dynamicAnchors"),vErrors:new Ke.Name("vErrors"),errors:new Ke.Name("errors"),this:new Ke.Name("this"),self:new Ke.Name("self"),scope:new Ke.Name("scope"),json:new Ke.Name("json"),jsonPos:new Ke.Name("jsonPos"),jsonLen:new Ke.Name("jsonLen"),jsonPart:new Ke.Name("jsonPart")};Al.default=mE});var ki=O(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.extendErrors=Ge.resetErrorsCount=Ge.reportExtraError=Ge.reportError=Ge.keyword$DataError=Ge.keywordError=void 0;var ie=B(),oa=oe(),Ye=or();Ge.keywordError={message:i(({keyword:t})=>(0,ie.str)`must pass "${t}" keyword validation`,"message")};Ge.keyword$DataError={message:i(({keyword:t,schemaType:e})=>e?(0,ie.str)`"${t}" keyword must be ${e} ($data)`:(0,ie.str)`"${t}" keyword is invalid ($data)`,"message")};function hE(t,e=Ge.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:c,allErrors:l}=o,d=ch(t,e,r);n??(c||l)?sh(s,d):ah(o,(0,ie._)`[${d}]`)}i(hE,"reportError");Ge.reportError=hE;function gE(t,e=Ge.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:c}=n,l=ch(t,e,r);sh(o,l),s||c||ah(n,Ye.default.vErrors)}i(gE,"reportExtraError");Ge.reportExtraError=gE;function yE(t,e){t.assign(Ye.default.errors,e),t.if((0,ie._)`${Ye.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ie._)`${Ye.default.vErrors}.length`,e),()=>t.assign(Ye.default.vErrors,null)))}i(yE,"resetErrorsCount");Ge.resetErrorsCount=yE;function _E({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let c=t.name("err");t.forRange("i",o,Ye.default.errors,l=>{t.const(c,(0,ie._)`${Ye.default.vErrors}[${l}]`),t.if((0,ie._)`${c}.instancePath === undefined`,()=>t.assign((0,ie._)`${c}.instancePath`,(0,ie.strConcat)(Ye.default.instancePath,s.errorPath))),t.assign((0,ie._)`${c}.schemaPath`,(0,ie.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ie._)`${c}.schema`,r),t.assign((0,ie._)`${c}.data`,n))})}i(_E,"extendErrors");Ge.extendErrors=_E;function sh(t,e){let r=t.const("err",e);t.if((0,ie._)`${Ye.default.vErrors} === null`,()=>t.assign(Ye.default.vErrors,(0,ie._)`[${r}]`),(0,ie._)`${Ye.default.vErrors}.push(${r})`),t.code((0,ie._)`${Ye.default.errors}++`)}i(sh,"addError");function ah(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ie._)`new ${t.ValidationError}(${e})`):(r.assign((0,ie._)`${n}.errors`,e),r.return(!1))}i(ah,"returnErrors");var Wr={keyword:new ie.Name("keyword"),schemaPath:new ie.Name("schemaPath"),params:new ie.Name("params"),propertyName:new ie.Name("propertyName"),message:new ie.Name("message"),schema:new ie.Name("schema"),parentSchema:new ie.Name("parentSchema")};function ch(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ie._)`{}`:vE(t,e,r)}i(ch,"errorObjectCode");function vE(t,e,r={}){let{gen:n,it:o}=t,s=[SE(o,r),wE(t,r)];return bE(t,e,s),n.object(...s)}i(vE,"errorObject");function SE({errorPath:t},{instancePath:e}){let r=e?(0,ie.str)`${t}${(0,oa.getErrorPath)(e,oa.Type.Str)}`:t;return[Ye.default.instancePath,(0,ie.strConcat)(Ye.default.instancePath,r)]}i(SE,"errorInstancePath");function wE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ie.str)`${e}/${t}`;return r&&(o=(0,ie.str)`${o}${(0,oa.getErrorPath)(r,oa.Type.Str)}`),[Wr.schemaPath,o]}i(wE,"errorSchemaPath");function bE(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:c,it:l}=t,{opts:d,propertyName:u,topSchemaRef:p,schemaPath:m}=l;n.push([Wr.keyword,o],[Wr.params,typeof e=="function"?e(t):e||(0,ie._)`{}`]),d.messages&&n.push([Wr.message,typeof r=="function"?r(t):r]),d.verbose&&n.push([Wr.schema,c],[Wr.parentSchema,(0,ie._)`${p}${m}`],[Ye.default.data,s]),u&&n.push([Wr.propertyName,u])}i(bE,"extraErrorProps")});var dh=O(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.boolOrEmptySchema=Bn.topBoolOrEmptySchema=void 0;var kE=ki(),EE=B(),xE=or(),PE={message:"boolean schema is false"};function RE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?lh(t,!1):typeof r=="object"&&r.$async===!0?e.return(xE.default.data):(e.assign((0,EE._)`${n}.errors`,null),e.return(!0))}i(RE,"topBoolOrEmptySchema");Bn.topBoolOrEmptySchema=RE;function IE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),lh(t)):r.var(e,!0)}i(IE,"boolOrEmptySchema");Bn.boolOrEmptySchema=IE;function lh(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,kE.reportError)(o,PE,void 0,e)}i(lh,"falseSchemaError")});var Ml=O(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.getRules=Jn.isJSONType=void 0;var CE=["string","number","integer","boolean","null","object","array"],$E=new Set(CE);function TE(t){return typeof t=="string"&&$E.has(t)}i(TE,"isJSONType");Jn.isJSONType=TE;function OE(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}i(OE,"getRules");Jn.getRules=OE});var zl=O(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.shouldUseRule=wr.shouldUseGroup=wr.schemaHasRulesForType=void 0;function AE({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&uh(t,n)}i(AE,"schemaHasRulesForType");wr.schemaHasRulesForType=AE;function uh(t,e){return e.rules.some(r=>ph(t,r))}i(uh,"shouldUseGroup");wr.shouldUseGroup=uh;function ph(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}i(ph,"shouldUseRule");wr.shouldUseRule=ph});var Ei=O(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.reportTypeError=We.checkDataTypes=We.checkDataType=We.coerceAndCheckDataType=We.getJSONTypes=We.getSchemaTypes=We.DataType=void 0;var ME=Ml(),zE=zl(),DE=ki(),W=B(),fh=oe(),Yn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Yn||(We.DataType=Yn={}));function NE(t){let e=mh(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}i(NE,"getSchemaTypes");We.getSchemaTypes=NE;function mh(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(ME.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}i(mh,"getJSONTypes");We.getJSONTypes=mh;function jE(t,e){let{gen:r,data:n,opts:o}=t,s=qE(e,o.coerceTypes),c=e.length>0&&!(s.length===0&&e.length===1&&(0,zE.schemaHasRulesForType)(t,e[0]));if(c){let l=Nl(e,n,o.strictNumbers,Yn.Wrong);r.if(l,()=>{s.length?LE(t,e,s):jl(t)})}return c}i(jE,"coerceAndCheckDataType");We.coerceAndCheckDataType=jE;var hh=new Set(["string","number","integer","boolean","null"]);function qE(t,e){return e?t.filter(r=>hh.has(r)||e==="array"&&r==="array"):[]}i(qE,"coerceToTypes");function LE(t,e,r){let{gen:n,data:o,opts:s}=t,c=n.let("dataType",(0,W._)`typeof ${o}`),l=n.let("coerced",(0,W._)`undefined`);s.coerceTypes==="array"&&n.if((0,W._)`${c} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,W._)`${o}[0]`).assign(c,(0,W._)`typeof ${o}`).if(Nl(e,o,s.strictNumbers),()=>n.assign(l,o))),n.if((0,W._)`${l} !== undefined`);for(let u of r)(hh.has(u)||u==="array"&&s.coerceTypes==="array")&&d(u);n.else(),jl(t),n.endIf(),n.if((0,W._)`${l} !== undefined`,()=>{n.assign(o,l),UE(t,l)});function d(u){switch(u){case"string":n.elseIf((0,W._)`${c} == "number" || ${c} == "boolean"`).assign(l,(0,W._)`"" + ${o}`).elseIf((0,W._)`${o} === null`).assign(l,(0,W._)`""`);return;case"number":n.elseIf((0,W._)`${c} == "boolean" || ${o} === null
20
+ || (${c} == "string" && ${o} && ${o} == +${o})`).assign(l,(0,W._)`+${o}`);return;case"integer":n.elseIf((0,W._)`${c} === "boolean" || ${o} === null
21
+ || (${c} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(l,(0,W._)`+${o}`);return;case"boolean":n.elseIf((0,W._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(l,!1).elseIf((0,W._)`${o} === "true" || ${o} === 1`).assign(l,!0);return;case"null":n.elseIf((0,W._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(l,null);return;case"array":n.elseIf((0,W._)`${c} === "string" || ${c} === "number"
22
+ || ${c} === "boolean" || ${o} === null`).assign(l,(0,W._)`[${o}]`)}}i(d,"coerceSpecificType")}i(LE,"coerceData");function UE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,W._)`${e} !== undefined`,()=>t.assign((0,W._)`${e}[${r}]`,n))}i(UE,"assignParentData");function Dl(t,e,r,n=Yn.Correct){let o=n===Yn.Correct?W.operators.EQ:W.operators.NEQ,s;switch(t){case"null":return(0,W._)`${e} ${o} null`;case"array":s=(0,W._)`Array.isArray(${e})`;break;case"object":s=(0,W._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=c((0,W._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=c();break;default:return(0,W._)`typeof ${e} ${o} ${t}`}return n===Yn.Correct?s:(0,W.not)(s);function c(l=W.nil){return(0,W.and)((0,W._)`typeof ${e} == "number"`,l,r?(0,W._)`isFinite(${e})`:W.nil)}}i(Dl,"checkDataType");We.checkDataType=Dl;function Nl(t,e,r,n){if(t.length===1)return Dl(t[0],e,r,n);let o,s=(0,fh.toHash)(t);if(s.array&&s.object){let c=(0,W._)`typeof ${e} != "object"`;o=s.null?c:(0,W._)`!${e} || ${c}`,delete s.null,delete s.array,delete s.object}else o=W.nil;s.number&&delete s.integer;for(let c in s)o=(0,W.and)(o,Dl(c,e,r,n));return o}i(Nl,"checkDataTypes");We.checkDataTypes=Nl;var VE={message:i(({schema:t})=>`must be ${t}`,"message"),params:i(({schema:t,schemaValue:e})=>typeof t=="string"?(0,W._)`{type: ${t}}`:(0,W._)`{type: ${e}}`,"params")};function jl(t){let e=FE(t);(0,DE.reportError)(e,VE)}i(jl,"reportTypeError");We.reportTypeError=jl;function FE(t){let{gen:e,data:r,schema:n}=t,o=(0,fh.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}i(FE,"getTypeErrorContext")});var yh=O(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.assignDefaults=void 0;var Xn=B(),HE=oe();function ZE(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)gh(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>gh(t,s,o.default))}i(ZE,"assignDefaults");ia.assignDefaults=ZE;function gh(t,e,r){let{gen:n,compositeRule:o,data:s,opts:c}=t;if(r===void 0)return;let l=(0,Xn._)`${s}${(0,Xn.getProperty)(e)}`;if(o){(0,HE.checkStrictMode)(t,`default is ignored for: ${l}`);return}let d=(0,Xn._)`${l} === undefined`;c.useDefaults==="empty"&&(d=(0,Xn._)`${d} || ${l} === null || ${l} === ""`),n.if(d,(0,Xn._)`${l} = ${(0,Xn.stringify)(r)}`)}i(gh,"assignDefault")});var wt=O(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=B(),ql=oe(),br=or(),KE=oe();function GE(t,e){let{gen:r,data:n,it:o}=t;r.if(Ul(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}i(GE,"checkReportMissingProp");ue.checkReportMissingProp=GE;function WE({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(Ul(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}i(WE,"checkMissingProp");ue.checkMissingProp=WE;function BE(t,e){t.setParams({missingProperty:e},!0),t.error()}i(BE,"reportMissingProp");ue.reportMissingProp=BE;function _h(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}i(_h,"hasPropFunc");ue.hasPropFunc=_h;function Ll(t,e,r){return(0,ge._)`${_h(t)}.call(${e}, ${r})`}i(Ll,"isOwnProperty");ue.isOwnProperty=Ll;function JE(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${Ll(t,e,r)}`:o}i(JE,"propertyInData");ue.propertyInData=JE;function Ul(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(Ll(t,e,r))):o}i(Ul,"noPropertyInData");ue.noPropertyInData=Ul;function vh(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}i(vh,"allSchemaProperties");ue.allSchemaProperties=vh;function YE(t,e){return vh(e).filter(r=>!(0,ql.alwaysValidSchema)(t,e[r]))}i(YE,"schemaProperties");ue.schemaProperties=YE;function XE({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:c},l,d,u){let p=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,m=[[br.default.instancePath,(0,ge.strConcat)(br.default.instancePath,s)],[br.default.parentData,c.parentData],[br.default.parentDataProperty,c.parentDataProperty],[br.default.rootData,br.default.rootData]];c.opts.dynamicRef&&m.push([br.default.dynamicAnchors,br.default.dynamicAnchors]);let g=(0,ge._)`${p}, ${r.object(...m)}`;return d!==ge.nil?(0,ge._)`${l}.call(${d}, ${g})`:(0,ge._)`${l}(${g})`}i(XE,"callValidateCode");ue.callValidateCode=XE;var QE=(0,ge._)`new RegExp`;function ex({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?QE:(0,KE.useFunc)(t,o)}(${r}, ${n})`})}i(ex,"usePattern");ue.usePattern=ex;function tx(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let l=e.let("valid",!0);return c(()=>e.assign(l,!1)),l}return e.var(s,!0),c(()=>e.break()),s;function c(l){let d=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,d,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ql.Type.Num},s),e.if((0,ge.not)(s),l)})}i(c,"validateItems")}i(tx,"validateArray");ue.validateArray=tx;function rx(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(d=>(0,ql.alwaysValidSchema)(o,d))&&!o.opts.unevaluated)return;let c=e.let("valid",!1),l=e.name("_valid");e.block(()=>r.forEach((d,u)=>{let p=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},l);e.assign(c,(0,ge._)`${c} || ${l}`),t.mergeValidEvaluated(p,l)||e.if((0,ge.not)(c))})),t.result(c,()=>t.reset(),()=>t.error(!0))}i(rx,"validateUnion");ue.validateUnion=rx});var bh=O(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.validateKeywordUsage=Ut.validSchemaType=Ut.funcKeywordCode=Ut.macroKeywordCode=void 0;var Xe=B(),Br=or(),nx=wt(),ox=ki();function ix(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:c}=t,l=e.macro.call(c.self,o,s,c),d=wh(r,n,l);c.opts.validateSchema!==!1&&c.self.validateSchema(l,!0);let u=r.name("valid");t.subschema({schema:l,schemaPath:Xe.nil,errSchemaPath:`${c.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}i(ix,"macroKeywordCode");Ut.macroKeywordCode=ix;function sx(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:c,$data:l,it:d}=t;cx(d,e);let u=!l&&e.compile?e.compile.call(d.self,s,c,d):e.validate,p=wh(n,o,u),m=n.let("valid");t.block$data(m,g),t.ok((r=e.valid)!==null&&r!==void 0?r:m);function g(){if(e.errors===!1)_(),e.modifying&&Sh(t),S(()=>t.error());else{let E=e.async?y():h();e.modifying&&Sh(t),S(()=>ax(t,E))}}i(g,"validateKeyword");function y(){let E=n.let("ruleErrs",null);return n.try(()=>_((0,Xe._)`await `),x=>n.assign(m,!1).if((0,Xe._)`${x} instanceof ${d.ValidationError}`,()=>n.assign(E,(0,Xe._)`${x}.errors`),()=>n.throw(x))),E}i(y,"validateAsync");function h(){let E=(0,Xe._)`${p}.errors`;return n.assign(E,null),_(Xe.nil),E}i(h,"validateSync");function _(E=e.async?(0,Xe._)`await `:Xe.nil){let x=d.opts.passContext?Br.default.this:Br.default.self,w=!("compile"in e&&!l||e.schema===!1);n.assign(m,(0,Xe._)`${E}${(0,nx.callValidateCode)(t,p,x,w)}`,e.modifying)}i(_,"assignValid");function S(E){var x;n.if((0,Xe.not)((x=e.valid)!==null&&x!==void 0?x:m),E)}i(S,"reportErrs")}i(sx,"funcKeywordCode");Ut.funcKeywordCode=sx;function Sh(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Xe._)`${n.parentData}[${n.parentDataProperty}]`))}i(Sh,"modifyData");function ax(t,e){let{gen:r}=t;r.if((0,Xe._)`Array.isArray(${e})`,()=>{r.assign(Br.default.vErrors,(0,Xe._)`${Br.default.vErrors} === null ? ${e} : ${Br.default.vErrors}.concat(${e})`).assign(Br.default.errors,(0,Xe._)`${Br.default.vErrors}.length`),(0,ox.extendErrors)(t)},()=>t.error())}i(ax,"addErrs");function cx({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}i(cx,"checkAsyncKeyword");function wh(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Xe.stringify)(r)})}i(wh,"useKeyword");function lx(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}i(lx,"validSchemaType");Ut.validSchemaType=lx;function dx({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let c=o.dependencies;if(c?.some(l=>!Object.prototype.hasOwnProperty.call(t,l)))throw new Error(`parent schema must have dependencies of ${s}: ${c.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let d=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(d);else throw new Error(d)}}i(dx,"validateKeywordUsage");Ut.validateKeywordUsage=dx});var Eh=O(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.extendSubschemaMode=kr.extendSubschemaData=kr.getSubschema=void 0;var Vt=B(),kh=oe();function ux(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let l=t.schema[e];return r===void 0?{schema:l,schemaPath:(0,Vt._)`${t.schemaPath}${(0,Vt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:l[r],schemaPath:(0,Vt._)`${t.schemaPath}${(0,Vt.getProperty)(e)}${(0,Vt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,kh.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||c===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}i(ux,"getSubschema");kr.getSubschema=ux;function px(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:l}=e;if(r!==void 0){let{errorPath:u,dataPathArr:p,opts:m}=e,g=l.let("data",(0,Vt._)`${e.data}${(0,Vt.getProperty)(r)}`,!0);d(g),t.errorPath=(0,Vt.str)`${u}${(0,kh.getErrorPath)(r,n,m.jsPropertySyntax)}`,t.parentDataProperty=(0,Vt._)`${r}`,t.dataPathArr=[...p,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Vt.Name?o:l.let("data",o,!0);d(u),c!==void 0&&(t.propertyName=c)}s&&(t.dataTypes=s);function d(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}i(d,"dataContextProps")}i(px,"extendSubschemaData");kr.extendSubschemaData=px;function fx(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}i(fx,"extendSubschemaMode");kr.extendSubschemaMode=fx});var Vl=O((RZ,xh)=>{"use strict";xh.exports=i(function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var c=s[o];if(!t(e[c],r[c]))return!1}return!0}return e!==e&&r!==r},"equal")});var Rh=O((CZ,Ph)=>{"use strict";var Er=Ph.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};sa(e,n,o,t,"",t)};Er.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Er.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Er.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Er.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function sa(t,e,r,n,o,s,c,l,d,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,c,l,d,u);for(var p in n){var m=n[p];if(Array.isArray(m)){if(p in Er.arrayKeywords)for(var g=0;g<m.length;g++)sa(t,e,r,m[g],o+"/"+p+"/"+g,s,o,p,n,g)}else if(p in Er.propsKeywords){if(m&&typeof m=="object")for(var y in m)sa(t,e,r,m[y],o+"/"+p+"/"+mx(y),s,o,p,n,y)}else(p in Er.keywords||t.allKeys&&!(p in Er.skipKeywords))&&sa(t,e,r,m,o+"/"+p,s,o,p,n)}r(n,o,s,c,l,d,u)}}i(sa,"_traverse");function mx(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}i(mx,"escapeJsonPtr")});var xi=O(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.getSchemaRefs=nt.resolveUrl=nt.normalizeId=nt._getFullPath=nt.getFullPath=nt.inlineRef=void 0;var hx=oe(),gx=Vl(),yx=Rh(),_x=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function vx(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Fl(t):e?Ih(t)<=e:!1}i(vx,"inlineRef");nt.inlineRef=vx;var Sx=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Fl(t){for(let e in t){if(Sx.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Fl)||typeof r=="object"&&Fl(r))return!0}return!1}i(Fl,"hasRef");function Ih(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!_x.has(r)&&(typeof t[r]=="object"&&(0,hx.eachItem)(t[r],n=>e+=Ih(n)),e===1/0))return 1/0}return e}i(Ih,"countKeys");function Ch(t,e="",r){r!==!1&&(e=Qn(e));let n=t.parse(e);return $h(t,n)}i(Ch,"getFullPath");nt.getFullPath=Ch;function $h(t,e){return t.serialize(e).split("#")[0]+"#"}i($h,"_getFullPath");nt._getFullPath=$h;var wx=/#\/?$/;function Qn(t){return t?t.replace(wx,""):""}i(Qn,"normalizeId");nt.normalizeId=Qn;function bx(t,e,r){return r=Qn(r),t.resolve(e,r)}i(bx,"resolveUrl");nt.resolveUrl=bx;var kx=/^[a-z_][-a-z0-9._]*$/i;function Ex(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Qn(t[r]||e),s={"":o},c=Ch(n,o,!1),l={},d=new Set;return yx(t,{allKeys:!0},(m,g,y,h)=>{if(h===void 0)return;let _=c+g,S=s[h];typeof m[r]=="string"&&(S=E.call(this,m[r])),x.call(this,m.$anchor),x.call(this,m.$dynamicAnchor),s[g]=S;function E(w){let P=this.opts.uriResolver.resolve;if(w=Qn(S?P(S,w):w),d.has(w))throw p(w);d.add(w);let I=this.refs[w];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?u(m,I.schema,w):w!==Qn(_)&&(w[0]==="#"?(u(m,l[w],w),l[w]=m):this.refs[w]=_),w}i(E,"addRef");function x(w){if(typeof w=="string"){if(!kx.test(w))throw new Error(`invalid anchor "${w}"`);E.call(this,`#${w}`)}}i(x,"addAnchor")}),l;function u(m,g,y){if(g!==void 0&&!gx(m,g))throw p(y)}i(u,"checkAmbiguosRef");function p(m){return new Error(`reference "${m}" resolves to more than one schema`)}i(p,"ambiguos")}i(Ex,"getSchemaRefs");nt.getSchemaRefs=Ex});var Ii=O(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.getData=xr.KeywordCxt=xr.validateFunctionCode=void 0;var zh=dh(),Th=Ei(),Zl=zl(),aa=Ei(),xx=yh(),Ri=bh(),Hl=Eh(),z=B(),U=or(),Px=xi(),ir=oe(),Pi=ki();function Rx(t){if(jh(t)&&(qh(t),Nh(t))){$x(t);return}Dh(t,()=>(0,zh.topBoolOrEmptySchema)(t))}i(Rx,"validateFunctionCode");xr.validateFunctionCode=Rx;function Dh({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,z._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{t.code((0,z._)`"use strict"; ${Oh(r,o)}`),Cx(t,o),t.code(s)}):t.func(e,(0,z._)`${U.default.data}, ${Ix(o)}`,n.$async,()=>t.code(Oh(r,o)).code(s))}i(Dh,"validateFunction");function Ix(t){return(0,z._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${t.dynamicRef?(0,z._)`, ${U.default.dynamicAnchors}={}`:z.nil}}={}`}i(Ix,"destructureValCxt");function Cx(t,e){t.if(U.default.valCxt,()=>{t.var(U.default.instancePath,(0,z._)`${U.default.valCxt}.${U.default.instancePath}`),t.var(U.default.parentData,(0,z._)`${U.default.valCxt}.${U.default.parentData}`),t.var(U.default.parentDataProperty,(0,z._)`${U.default.valCxt}.${U.default.parentDataProperty}`),t.var(U.default.rootData,(0,z._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,z._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{t.var(U.default.instancePath,(0,z._)`""`),t.var(U.default.parentData,(0,z._)`undefined`),t.var(U.default.parentDataProperty,(0,z._)`undefined`),t.var(U.default.rootData,U.default.data),e.dynamicRef&&t.var(U.default.dynamicAnchors,(0,z._)`{}`)})}i(Cx,"destructureValCxtES5");function $x(t){let{schema:e,opts:r,gen:n}=t;Dh(t,()=>{r.$comment&&e.$comment&&Uh(t),zx(t),n.let(U.default.vErrors,null),n.let(U.default.errors,0),r.unevaluated&&Tx(t),Lh(t),jx(t)})}i($x,"topSchemaObjCode");function Tx(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,z._)`${r}.evaluated`),e.if((0,z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,z._)`${t.evaluated}.props`,(0,z._)`undefined`)),e.if((0,z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,z._)`${t.evaluated}.items`,(0,z._)`undefined`))}i(Tx,"resetEvaluated");function Oh(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,z._)`/*# sourceURL=${r} */`:z.nil}i(Oh,"funcSourceUrl");function Ox(t,e){if(jh(t)&&(qh(t),Nh(t))){Ax(t,e);return}(0,zh.boolOrEmptySchema)(t,e)}i(Ox,"subschemaCode");function Nh({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}i(Nh,"schemaCxtHasRules");function jh(t){return typeof t.schema!="boolean"}i(jh,"isSchemaObj");function Ax(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Uh(t),Dx(t),Nx(t);let s=n.const("_errs",U.default.errors);Lh(t,s),n.var(e,(0,z._)`${s} === ${U.default.errors}`)}i(Ax,"subSchemaObjCode");function qh(t){(0,ir.checkUnknownRules)(t),Mx(t)}i(qh,"checkKeywords");function Lh(t,e){if(t.opts.jtd)return Ah(t,[],!1,e);let r=(0,Th.getSchemaTypes)(t.schema),n=(0,Th.coerceAndCheckDataType)(t,r);Ah(t,r,!n,e)}i(Lh,"typeAndKeywords");function Mx(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ir.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}i(Mx,"checkRefsAndKeywords");function zx(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ir.checkStrictMode)(t,"default is ignored in the schema root")}i(zx,"checkNoDefault");function Dx(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Px.resolveUrl)(t.opts.uriResolver,t.baseId,e))}i(Dx,"updateContext");function Nx(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}i(Nx,"checkAsyncSchema");function Uh({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,z._)`${U.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let c=(0,z.str)`${n}/$comment`,l=t.scopeValue("root",{ref:e.root});t.code((0,z._)`${U.default.self}.opts.$comment(${s}, ${c}, ${l}.schema)`)}}i(Uh,"commentKeyword");function jx(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,z._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,z._)`new ${o}(${U.default.vErrors})`)):(e.assign((0,z._)`${n}.errors`,U.default.vErrors),s.unevaluated&&qx(t),e.return((0,z._)`${U.default.errors} === 0`))}i(jx,"returnResults");function qx({gen:t,evaluated:e,props:r,items:n}){r instanceof z.Name&&t.assign((0,z._)`${e}.props`,r),n instanceof z.Name&&t.assign((0,z._)`${e}.items`,n)}i(qx,"assignEvaluated");function Ah(t,e,r,n){let{gen:o,schema:s,data:c,allErrors:l,opts:d,self:u}=t,{RULES:p}=u;if(s.$ref&&(d.ignoreKeywordsWithRef||!(0,ir.schemaHasRulesButRef)(s,p))){o.block(()=>Fh(t,"$ref",p.all.$ref.definition));return}d.jtd||Lx(t,e),o.block(()=>{for(let g of p.rules)m(g);m(p.post)});function m(g){(0,Zl.shouldUseGroup)(s,g)&&(g.type?(o.if((0,aa.checkDataType)(g.type,c,d.strictNumbers)),Mh(t,g),e.length===1&&e[0]===g.type&&r&&(o.else(),(0,aa.reportTypeError)(t)),o.endIf()):Mh(t,g),l||o.if((0,z._)`${U.default.errors} === ${n||0}`))}i(m,"groupKeywords")}i(Ah,"schemaKeywords");function Mh(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,xx.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Zl.shouldUseRule)(n,s)&&Fh(t,s.keyword,s.definition,e.type)})}i(Mh,"iterateKeywords");function Lx(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Ux(t,e),t.opts.allowUnionTypes||Vx(t,e),Fx(t,t.dataTypes))}i(Lx,"checkStrictTypes");function Ux(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Vh(t.dataTypes,r)||Kl(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Zx(t,e)}}i(Ux,"checkContextTypes");function Vx(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Kl(t,"use allowUnionTypes to allow union type keyword")}i(Vx,"checkMultipleTypes");function Fx(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Zl.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(c=>Hx(e,c))&&Kl(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}i(Fx,"checkKeywordTypes");function Hx(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}i(Hx,"hasApplicableType");function Vh(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}i(Vh,"includesType");function Zx(t,e){let r=[];for(let n of t.dataTypes)Vh(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}i(Zx,"narrowSchemaTypes");function Kl(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ir.checkStrictMode)(t,e,t.opts.strictTypes)}i(Kl,"strictTypesError");var ca=class{static{i(this,"KeywordCxt")}constructor(e,r,n){if((0,Ri.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ir.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Hh(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ri.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",U.default.errors))}result(e,r,n){this.failResult((0,z.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,z.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,z._)`${r} !== undefined && (${(0,z.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Pi.reportExtraError:Pi.reportError)(this,this.def.error,r)}$dataError(){(0,Pi.reportError)(this,this.def.$dataError||Pi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Pi.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=z.nil,r=z.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:c}=this;n.if((0,z.or)((0,z._)`${o} === undefined`,r)),e!==z.nil&&n.assign(e,!0),(s.length||c.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,z.or)(c(),l());function c(){if(n.length){if(!(r instanceof z.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,z._)`${(0,aa.checkDataTypes)(d,r,s.opts.strictNumbers,aa.DataType.Wrong)}`}return z.nil}function l(){if(o.validateSchema){let d=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,z._)`!${d}(${r})`}return z.nil}}subschema(e,r){let n=(0,Hl.getSubschema)(this.it,e);(0,Hl.extendSubschemaData)(n,this.it,e),(0,Hl.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Ox(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ir.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ir.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,z.Name)),!0}};xr.KeywordCxt=ca;function Fh(t,e,r,n){let o=new ca(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ri.funcKeywordCode)(o,r):"macro"in r?(0,Ri.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ri.funcKeywordCode)(o,r)}i(Fh,"keywordCode");var Kx=/^\/(?:[^~]|~0|~1)*$/,Gx=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Hh(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return U.default.rootData;if(t[0]==="/"){if(!Kx.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=U.default.rootData}else{let u=Gx.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+u[1];if(o=u[2],o==="#"){if(p>=e)throw new Error(d("property/index",p));return n[e-p]}if(p>e)throw new Error(d("data",p));if(s=r[e-p],!o)return s}let c=s,l=o.split("/");for(let u of l)u&&(s=(0,z._)`${s}${(0,z.getProperty)((0,ir.unescapeJsonPointer)(u))}`,c=(0,z._)`${c} && ${s}`);return c;function d(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}i(Hh,"getData");xr.getData=Hh});var la=O(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});var Gl=class extends Error{static{i(this,"ValidationError")}constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Wl.default=Gl});var Ci=O(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var Bl=xi(),Jl=class extends Error{static{i(this,"MissingRefError")}constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Bl.resolveUrl)(e,r,n),this.missingSchema=(0,Bl.normalizeId)((0,Bl.getFullPath)(e,this.missingRef))}};Yl.default=Jl});var ua=O(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.resolveSchema=bt.getCompilingSchema=bt.resolveRef=bt.compileSchema=bt.SchemaEnv=void 0;var Ct=B(),Wx=la(),Jr=or(),$t=xi(),Zh=oe(),Bx=Ii(),eo=class{static{i(this,"SchemaEnv")}constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,$t.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};bt.SchemaEnv=eo;function Ql(t){let e=Kh.call(this,t);if(e)return e;let r=(0,$t.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,c=new Ct.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),l;t.$async&&(l=c.scopeValue("Error",{ref:Wx.default,code:(0,Ct._)`require("ajv/dist/runtime/validation_error").default`}));let d=c.scopeName("validate");t.validateName=d;let u={gen:c,allErrors:this.opts.allErrors,data:Jr.default.data,parentData:Jr.default.parentData,parentDataProperty:Jr.default.parentDataProperty,dataNames:[Jr.default.data],dataPathArr:[Ct.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:c.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Ct.stringify)(t.schema)}:{ref:t.schema}),validateName:d,ValidationError:l,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Ct.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ct._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,Bx.validateFunctionCode)(u),c.optimize(this.opts.code.optimize);let m=c.toString();p=`${c.scopeRefs(Jr.default.scope)}return ${m}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let y=new Function(`${Jr.default.self}`,`${Jr.default.scope}`,p)(this,this.scope.get());if(this.scope.value(d,{ref:y}),y.errors=null,y.schema=t.schema,y.schemaEnv=t,t.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:d,validateCode:m,scopeValues:c._values}),this.opts.unevaluated){let{props:h,items:_}=u;y.evaluated={props:h instanceof Ct.Name?void 0:h,items:_ instanceof Ct.Name?void 0:_,dynamicProps:h instanceof Ct.Name,dynamicItems:_ instanceof Ct.Name},y.source&&(y.source.evaluated=(0,Ct.stringify)(y.evaluated))}return t.validate=y,t}catch(m){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),m}finally{this._compilations.delete(t)}}i(Ql,"compileSchema");bt.compileSchema=Ql;function Jx(t,e,r){var n;r=(0,$t.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Qx.call(this,t,r);if(s===void 0){let c=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:l}=this.opts;c&&(s=new eo({schema:c,schemaId:l,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Yx.call(this,s)}i(Jx,"resolveRef");bt.resolveRef=Jx;function Yx(t){return(0,$t.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ql.call(this,t)}i(Yx,"inlineOrCompile");function Kh(t){for(let e of this._compilations)if(Xx(e,t))return e}i(Kh,"getCompilingSchema");bt.getCompilingSchema=Kh;function Xx(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}i(Xx,"sameSchemaEnv");function Qx(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||da.call(this,t,e)}i(Qx,"resolve");function da(t,e){let r=this.opts.uriResolver.parse(e),n=(0,$t._getFullPath)(this.opts.uriResolver,r),o=(0,$t.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Xl.call(this,r,t);let s=(0,$t.normalizeId)(n),c=this.refs[s]||this.schemas[s];if(typeof c=="string"){let l=da.call(this,t,c);return typeof l?.schema!="object"?void 0:Xl.call(this,r,l)}if(typeof c?.schema=="object"){if(c.validate||Ql.call(this,c),s===(0,$t.normalizeId)(e)){let{schema:l}=c,{schemaId:d}=this.opts,u=l[d];return u&&(o=(0,$t.resolveUrl)(this.opts.uriResolver,o,u)),new eo({schema:l,schemaId:d,root:t,baseId:o})}return Xl.call(this,r,c)}}i(da,"resolveSchema");bt.resolveSchema=da;var e0=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Xl(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let l of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let d=r[(0,Zh.unescapeFragment)(l)];if(d===void 0)return;r=d;let u=typeof r=="object"&&r[this.opts.schemaId];!e0.has(l)&&u&&(e=(0,$t.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Zh.schemaHasRulesButRef)(r,this.RULES)){let l=(0,$t.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=da.call(this,n,l)}let{schemaId:c}=this.opts;if(s=s||new eo({schema:r,schemaId:c,root:n,baseId:e}),s.schema!==s.root.schema)return s}i(Xl,"getJsonPointer")});var Gh=O((UZ,t0)=>{t0.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var td=O((VZ,Yh)=>{"use strict";var r0=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Bh=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function ed(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}i(ed,"stringArrayToHexStripped");var n0=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Wh(t){return t.length=0,!0}i(Wh,"consumeIsZone");function o0(t,e,r){if(t.length){let n=ed(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}i(o0,"consumeHextets");function i0(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,c=!1,l=o0;for(let d=0;d<t.length;d++){let u=t[d];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(c=!0),!l(o,n,r))break;if(++e>7){r.error=!0;break}d>0&&t[d-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!l(o,n,r))break;l=Wh}else{o.push(u);continue}}return o.length&&(l===Wh?r.zone=o.join(""):c?n.push(o.join("")):n.push(ed(o))),r.address=n.join(""),r}i(i0,"getIPV6");function Jh(t){if(s0(t,":")<2)return{host:t,isIPV6:!1};let e=i0(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}i(Jh,"normalizeIPv6");function s0(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}i(s0,"findToken");function a0(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}i(a0,"removeDotSegments");function c0(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}i(c0,"normalizeComponentEncoding");function l0(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Bh(r)){let n=Jh(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}i(l0,"recomposeAuthority");Yh.exports={nonSimpleDomain:n0,recomposeAuthority:l0,normalizeComponentEncoding:c0,removeDotSegments:a0,isIPv4:Bh,isUUID:r0,normalizeIPv6:Jh,stringArrayToHexStripped:ed}});var rg=O((HZ,tg)=>{"use strict";var{isUUID:d0}=td(),u0=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,p0=["http","https","ws","wss","urn","urn:uuid"];function f0(t){return p0.indexOf(t)!==-1}i(f0,"isValidSchemeName");function rd(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}i(rd,"wsIsSecure");function Xh(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}i(Xh,"httpParse");function Qh(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}i(Qh,"httpSerialize");function m0(t){return t.secure=rd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}i(m0,"wsParse");function h0(t){if((t.port===(rd(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}i(h0,"wsSerialize");function g0(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(u0);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=nd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}i(g0,"urnParse");function y0(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=nd(o);s&&(t=s.serialize(t,e));let c=t,l=t.nss;return c.path=`${n||e.nid}:${l}`,e.skipEscape=!0,c}i(y0,"urnSerialize");function _0(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!d0(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}i(_0,"urnuuidParse");function v0(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}i(v0,"urnuuidSerialize");var eg={scheme:"http",domainHost:!0,parse:Xh,serialize:Qh},S0={scheme:"https",domainHost:eg.domainHost,parse:Xh,serialize:Qh},pa={scheme:"ws",domainHost:!0,parse:m0,serialize:h0},w0={scheme:"wss",domainHost:pa.domainHost,parse:pa.parse,serialize:pa.serialize},b0={scheme:"urn",parse:g0,serialize:y0,skipNormalize:!0},k0={scheme:"urn:uuid",parse:_0,serialize:v0,skipNormalize:!0},fa={http:eg,https:S0,ws:pa,wss:w0,urn:b0,"urn:uuid":k0};Object.setPrototypeOf(fa,null);function nd(t){return t&&(fa[t]||fa[t.toLowerCase()])||void 0}i(nd,"getSchemeHandler");tg.exports={wsIsSecure:rd,SCHEMES:fa,isValidSchemeName:f0,getSchemeHandler:nd}});var ig=O((KZ,ha)=>{"use strict";var{normalizeIPv6:E0,removeDotSegments:$i,recomposeAuthority:x0,normalizeComponentEncoding:ma,isIPv4:P0,nonSimpleDomain:R0}=td(),{SCHEMES:I0,getSchemeHandler:ng}=rg();function C0(t,e){return typeof t=="string"?t=Ft(sr(t,e),e):typeof t=="object"&&(t=sr(Ft(t,e),e)),t}i(C0,"normalize");function $0(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=og(sr(t,n),sr(e,n),n,!0);return n.skipEscape=!0,Ft(o,n)}i($0,"resolve");function og(t,e,r,n){let o={};return n||(t=sr(Ft(t,r),r),e=sr(Ft(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=$i(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=$i(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=$i(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=$i(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}i(og,"resolveComponent");function T0(t,e,r){return typeof t=="string"?(t=unescape(t),t=Ft(ma(sr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Ft(ma(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Ft(ma(sr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Ft(ma(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}i(T0,"equal");function Ft(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=ng(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let c=x0(r);if(c!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(c),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let l=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=$i(l)),c===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),o.push(l)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}i(Ft,"serialize");var O0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function sr(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(O0);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(P0(n.host)===!1){let d=E0(n.host);n.host=d.host.toLowerCase(),o=d.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let c=ng(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&o===!1&&R0(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}(!c||c&&!c.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}i(sr,"parse");var od={SCHEMES:I0,normalize:C0,resolve:$0,resolveComponent:og,equal:T0,serialize:Ft,parse:sr};ha.exports=od;ha.exports.default=od;ha.exports.fastUri=od});var ag=O(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var sg=ig();sg.code='require("ajv/dist/runtime/uri").default';id.default=sg});var hg=O(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CodeGen=Ue.Name=Ue.nil=Ue.stringify=Ue.str=Ue._=Ue.KeywordCxt=void 0;var A0=Ii();Object.defineProperty(Ue,"KeywordCxt",{enumerable:!0,get:i(function(){return A0.KeywordCxt},"get")});var to=B();Object.defineProperty(Ue,"_",{enumerable:!0,get:i(function(){return to._},"get")});Object.defineProperty(Ue,"str",{enumerable:!0,get:i(function(){return to.str},"get")});Object.defineProperty(Ue,"stringify",{enumerable:!0,get:i(function(){return to.stringify},"get")});Object.defineProperty(Ue,"nil",{enumerable:!0,get:i(function(){return to.nil},"get")});Object.defineProperty(Ue,"Name",{enumerable:!0,get:i(function(){return to.Name},"get")});Object.defineProperty(Ue,"CodeGen",{enumerable:!0,get:i(function(){return to.CodeGen},"get")});var M0=la(),pg=Ci(),z0=Ml(),Ti=ua(),D0=B(),Oi=xi(),ga=Ei(),ad=oe(),cg=Gh(),N0=ag(),fg=i((t,e)=>new RegExp(t,e),"defaultRegExp");fg.code="new RegExp";var j0=["removeAdditional","useDefaults","coerceTypes"],q0=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),L0={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},U0={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},lg=200;function V0(t){var e,r,n,o,s,c,l,d,u,p,m,g,y,h,_,S,E,x,w,P,I,L,F,Be,Gt;let xt=t.strict,Tr=(e=t.code)===null||e===void 0?void 0:e.optimize,ps=Tr===!0||Tr===void 0?1:Tr||0,fs=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:fg,ms=(o=t.uriResolver)!==null&&o!==void 0?o:N0.default;return{strictSchema:(c=(s=t.strictSchema)!==null&&s!==void 0?s:xt)!==null&&c!==void 0?c:!0,strictNumbers:(d=(l=t.strictNumbers)!==null&&l!==void 0?l:xt)!==null&&d!==void 0?d:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:xt)!==null&&p!==void 0?p:"log",strictTuples:(g=(m=t.strictTuples)!==null&&m!==void 0?m:xt)!==null&&g!==void 0?g:"log",strictRequired:(h=(y=t.strictRequired)!==null&&y!==void 0?y:xt)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:ps,regExp:fs}:{optimize:ps,regExp:fs},loopRequired:(_=t.loopRequired)!==null&&_!==void 0?_:lg,loopEnum:(S=t.loopEnum)!==null&&S!==void 0?S:lg,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(x=t.messages)!==null&&x!==void 0?x:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(P=t.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(I=t.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(L=t.validateSchema)!==null&&L!==void 0?L:!0,validateFormats:(F=t.validateFormats)!==null&&F!==void 0?F:!0,unicodeRegExp:(Be=t.unicodeRegExp)!==null&&Be!==void 0?Be:!0,int32range:(Gt=t.int32range)!==null&&Gt!==void 0?Gt:!0,uriResolver:ms}}i(V0,"requiredOptions");var Ai=class{static{i(this,"Ajv")}constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...V0(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new D0.ValueScope({scope:{},prefixes:q0,es5:r,lines:n}),this.logger=W0(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,z0.getRules)(),dg.call(this,L0,e,"NOT SUPPORTED"),dg.call(this,U0,e,"DEPRECATED","warn"),this._metaOpts=K0.call(this),e.formats&&H0.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Z0.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),F0.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=cg;n==="id"&&(o={...cg},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(p,m){await s.call(this,p.$schema);let g=this._addSchema(p,m);return g.validate||c.call(this,g)}async function s(p){p&&!this.getSchema(p)&&await o.call(this,{$ref:p},!0)}async function c(p){try{return this._compileSchemaEnv(p)}catch(m){if(!(m instanceof pg.default))throw m;return l.call(this,m),await d.call(this,m.missingSchema),c.call(this,p)}}function l({missingSchema:p,missingRef:m}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${m} cannot be resolved`)}async function d(p){let m=await u.call(this,p);this.refs[p]||await s.call(this,m.$schema),this.refs[p]||this.addSchema(m,p,r)}async function u(p){let m=this._loading[p];if(m)return m;try{return await(this._loading[p]=n(p))}finally{delete this._loading[p]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let c of e)this.addSchema(c,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:c}=this.opts;if(s=e[c],s!==void 0&&typeof s!="string")throw new Error(`schema ${c} must be string`)}return r=(0,Oi.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=ug.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Ti.SchemaEnv({schema:{},schemaId:n});if(r=Ti.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=ug.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Oi.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(J0.call(this,n,r),!r)return(0,ad.eachItem)(n,s=>sd.call(this,s)),this;X0.call(this,r);let o={...r,type:(0,ga.getJSONTypes)(r.type),schemaType:(0,ga.getJSONTypes)(r.schemaType)};return(0,ad.eachItem)(n,o.type.length===0?s=>sd.call(this,s,o):s=>o.type.forEach(c=>sd.call(this,s,o,c))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),c=e;for(let l of s)c=c[l];for(let l in n){let d=n[l];if(typeof d!="object")continue;let{$data:u}=d.definition,p=c[l];u&&p&&(c[l]=mg(p))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let c,{schemaId:l}=this.opts;if(typeof e=="object")c=e[l];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let d=this._cache.get(e);if(d!==void 0)return d;n=(0,Oi.normalizeId)(c||n);let u=Oi.getSchemaRefs.call(this,e,n);return d=new Ti.SchemaEnv({schema:e,schemaId:l,meta:r,baseId:n,localRefs:u}),this._cache.set(d.schema,d),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=d),o&&this.validateSchema(e,!0),d}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Ti.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Ti.compileSchema.call(this,e)}finally{this.opts=r}}};Ai.ValidationError=M0.default;Ai.MissingRefError=pg.default;Ue.default=Ai;function dg(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}i(dg,"checkOptions");function ug(t){return t=(0,Oi.normalizeId)(t),this.schemas[t]||this.refs[t]}i(ug,"getSchEnv");function F0(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}i(F0,"addInitialSchemas");function H0(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}i(H0,"addInitialFormats");function Z0(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}i(Z0,"addInitialKeywords");function K0(){let t={...this.opts};for(let e of j0)delete t[e];return t}i(K0,"getMetaSchemaOptions");var G0={log(){},warn(){},error(){}};function W0(t){if(t===!1)return G0;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}i(W0,"getLogger");var B0=/^[a-z_$][a-z0-9_$:-]*$/i;function J0(t,e){let{RULES:r}=this;if((0,ad.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!B0.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}i(J0,"checkKeyword");function sd(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,c=o?s.post:s.rules.find(({type:d})=>d===r);if(c||(c={type:r,rules:[]},s.rules.push(c)),s.keywords[t]=!0,!e)return;let l={keyword:t,definition:{...e,type:(0,ga.getJSONTypes)(e.type),schemaType:(0,ga.getJSONTypes)(e.schemaType)}};e.before?Y0.call(this,c,l,e.before):c.rules.push(l),s.all[t]=l,(n=e.implements)===null||n===void 0||n.forEach(d=>this.addKeyword(d))}i(sd,"addRule");function Y0(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}i(Y0,"addBeforeRule");function X0(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=mg(e)),t.validateSchema=this.compile(e,!0))}i(X0,"keywordMetaschema");var Q0={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function mg(t){return{anyOf:[t,Q0]}}i(mg,"schemaOrData")});var gg=O(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var eP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};cd.default=eP});var Sg=O(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.callRef=Yr.getValidate=void 0;var tP=Ci(),yg=wt(),ot=B(),ro=or(),_g=ua(),ya=oe(),rP={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:c,opts:l,self:d}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return m();let p=_g.resolveRef.call(d,u,o,r);if(p===void 0)throw new tP.default(n.opts.uriResolver,o,r);if(p instanceof _g.SchemaEnv)return g(p);return y(p);function m(){if(s===u)return _a(t,c,s,s.$async);let h=e.scopeValue("root",{ref:u});return _a(t,(0,ot._)`${h}.validate`,u,u.$async)}function g(h){let _=vg(t,h);_a(t,_,h,h.$async)}function y(h){let _=e.scopeValue("schema",l.code.source===!0?{ref:h,code:(0,ot.stringify)(h)}:{ref:h}),S=e.name("valid"),E=t.subschema({schema:h,dataTypes:[],schemaPath:ot.nil,topSchemaRef:_,errSchemaPath:r},S);t.mergeEvaluated(E),t.ok(S)}}};function vg(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ot._)`${r.scopeValue("wrapper",{ref:e})}.validate`}i(vg,"getValidate");Yr.getValidate=vg;function _a(t,e,r,n){let{gen:o,it:s}=t,{allErrors:c,schemaEnv:l,opts:d}=s,u=d.passContext?ro.default.this:ot.nil;n?p():m();function p(){if(!l.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,ot._)`await ${(0,yg.callValidateCode)(t,e,u)}`),y(e),c||o.assign(h,!0)},_=>{o.if((0,ot._)`!(${_} instanceof ${s.ValidationError})`,()=>o.throw(_)),g(_),c||o.assign(h,!1)}),t.ok(h)}i(p,"callAsyncRef");function m(){t.result((0,yg.callValidateCode)(t,e,u),()=>y(e),()=>g(e))}i(m,"callSyncRef");function g(h){let _=(0,ot._)`${h}.errors`;o.assign(ro.default.vErrors,(0,ot._)`${ro.default.vErrors} === null ? ${_} : ${ro.default.vErrors}.concat(${_})`),o.assign(ro.default.errors,(0,ot._)`${ro.default.vErrors}.length`)}i(g,"addErrorsFrom");function y(h){var _;if(!s.opts.unevaluated)return;let S=(_=r?.validate)===null||_===void 0?void 0:_.evaluated;if(s.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(s.props=ya.mergeEvaluated.props(o,S.props,s.props));else{let E=o.var("props",(0,ot._)`${h}.evaluated.props`);s.props=ya.mergeEvaluated.props(o,E,s.props,ot.Name)}if(s.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(s.items=ya.mergeEvaluated.items(o,S.items,s.items));else{let E=o.var("items",(0,ot._)`${h}.evaluated.items`);s.items=ya.mergeEvaluated.items(o,E,s.items,ot.Name)}}i(y,"addEvaluatedFrom")}i(_a,"callRef");Yr.callRef=_a;Yr.default=rP});var wg=O(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var nP=gg(),oP=Sg(),iP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",nP.default,oP.default];ld.default=iP});var bg=O(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var va=B(),Pr=va.operators,Sa={maximum:{okStr:"<=",ok:Pr.LTE,fail:Pr.GT},minimum:{okStr:">=",ok:Pr.GTE,fail:Pr.LT},exclusiveMaximum:{okStr:"<",ok:Pr.LT,fail:Pr.GTE},exclusiveMinimum:{okStr:">",ok:Pr.GT,fail:Pr.LTE}},sP={message:i(({keyword:t,schemaCode:e})=>(0,va.str)`must be ${Sa[t].okStr} ${e}`,"message"),params:i(({keyword:t,schemaCode:e})=>(0,va._)`{comparison: ${Sa[t].okStr}, limit: ${e}}`,"params")},aP={keyword:Object.keys(Sa),type:"number",schemaType:"number",$data:!0,error:sP,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,va._)`${r} ${Sa[e].fail} ${n} || isNaN(${r})`)}};dd.default=aP});var kg=O(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var Mi=B(),cP={message:i(({schemaCode:t})=>(0,Mi.str)`must be multiple of ${t}`,"message"),params:i(({schemaCode:t})=>(0,Mi._)`{multipleOf: ${t}}`,"params")},lP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:cP,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,c=e.let("res"),l=s?(0,Mi._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${s}`:(0,Mi._)`${c} !== parseInt(${c})`;t.fail$data((0,Mi._)`(${n} === 0 || (${c} = ${r}/${n}, ${l}))`)}};ud.default=lP});var xg=O(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});function Eg(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}i(Eg,"ucs2length");pd.default=Eg;Eg.code='require("ajv/dist/runtime/ucs2length").default'});var Pg=O(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var Xr=B(),dP=oe(),uP=xg(),pP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Xr.str)`must NOT have ${r} than ${e} characters`},params:i(({schemaCode:t})=>(0,Xr._)`{limit: ${t}}`,"params")},fP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:pP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Xr.operators.GT:Xr.operators.LT,c=o.opts.unicode===!1?(0,Xr._)`${r}.length`:(0,Xr._)`${(0,dP.useFunc)(t.gen,uP.default)}(${r})`;t.fail$data((0,Xr._)`${c} ${s} ${n}`)}};fd.default=fP});var Rg=O(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var mP=wt(),hP=oe(),no=B(),gP={message:i(({schemaCode:t})=>(0,no.str)`must match pattern "${t}"`,"message"),params:i(({schemaCode:t})=>(0,no._)`{pattern: ${t}}`,"params")},yP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:gP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:c}=t,l=c.opts.unicodeRegExp?"u":"";if(n){let{regExp:d}=c.opts.code,u=d.code==="new RegExp"?(0,no._)`new RegExp`:(0,hP.useFunc)(e,d),p=e.let("valid");e.try(()=>e.assign(p,(0,no._)`${u}(${s}, ${l}).test(${r})`),()=>e.assign(p,!1)),t.fail$data((0,no._)`!${p}`)}else{let d=(0,mP.usePattern)(t,o);t.fail$data((0,no._)`!${d}.test(${r})`)}}};md.default=yP});var Ig=O(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var zi=B(),_P={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,zi.str)`must NOT have ${r} than ${e} properties`},params:i(({schemaCode:t})=>(0,zi._)`{limit: ${t}}`,"params")},vP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:_P,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?zi.operators.GT:zi.operators.LT;t.fail$data((0,zi._)`Object.keys(${r}).length ${o} ${n}`)}};hd.default=vP});var Cg=O(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var Di=wt(),Ni=B(),SP=oe(),wP={message:i(({params:{missingProperty:t}})=>(0,Ni.str)`must have required property '${t}'`,"message"),params:i(({params:{missingProperty:t}})=>(0,Ni._)`{missingProperty: ${t}}`,"params")},bP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:wP,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:c}=t,{opts:l}=c;if(!s&&r.length===0)return;let d=r.length>=l.loopRequired;if(c.allErrors?u():p(),l.strictRequired){let y=t.parentSchema.properties,{definedProperties:h}=t.it;for(let _ of r)if(y?.[_]===void 0&&!h.has(_)){let S=c.schemaEnv.baseId+c.errSchemaPath,E=`required property "${_}" is not defined at "${S}" (strictRequired)`;(0,SP.checkStrictMode)(c,E,c.opts.strictRequired)}}function u(){if(d||s)t.block$data(Ni.nil,m);else for(let y of r)(0,Di.checkReportMissingProp)(t,y)}i(u,"allErrorsMode");function p(){let y=e.let("missing");if(d||s){let h=e.let("valid",!0);t.block$data(h,()=>g(y,h)),t.ok(h)}else e.if((0,Di.checkMissingProp)(t,r,y)),(0,Di.reportMissingProp)(t,y),e.else()}i(p,"exitOnErrorMode");function m(){e.forOf("prop",n,y=>{t.setParams({missingProperty:y}),e.if((0,Di.noPropertyInData)(e,o,y,l.ownProperties),()=>t.error())})}i(m,"loopAllRequired");function g(y,h){t.setParams({missingProperty:y}),e.forOf(y,n,()=>{e.assign(h,(0,Di.propertyInData)(e,o,y,l.ownProperties)),e.if((0,Ni.not)(h),()=>{t.error(),e.break()})},Ni.nil)}i(g,"loopUntilMissing")}};gd.default=bP});var $g=O(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var ji=B(),kP={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ji.str)`must NOT have ${r} than ${e} items`},params:i(({schemaCode:t})=>(0,ji._)`{limit: ${t}}`,"params")},EP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:kP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ji.operators.GT:ji.operators.LT;t.fail$data((0,ji._)`${r}.length ${o} ${n}`)}};yd.default=EP});var wa=O(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var Tg=Vl();Tg.code='require("ajv/dist/runtime/equal").default';_d.default=Tg});var Og=O(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var vd=Ei(),Ve=B(),xP=oe(),PP=wa(),RP={message:i(({params:{i:t,j:e}})=>(0,Ve.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,"message"),params:i(({params:{i:t,j:e}})=>(0,Ve._)`{i: ${t}, j: ${e}}`,"params")},IP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:RP,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:c,it:l}=t;if(!n&&!o)return;let d=e.let("valid"),u=s.items?(0,vd.getSchemaTypes)(s.items):[];t.block$data(d,p,(0,Ve._)`${c} === false`),t.ok(d);function p(){let h=e.let("i",(0,Ve._)`${r}.length`),_=e.let("j");t.setParams({i:h,j:_}),e.assign(d,!0),e.if((0,Ve._)`${h} > 1`,()=>(m()?g:y)(h,_))}i(p,"validateUniqueItems");function m(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}i(m,"canOptimize");function g(h,_){let S=e.name("item"),E=(0,vd.checkDataTypes)(u,S,l.opts.strictNumbers,vd.DataType.Wrong),x=e.const("indices",(0,Ve._)`{}`);e.for((0,Ve._)`;${h}--;`,()=>{e.let(S,(0,Ve._)`${r}[${h}]`),e.if(E,(0,Ve._)`continue`),u.length>1&&e.if((0,Ve._)`typeof ${S} == "string"`,(0,Ve._)`${S} += "_"`),e.if((0,Ve._)`typeof ${x}[${S}] == "number"`,()=>{e.assign(_,(0,Ve._)`${x}[${S}]`),t.error(),e.assign(d,!1).break()}).code((0,Ve._)`${x}[${S}] = ${h}`)})}i(g,"loopN");function y(h,_){let S=(0,xP.useFunc)(e,PP.default),E=e.name("outer");e.label(E).for((0,Ve._)`;${h}--;`,()=>e.for((0,Ve._)`${_} = ${h}; ${_}--;`,()=>e.if((0,Ve._)`${S}(${r}[${h}], ${r}[${_}])`,()=>{t.error(),e.assign(d,!1).break(E)})))}i(y,"loopN2")}};Sd.default=IP});var Ag=O(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var wd=B(),CP=oe(),$P=wa(),TP={message:"must be equal to constant",params:i(({schemaCode:t})=>(0,wd._)`{allowedValue: ${t}}`,"params")},OP={keyword:"const",$data:!0,error:TP,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,wd._)`!${(0,CP.useFunc)(e,$P.default)}(${r}, ${o})`):t.fail((0,wd._)`${s} !== ${r}`)}};bd.default=OP});var Mg=O(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var qi=B(),AP=oe(),MP=wa(),zP={message:"must be equal to one of the allowed values",params:i(({schemaCode:t})=>(0,qi._)`{allowedValues: ${t}}`,"params")},DP={keyword:"enum",schemaType:"array",$data:!0,error:zP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:c}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let l=o.length>=c.opts.loopEnum,d,u=i(()=>d??(d=(0,AP.useFunc)(e,MP.default)),"getEql"),p;if(l||n)p=e.let("valid"),t.block$data(p,m);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let y=e.const("vSchema",s);p=(0,qi.or)(...o.map((h,_)=>g(y,_)))}t.pass(p);function m(){e.assign(p,!1),e.forOf("v",s,y=>e.if((0,qi._)`${u()}(${r}, ${y})`,()=>e.assign(p,!0).break()))}i(m,"loopEnum");function g(y,h){let _=o[h];return typeof _=="object"&&_!==null?(0,qi._)`${u()}(${r}, ${y}[${h}])`:(0,qi._)`${r} === ${_}`}i(g,"equalCode")}};kd.default=DP});var zg=O(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var NP=bg(),jP=kg(),qP=Pg(),LP=Rg(),UP=Ig(),VP=Cg(),FP=$g(),HP=Og(),ZP=Ag(),KP=Mg(),GP=[NP.default,jP.default,qP.default,LP.default,UP.default,VP.default,FP.default,HP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},ZP.default,KP.default];Ed.default=GP});var Pd=O(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.validateAdditionalItems=void 0;var Qr=B(),xd=oe(),WP={message:i(({params:{len:t}})=>(0,Qr.str)`must NOT have more than ${t} items`,"message"),params:i(({params:{len:t}})=>(0,Qr._)`{limit: ${t}}`,"params")},BP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:WP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,xd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Dg(t,n)}};function Dg(t,e){let{gen:r,schema:n,data:o,keyword:s,it:c}=t;c.items=!0;let l=r.const("len",(0,Qr._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Qr._)`${l} <= ${e.length}`);else if(typeof n=="object"&&!(0,xd.alwaysValidSchema)(c,n)){let u=r.var("valid",(0,Qr._)`${l} <= ${e.length}`);r.if((0,Qr.not)(u),()=>d(u)),t.ok(u)}function d(u){r.forRange("i",e.length,l,p=>{t.subschema({keyword:s,dataProp:p,dataPropType:xd.Type.Num},u),c.allErrors||r.if((0,Qr.not)(u),()=>r.break())})}i(d,"validateItems")}i(Dg,"validateAdditionalItems");Li.validateAdditionalItems=Dg;Li.default=BP});var Rd=O(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.validateTuple=void 0;var Ng=B(),ba=oe(),JP=wt(),YP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return jg(t,"additionalItems",e);r.items=!0,!(0,ba.alwaysValidSchema)(r,e)&&t.ok((0,JP.validateArray)(t))}};function jg(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:c,it:l}=t;p(o),l.opts.unevaluated&&r.length&&l.items!==!0&&(l.items=ba.mergeEvaluated.items(n,r.length,l.items));let d=n.name("valid"),u=n.const("len",(0,Ng._)`${s}.length`);r.forEach((m,g)=>{(0,ba.alwaysValidSchema)(l,m)||(n.if((0,Ng._)`${u} > ${g}`,()=>t.subschema({keyword:c,schemaProp:g,dataProp:g},d)),t.ok(d))});function p(m){let{opts:g,errSchemaPath:y}=l,h=r.length,_=h===m.minItems&&(h===m.maxItems||m[e]===!1);if(g.strictTuples&&!_){let S=`"${c}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${y}"`;(0,ba.checkStrictMode)(l,S,g.strictTuples)}}i(p,"checkStrictTuple")}i(jg,"validateTuple");Ui.validateTuple=jg;Ui.default=YP});var qg=O(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var XP=Rd(),QP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:i(t=>(0,XP.validateTuple)(t,"items"),"code")};Id.default=QP});var Ug=O(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var Lg=B(),eR=oe(),tR=wt(),rR=Pd(),nR={message:i(({params:{len:t}})=>(0,Lg.str)`must NOT have more than ${t} items`,"message"),params:i(({params:{len:t}})=>(0,Lg._)`{limit: ${t}}`,"params")},oR={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:nR,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,eR.alwaysValidSchema)(n,e)&&(o?(0,rR.validateAdditionalItems)(t,o):t.ok((0,tR.validateArray)(t)))}};Cd.default=oR});var Vg=O($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var kt=B(),ka=oe(),iR={message:i(({params:{min:t,max:e}})=>e===void 0?(0,kt.str)`must contain at least ${t} valid item(s)`:(0,kt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,"message"),params:i(({params:{min:t,max:e}})=>e===void 0?(0,kt._)`{minContains: ${t}}`:(0,kt._)`{minContains: ${t}, maxContains: ${e}}`,"params")},sR={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:iR,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,c,l,{minContains:d,maxContains:u}=n;s.opts.next?(c=d===void 0?1:d,l=u):c=1;let p=e.const("len",(0,kt._)`${o}.length`);if(t.setParams({min:c,max:l}),l===void 0&&c===0){(0,ka.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(l!==void 0&&c>l){(0,ka.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ka.alwaysValidSchema)(s,r)){let _=(0,kt._)`${p} >= ${c}`;l!==void 0&&(_=(0,kt._)`${_} && ${p} <= ${l}`),t.pass(_);return}s.items=!0;let m=e.name("valid");l===void 0&&c===1?y(m,()=>e.if(m,()=>e.break())):c===0?(e.let(m,!0),l!==void 0&&e.if((0,kt._)`${o}.length > 0`,g)):(e.let(m,!1),g()),t.result(m,()=>t.reset());function g(){let _=e.name("_valid"),S=e.let("count",0);y(_,()=>e.if(_,()=>h(S)))}i(g,"validateItemsWithCount");function y(_,S){e.forRange("i",0,p,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:ka.Type.Num,compositeRule:!0},_),S()})}i(y,"validateItems");function h(_){e.code((0,kt._)`${_}++`),l===void 0?e.if((0,kt._)`${_} >= ${c}`,()=>e.assign(m,!0).break()):(e.if((0,kt._)`${_} > ${l}`,()=>e.assign(m,!1).break()),c===1?e.assign(m,!0):e.if((0,kt._)`${_} >= ${c}`,()=>e.assign(m,!0)))}i(h,"checkLimits")}};$d.default=sR});var Zg=O(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.validateSchemaDeps=Ht.validatePropertyDeps=Ht.error=void 0;var Td=B(),aR=oe(),Vi=wt();Ht.error={message:i(({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Td.str)`must have ${n} ${r} when property ${t} is present`},"message"),params:i(({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Td._)`{property: ${t},
23
+ missingProperty: ${n},
24
+ depsCount: ${e},
25
+ deps: ${r}}`,"params")};var cR={keyword:"dependencies",type:"object",schemaType:"object",error:Ht.error,code(t){let[e,r]=lR(t);Fg(t,e),Hg(t,r)}};function lR({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}i(lR,"splitDependencies");function Fg(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let c in e){let l=e[c];if(l.length===0)continue;let d=(0,Vi.propertyInData)(r,n,c,o.opts.ownProperties);t.setParams({property:c,depsCount:l.length,deps:l.join(", ")}),o.allErrors?r.if(d,()=>{for(let u of l)(0,Vi.checkReportMissingProp)(t,u)}):(r.if((0,Td._)`${d} && (${(0,Vi.checkMissingProp)(t,l,s)})`),(0,Vi.reportMissingProp)(t,s),r.else())}}i(Fg,"validatePropertyDeps");Ht.validatePropertyDeps=Fg;function Hg(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,c=r.name("valid");for(let l in e)(0,aR.alwaysValidSchema)(s,e[l])||(r.if((0,Vi.propertyInData)(r,n,l,s.opts.ownProperties),()=>{let d=t.subschema({keyword:o,schemaProp:l},c);t.mergeValidEvaluated(d,c)},()=>r.var(c,!0)),t.ok(c))}i(Hg,"validateSchemaDeps");Ht.validateSchemaDeps=Hg;Ht.default=cR});var Gg=O(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var Kg=B(),dR=oe(),uR={message:"property name must be valid",params:i(({params:t})=>(0,Kg._)`{propertyName: ${t.propertyName}}`,"params")},pR={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:uR,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,dR.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,c=>{t.setParams({propertyName:c}),t.subschema({keyword:"propertyNames",data:c,dataTypes:["string"],propertyName:c,compositeRule:!0},s),e.if((0,Kg.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Od.default=pR});var Md=O(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var Ea=wt(),Tt=B(),fR=or(),xa=oe(),mR={message:"must NOT have additional properties",params:i(({params:t})=>(0,Tt._)`{additionalProperty: ${t.additionalProperty}}`,"params")},hR={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:mR,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:c}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:l,opts:d}=c;if(c.props=!0,d.removeAdditional!=="all"&&(0,xa.alwaysValidSchema)(c,r))return;let u=(0,Ea.allSchemaProperties)(n.properties),p=(0,Ea.allSchemaProperties)(n.patternProperties);m(),t.ok((0,Tt._)`${s} === ${fR.default.errors}`);function m(){e.forIn("key",o,S=>{!u.length&&!p.length?h(S):e.if(g(S),()=>h(S))})}i(m,"checkAdditionalProperties");function g(S){let E;if(u.length>8){let x=(0,xa.schemaRefOrVal)(c,n.properties,"properties");E=(0,Ea.isOwnProperty)(e,x,S)}else u.length?E=(0,Tt.or)(...u.map(x=>(0,Tt._)`${S} === ${x}`)):E=Tt.nil;return p.length&&(E=(0,Tt.or)(E,...p.map(x=>(0,Tt._)`${(0,Ea.usePattern)(t,x)}.test(${S})`))),(0,Tt.not)(E)}i(g,"isAdditional");function y(S){e.code((0,Tt._)`delete ${o}[${S}]`)}i(y,"deleteAdditional");function h(S){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){y(S);return}if(r===!1){t.setParams({additionalProperty:S}),t.error(),l||e.break();return}if(typeof r=="object"&&!(0,xa.alwaysValidSchema)(c,r)){let E=e.name("valid");d.removeAdditional==="failing"?(_(S,E,!1),e.if((0,Tt.not)(E),()=>{t.reset(),y(S)})):(_(S,E),l||e.if((0,Tt.not)(E),()=>e.break()))}}i(h,"additionalPropertyCode");function _(S,E,x){let w={keyword:"additionalProperties",dataProp:S,dataPropType:xa.Type.Str};x===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,E)}i(_,"applyAdditionalSchema")}};Ad.default=hR});var Jg=O(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var gR=Ii(),Wg=wt(),zd=oe(),Bg=Md(),yR={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Bg.default.code(new gR.KeywordCxt(s,Bg.default,"additionalProperties"));let c=(0,Wg.allSchemaProperties)(r);for(let m of c)s.definedProperties.add(m);s.opts.unevaluated&&c.length&&s.props!==!0&&(s.props=zd.mergeEvaluated.props(e,(0,zd.toHash)(c),s.props));let l=c.filter(m=>!(0,zd.alwaysValidSchema)(s,r[m]));if(l.length===0)return;let d=e.name("valid");for(let m of l)u(m)?p(m):(e.if((0,Wg.propertyInData)(e,o,m,s.opts.ownProperties)),p(m),s.allErrors||e.else().var(d,!0),e.endIf()),t.it.definedProperties.add(m),t.ok(d);function u(m){return s.opts.useDefaults&&!s.compositeRule&&r[m].default!==void 0}i(u,"hasDefault");function p(m){t.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}i(p,"applyPropertySchema")}};Dd.default=yR});var ey=O(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var Yg=wt(),Pa=B(),Xg=oe(),Qg=oe(),_R={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:c}=s,l=(0,Yg.allSchemaProperties)(r),d=l.filter(_=>(0,Xg.alwaysValidSchema)(s,r[_]));if(l.length===0||d.length===l.length&&(!s.opts.unevaluated||s.props===!0))return;let u=c.strictSchema&&!c.allowMatchingProperties&&o.properties,p=e.name("valid");s.props!==!0&&!(s.props instanceof Pa.Name)&&(s.props=(0,Qg.evaluatedPropsToName)(e,s.props));let{props:m}=s;g();function g(){for(let _ of l)u&&y(_),s.allErrors?h(_):(e.var(p,!0),h(_),e.if(p))}i(g,"validatePatternProperties");function y(_){for(let S in u)new RegExp(_).test(S)&&(0,Xg.checkStrictMode)(s,`property ${S} matches pattern ${_} (use allowMatchingProperties)`)}i(y,"checkMatchingProperties");function h(_){e.forIn("key",n,S=>{e.if((0,Pa._)`${(0,Yg.usePattern)(t,_)}.test(${S})`,()=>{let E=d.includes(_);E||t.subschema({keyword:"patternProperties",schemaProp:_,dataProp:S,dataPropType:Qg.Type.Str},p),s.opts.unevaluated&&m!==!0?e.assign((0,Pa._)`${m}[${S}]`,!0):!E&&!s.allErrors&&e.if((0,Pa.not)(p),()=>e.break())})})}i(h,"validateProperties")}};Nd.default=_R});var ty=O(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var vR=oe(),SR={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,vR.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};jd.default=SR});var ry=O(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var wR=wt(),bR={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:wR.validateUnion,error:{message:"must match a schema in anyOf"}};qd.default=bR});var ny=O(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Ra=B(),kR=oe(),ER={message:"must match exactly one schema in oneOf",params:i(({params:t})=>(0,Ra._)`{passingSchemas: ${t.passing}}`,"params")},xR={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ER,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,c=e.let("valid",!1),l=e.let("passing",null),d=e.name("_valid");t.setParams({passing:l}),e.block(u),t.result(c,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((p,m)=>{let g;(0,kR.alwaysValidSchema)(o,p)?e.var(d,!0):g=t.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&e.if((0,Ra._)`${d} && ${c}`).assign(c,!1).assign(l,(0,Ra._)`[${l}, ${m}]`).else(),e.if(d,()=>{e.assign(c,!0),e.assign(l,m),g&&t.mergeEvaluated(g,Ra.Name)})})}i(u,"validateOneOf")}};Ld.default=xR});var oy=O(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var PR=oe(),RR={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,c)=>{if((0,PR.alwaysValidSchema)(n,s))return;let l=t.subschema({keyword:"allOf",schemaProp:c},o);t.ok(o),t.mergeEvaluated(l)})}};Ud.default=RR});var ay=O(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var Ia=B(),sy=oe(),IR={message:i(({params:t})=>(0,Ia.str)`must match "${t.ifClause}" schema`,"message"),params:i(({params:t})=>(0,Ia._)`{failingKeyword: ${t.ifClause}}`,"params")},CR={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:IR,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,sy.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=iy(n,"then"),s=iy(n,"else");if(!o&&!s)return;let c=e.let("valid",!0),l=e.name("_valid");if(d(),t.reset(),o&&s){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(l,u("then",p),u("else",p))}else o?e.if(l,u("then")):e.if((0,Ia.not)(l),u("else"));t.pass(c,()=>t.error(!0));function d(){let p=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},l);t.mergeEvaluated(p)}i(d,"validateIf");function u(p,m){return()=>{let g=t.subschema({keyword:p},l);e.assign(c,l),t.mergeValidEvaluated(g,c),m?e.assign(m,(0,Ia._)`${p}`):t.setParams({ifClause:p})}}i(u,"validateClause")}};function iy(t,e){let r=t.schema[e];return r!==void 0&&!(0,sy.alwaysValidSchema)(t,r)}i(iy,"hasSchema");Vd.default=CR});var cy=O(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var $R=oe(),TR={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,$R.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Fd.default=TR});var ly=O(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var OR=Pd(),AR=qg(),MR=Rd(),zR=Ug(),DR=Vg(),NR=Zg(),jR=Gg(),qR=Md(),LR=Jg(),UR=ey(),VR=ty(),FR=ry(),HR=ny(),ZR=oy(),KR=ay(),GR=cy();function WR(t=!1){let e=[VR.default,FR.default,HR.default,ZR.default,KR.default,GR.default,jR.default,qR.default,NR.default,LR.default,UR.default];return t?e.push(AR.default,zR.default):e.push(OR.default,MR.default),e.push(DR.default),e}i(WR,"getApplicator");Hd.default=WR});var dy=O(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});var Pe=B(),BR={message:i(({schemaCode:t})=>(0,Pe.str)`must match format "${t}"`,"message"),params:i(({schemaCode:t})=>(0,Pe._)`{format: ${t}}`,"params")},JR={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:BR,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:c,it:l}=t,{opts:d,errSchemaPath:u,schemaEnv:p,self:m}=l;if(!d.validateFormats)return;o?g():y();function g(){let h=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),_=r.const("fDef",(0,Pe._)`${h}[${c}]`),S=r.let("fType"),E=r.let("format");r.if((0,Pe._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>r.assign(S,(0,Pe._)`${_}.type || "string"`).assign(E,(0,Pe._)`${_}.validate`),()=>r.assign(S,(0,Pe._)`"string"`).assign(E,_)),t.fail$data((0,Pe.or)(x(),w()));function x(){return d.strictSchema===!1?Pe.nil:(0,Pe._)`${c} && !${E}`}i(x,"unknownFmt");function w(){let P=p.$async?(0,Pe._)`(${_}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,Pe._)`${E}(${n})`,I=(0,Pe._)`(typeof ${E} == "function" ? ${P} : ${E}.test(${n}))`;return(0,Pe._)`${E} && ${E} !== true && ${S} === ${e} && !${I}`}i(w,"invalidFmt")}i(g,"validate$DataFormat");function y(){let h=m.formats[s];if(!h){x();return}if(h===!0)return;let[_,S,E]=w(h);_===e&&t.pass(P());function x(){if(d.strictSchema===!1){m.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${s}" ignored in schema at path "${u}"`}}i(x,"unknownFormat");function w(I){let L=I instanceof RegExp?(0,Pe.regexpCode)(I):d.code.formats?(0,Pe._)`${d.code.formats}${(0,Pe.getProperty)(s)}`:void 0,F=r.scopeValue("formats",{key:s,ref:I,code:L});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,Pe._)`${F}.validate`]:["string",I,F]}i(w,"getFormat");function P(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!p.$async)throw new Error("async format in sync schema");return(0,Pe._)`await ${E}(${n})`}return typeof S=="function"?(0,Pe._)`${E}(${n})`:(0,Pe._)`${E}.test(${n})`}i(P,"validCondition")}i(y,"validateFormat")}};Zd.default=JR});var uy=O(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var YR=dy(),XR=[YR.default];Kd.default=XR});var py=O(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.contentVocabulary=oo.metadataVocabulary=void 0;oo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];oo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var my=O(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var QR=wg(),eI=zg(),tI=ly(),rI=uy(),fy=py(),nI=[QR.default,eI.default,(0,tI.default)(),rI.default,fy.metadataVocabulary,fy.contentVocabulary];Gd.default=nI});var gy=O(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.DiscrError=void 0;var hy;(function(t){t.Tag="tag",t.Mapping="mapping"})(hy||(Ca.DiscrError=hy={}))});var _y=O(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var io=B(),Wd=gy(),yy=ua(),oI=Ci(),iI=oe(),sI={message:i(({params:{discrError:t,tagName:e}})=>t===Wd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,"message"),params:i(({params:{discrError:t,tag:e,tagName:r}})=>(0,io._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`,"params")},aI={keyword:"discriminator",type:"object",schemaType:"object",error:sI,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:c}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let l=n.propertyName;if(typeof l!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!c)throw new Error("discriminator: requires oneOf keyword");let d=e.let("valid",!1),u=e.const("tag",(0,io._)`${r}${(0,io.getProperty)(l)}`);e.if((0,io._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:Wd.DiscrError.Tag,tag:u,tagName:l})),t.ok(d);function p(){let y=g();e.if(!1);for(let h in y)e.elseIf((0,io._)`${u} === ${h}`),e.assign(d,m(y[h]));e.else(),t.error(!1,{discrError:Wd.DiscrError.Mapping,tag:u,tagName:l}),e.endIf()}i(p,"validateMapping");function m(y){let h=e.name("valid"),_=t.subschema({keyword:"oneOf",schemaProp:y},h);return t.mergeEvaluated(_,io.Name),h}i(m,"applyTagSchema");function g(){var y;let h={},_=E(o),S=!0;for(let P=0;P<c.length;P++){let I=c[P];if(I?.$ref&&!(0,iI.schemaHasRulesButRef)(I,s.self.RULES)){let F=I.$ref;if(I=yy.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,F),I instanceof yy.SchemaEnv&&(I=I.schema),I===void 0)throw new oI.default(s.opts.uriResolver,s.baseId,F)}let L=(y=I?.properties)===null||y===void 0?void 0:y[l];if(typeof L!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${l}"`);S=S&&(_||E(I)),x(L,P)}if(!S)throw new Error(`discriminator: "${l}" must be required`);return h;function E({required:P}){return Array.isArray(P)&&P.includes(l)}function x(P,I){if(P.const)w(P.const,I);else if(P.enum)for(let L of P.enum)w(L,I);else throw new Error(`discriminator: "properties/${l}" must have "const" or "enum"`)}function w(P,I){if(typeof P!="string"||P in h)throw new Error(`discriminator: "${l}" values must be unique strings`);h[P]=I}}i(g,"getMapping")}};Bd.default=aI});var vy=O((l3,cI)=>{cI.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Yd=O((ye,Jd)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var lI=hg(),dI=my(),uI=_y(),Sy=vy(),pI=["/properties"],$a="http://json-schema.org/draft-07/schema",so=class extends lI.default{static{i(this,"Ajv")}_addVocabularies(){super._addVocabularies(),dI.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(uI.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Sy,pI):Sy;this.addMetaSchema(e,$a,!1),this.refs["http://json-schema.org/schema"]=$a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema($a)?$a:void 0)}};ye.Ajv=so;Jd.exports=ye=so;Jd.exports.Ajv=so;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=so;var fI=Ii();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:i(function(){return fI.KeywordCxt},"get")});var ao=B();Object.defineProperty(ye,"_",{enumerable:!0,get:i(function(){return ao._},"get")});Object.defineProperty(ye,"str",{enumerable:!0,get:i(function(){return ao.str},"get")});Object.defineProperty(ye,"stringify",{enumerable:!0,get:i(function(){return ao.stringify},"get")});Object.defineProperty(ye,"nil",{enumerable:!0,get:i(function(){return ao.nil},"get")});Object.defineProperty(ye,"Name",{enumerable:!0,get:i(function(){return ao.Name},"get")});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:i(function(){return ao.CodeGen},"get")});var mI=la();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:i(function(){return mI.default},"get")});var hI=Ci();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:i(function(){return hI.default},"get")})});var Iy=O(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.formatNames=Kt.fastFormats=Kt.fullFormats=void 0;function Zt(t,e){return{validate:t,compare:e}}i(Zt,"fmtDef");Kt.fullFormats={date:Zt(Ey,tu),time:Zt(Qd(!0),ru),"date-time":Zt(wy(!0),Py),"iso-time":Zt(Qd(),xy),"iso-date-time":Zt(wy(),Ry),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:wI,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:II,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:bI,int32:{type:"number",validate:xI},int64:{type:"number",validate:PI},float:{type:"number",validate:ky},double:{type:"number",validate:ky},password:!0,binary:!0};Kt.fastFormats={...Kt.fullFormats,date:Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,tu),time:Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ru),"date-time":Zt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Py),"iso-time":Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,xy),"iso-date-time":Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Ry),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Kt.formatNames=Object.keys(Kt.fullFormats);function gI(t){return t%4===0&&(t%100!==0||t%400===0)}i(gI,"isLeapYear");var yI=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,_I=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Ey(t){let e=yI.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&gI(r)?29:_I[n])}i(Ey,"date");function tu(t,e){if(t&&e)return t>e?1:t<e?-1:0}i(tu,"compareDate");var Xd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Qd(t){return i(function(r){let n=Xd.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],c=+n[3],l=n[4],d=n[5]==="-"?-1:1,u=+(n[6]||0),p=+(n[7]||0);if(u>23||p>59||t&&!l)return!1;if(o<=23&&s<=59&&c<60)return!0;let m=s-p*d,g=o-u*d-(m<0?1:0);return(g===23||g===-1)&&(m===59||m===-1)&&c<61},"time")}i(Qd,"getTime");function ru(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}i(ru,"compareTime");function xy(t,e){if(!(t&&e))return;let r=Xd.exec(t),n=Xd.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}i(xy,"compareIsoTime");var eu=/t|\s/i;function wy(t){let e=Qd(t);return i(function(n){let o=n.split(eu);return o.length===2&&Ey(o[0])&&e(o[1])},"date_time")}i(wy,"getDateTime");function Py(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}i(Py,"compareDateTime");function Ry(t,e){if(!(t&&e))return;let[r,n]=t.split(eu),[o,s]=e.split(eu),c=tu(r,o);if(c!==void 0)return c||ru(n,s)}i(Ry,"compareIsoDateTime");var vI=/\/|:/,SI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function wI(t){return vI.test(t)&&SI.test(t)}i(wI,"uri");var by=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function bI(t){return by.lastIndex=0,by.test(t)}i(bI,"byte");var kI=-(2**31),EI=2**31-1;function xI(t){return Number.isInteger(t)&&t<=EI&&t>=kI}i(xI,"validateInt32");function PI(t){return Number.isInteger(t)}i(PI,"validateInt64");function ky(){return!0}i(ky,"validateNumber");var RI=/[^\\]\\Z/;function II(t){if(RI.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}i(II,"regex")});var Cy=O(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.formatLimitDefinition=void 0;var CI=Yd(),Ot=B(),Rr=Ot.operators,Ta={formatMaximum:{okStr:"<=",ok:Rr.LTE,fail:Rr.GT},formatMinimum:{okStr:">=",ok:Rr.GTE,fail:Rr.LT},formatExclusiveMaximum:{okStr:"<",ok:Rr.LT,fail:Rr.GTE},formatExclusiveMinimum:{okStr:">",ok:Rr.GT,fail:Rr.LTE}},$I={message:i(({keyword:t,schemaCode:e})=>(0,Ot.str)`should be ${Ta[t].okStr} ${e}`,"message"),params:i(({keyword:t,schemaCode:e})=>(0,Ot._)`{comparison: ${Ta[t].okStr}, limit: ${e}}`,"params")};co.formatLimitDefinition={keyword:Object.keys(Ta),type:"string",schemaType:"string",$data:!0,error:$I,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:c,self:l}=s;if(!c.validateFormats)return;let d=new CI.KeywordCxt(s,l.RULES.all.format.definition,"format");d.$data?u():p();function u(){let g=e.scopeValue("formats",{ref:l.formats,code:c.code.formats}),y=e.const("fmt",(0,Ot._)`${g}[${d.schemaCode}]`);t.fail$data((0,Ot.or)((0,Ot._)`typeof ${y} != "object"`,(0,Ot._)`${y} instanceof RegExp`,(0,Ot._)`typeof ${y}.compare != "function"`,m(y)))}i(u,"validate$DataFormat");function p(){let g=d.schema,y=l.formats[g];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${o}": format "${g}" does not define "compare" function`);let h=e.scopeValue("formats",{key:g,ref:y,code:c.code.formats?(0,Ot._)`${c.code.formats}${(0,Ot.getProperty)(g)}`:void 0});t.fail$data(m(h))}i(p,"validateFormat");function m(g){return(0,Ot._)`${g}.compare(${r}, ${n}) ${Ta[o].fail} 0`}i(m,"compareCode")},dependencies:["format"]};var TI=i(t=>(t.addKeyword(co.formatLimitDefinition),t),"formatLimitPlugin");co.default=TI});var Ay=O((Fi,Oy)=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});var lo=Iy(),OI=Cy(),nu=B(),$y=new nu.Name("fullFormats"),AI=new nu.Name("fastFormats"),ou=i((t,e={keywords:!0})=>{if(Array.isArray(e))return Ty(t,e,lo.fullFormats,$y),t;let[r,n]=e.mode==="fast"?[lo.fastFormats,AI]:[lo.fullFormats,$y],o=e.formats||lo.formatNames;return Ty(t,o,r,n),e.keywords&&(0,OI.default)(t),t},"formatsPlugin");ou.get=(t,e="full")=>{let n=(e==="fast"?lo.fastFormats:lo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Ty(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,nu._)`require("ajv-formats/dist/formats").${n}`);for(let c of e)t.addFormat(c,r[c])}i(Ty,"addFormats");Oy.exports=Fi=ou;Object.defineProperty(Fi,"__esModule",{value:!0});Fi.default=ou});var jt={};H(jt,{CatalogModelStatus:()=>Rp,Event:()=>Cp,Model:()=>Ip,ModelsDev:()=>jt,Provider:()=>j_,Service:()=>yn,node:()=>L_});import M_ from"path";var Io={};H(Io,{Event:()=>A_,ModelsDev:()=>Io});var Ep=pn({type:"models-dev.refreshed",schema:{}}),A_={Refreshed:Ep,Definitions:fn(Ep)};var Rp=f.Literals(["alpha","beta","deprecated"]),xp=f.Union([f.Literals(["reasoning","reasoning_content","reasoning_text"]),f.String]),z_=`opencode/${Wu}/${ht}/${Mr.OPENCODE_CLIENT}`,D_=f.Struct({input:f.Finite,output:f.Finite,cache_read:f.optional(f.Finite),cache_write:f.optional(f.Finite),tier:f.Struct({type:f.Literal("context"),size:f.Finite})}),Pp=f.Struct({input:f.Finite,output:f.Finite,cache_read:f.optional(f.Finite),cache_write:f.optional(f.Finite),tiers:f.optional(f.Array(D_)),context_over_200k:f.optional(f.Struct({input:f.Finite,output:f.Finite,cache_read:f.optional(f.Finite),cache_write:f.optional(f.Finite)}))}),N_=f.Union([f.Struct({type:f.Literal("effort"),values:f.Array(f.NullOr(f.String))}),f.Struct({type:f.Literal("toggle")}),f.Struct({type:f.Literal("budget_tokens"),min:f.optional(f.Finite),max:f.optional(f.Finite)})]),Ip=f.Struct({id:f.String,name:f.String,family:f.optional(f.String),release_date:f.String,attachment:f.Boolean,reasoning:f.Boolean,temperature:f.Boolean,tool_call:f.Boolean,reasoning_options:f.optional(f.Array(N_)),interleaved:f.optional(f.Union([f.Boolean,xp,f.Struct({field:xp})])),cost:f.optional(Pp),limit:f.Struct({context:f.Finite,input:f.optional(f.Finite),output:f.Finite}),modalities:f.optional(f.Struct({input:f.Array(f.Literals(["text","audio","image","video","pdf"])),output:f.Array(f.Literals(["text","audio","image","video","pdf"]))})),experimental:f.optional(f.Struct({modes:f.optional(f.Record(f.String,f.Struct({cost:f.optional(Pp),provider:f.optional(f.Struct({body:f.optional(f.Record(f.String,f.MutableJson)),headers:f.optional(f.Record(f.String,f.String))}))})))})),status:f.optional(Rp),provider:f.optional(f.Struct({npm:f.optional(f.String),api:f.optional(f.String)}))}),j_=f.Struct({api:f.optional(f.String),name:f.String,env:f.Array(f.String),id:f.String,npm:f.optional(f.String),models:f.Record(f.String,Ip)}),Cp=Io.Event,yn=class extends te.Service()("@opencode/ModelsDev"){static{i(this,"Service")}},q_=V.effect(yn,a.gen(function*(){let t=yield*ae.Service,e=yield*Ie.Service,r=De.filterStatusOk((yield*De.HttpClient).pipe(De.retryTransient({retryOn:"errors-and-responses",times:2,schedule:Ar.exponential(200).pipe(Ar.jittered)}))),n=Mr.OPENCODE_MODELS_URL||"https://models.opencode.ai",o=M_.join(se.Path.cache,n==="https://models.opencode.ai"?"models.json":`models-${Gu.fast(n)}.json`),s=dr.minutes(5),c=`models-dev:${o}`,l=a.fnUntraced(function*(){let E=yield*t.stat(o).pipe(a.catch(()=>a.succeed(void 0)));if(!E)return!1;let x=pt.getOrElse(E.mtime,()=>new Date(0)).getTime();return Date.now()-x<dr.toMillis(s)}),d=a.fn("ModelsDev.fetchApi")(function*(){return yield*be.get(`${n}/api.json`).pipe(be.setHeader("User-Agent",z_),r.execute,a.flatMap(E=>E.text),a.timeout("10 seconds"))}),u=t.readJson(Mr.OPENCODE_MODELS_PATH??o).pipe(a.catch(E=>Mr.OPENCODE_MODELS_PATH===void 0&&E._tag==="FileSystemError"&&E.method==="readJson"?t.remove(o,{force:!0}).pipe(a.ignore,a.as(void 0)):a.succeed(void 0)),a.map(E=>E)),p=a.sync(()=>typeof OPENCODE_MODELS_DEV>"u"?void 0:OPENCODE_MODELS_DEV),m=a.fn("ModelsDev.fetchAndWrite")(function*(){let E=yield*d(),x=`${o}.${process.pid}.${Date.now()}.tmp`;return yield*t.writeWithDirs(x,E).pipe(a.andThen(t.rename(x,o)),a.catch(w=>a.gen(function*(){return yield*t.remove(x,{force:!0}).pipe(a.ignore),yield*a.fail(w)}))),E}),g=a.gen(function*(){let E=yield*u;if(E)return E;let x=yield*p;if(x)return x;if(Mr.OPENCODE_DISABLE_MODELS_FETCH)return{};let w=yield*a.scoped(a.gen(function*(){return yield*Ba.effect(c),yield*m()}));return JSON.parse(w)}).pipe(a.withSpan("ModelsDev.populate"),a.orDie),[y,h]=yield*a.cachedInvalidateWithTTL(g,dr.infinity),_=i(()=>y,"get"),S=a.fn("ModelsDev.refresh")(function*(E=!1){!E&&(yield*l())||(yield*a.scoped(a.gen(function*(){yield*Ba.effect(c),!(!E&&(yield*l()))&&(yield*m(),yield*h,yield*e.publish(Cp.Refreshed,{}))})).pipe(a.tapCause(x=>a.logError("Failed to fetch models.dev",{cause:x})),a.ignore))});return!Mr.OPENCODE_DISABLE_MODELS_FETCH&&!process.argv.includes("--get-yargs-completions")&&(yield*a.forkScoped(S().pipe(a.repeat(Ar.spaced("60 minutes")),a.ignore))),yn.of({get:_,refresh:S})})),L_=pr({service:yn,layer:q_,deps:[ae.node,Ie.node,fr]});function ws(t,e){return!e.instance&&!e.workspace?t:e.instance?e.workspace?t.pipe(a.provideService(zr,e.instance),a.provideService(mr,e.workspace)):t.pipe(a.provideService(zr,e.instance)):t.pipe(a.provideService(mr,e.workspace))}i(ws,"attachWith");function C$(t){let e=Ro.workspaceID,r=gs.getCurrent();return ws(t,{instance:r?Ga(r.context,zr):void 0,workspace:e??(r?Ga(r.context,mr):void 0)})}i(C$,"attach");var $o={};H($o,{Event:()=>Co,Permission:()=>$o,Service:()=>_n,disabled:()=>$p,evaluate:()=>ic,fromConfig:()=>F_,merge:()=>H_,node:()=>K_,visibleTools:()=>Z_});import bs from"os";var Co=Yt.Event;function ic(t,e,...r){return r.flat().findLast(n=>Bt.match(t,n.permission)&&Bt.match(e,n.pattern))??{action:"ask",permission:t,pattern:"*"}}i(ic,"evaluate");var _n=class extends te.Service()("@opencode/Permission"){static{i(this,"Service")}},U_=V.effect(_n,a.gen(function*(){let t=yield*Xt.Service,e=yield*Q.make(a.fn("Permission.state")(function*(s){let c={pending:new Map,approved:[]};return yield*a.addFinalizer(()=>a.gen(function*(){for(let l of c.pending.values())yield*pe.fail(l.deferred,new Yt.RejectedError);c.pending.clear()})),c})),r=a.fn("Permission.ask")(function*(s){let{approved:c,pending:l}=yield*Q.get(e),{ruleset:d,...u}=s,p=!1;for(let h of u.patterns){let _=ic(u.permission,h,d,c);if(yield*a.logInfo("evaluated",{permission:u.permission,pattern:h,action:_}),_.action==="deny")return yield*new Yt.DeniedError({ruleset:d.filter(S=>Bt.match(u.permission,S.permission))});_.action!=="allow"&&(p=!0)}if(!p)return;let m=u.id??Yt.ID.ascending(),g={id:m,sessionID:u.sessionID,permission:u.permission,patterns:u.patterns,metadata:u.metadata,always:u.always,tool:u.tool};yield*a.logInfo("asking",{id:m,permission:g.permission,patterns:g.patterns});let y=yield*pe.make();return l.set(m,{info:g,deferred:y}),yield*t.publish(Co.Asked,g),yield*a.ensuring(pe.await(y),a.sync(()=>{l.delete(m)}))}),n=a.fn("Permission.reply")(function*(s){let{approved:c,pending:l}=yield*Q.get(e),d=l.get(s.requestID);if(!d)return yield*new Yt.NotFoundError({requestID:s.requestID});if(l.delete(s.requestID),yield*t.publish(Co.Replied,{sessionID:d.info.sessionID,requestID:d.info.id,reply:s.reply}),s.reply==="reject"){yield*pe.fail(d.deferred,s.message?new Yt.CorrectedError({feedback:s.message}):new Yt.RejectedError);for(let[u,p]of l.entries())p.info.sessionID===d.info.sessionID&&(l.delete(u),yield*t.publish(Co.Replied,{sessionID:p.info.sessionID,requestID:p.info.id,reply:"reject"}),yield*pe.fail(p.deferred,new Yt.RejectedError));return}if(yield*pe.succeed(d.deferred,void 0),s.reply!=="once"){for(let u of d.info.always)c.push({permission:d.info.permission,pattern:u,action:"allow"});for(let[u,p]of l.entries())p.info.sessionID!==d.info.sessionID||!p.info.patterns.every(g=>ic(p.info.permission,g,c).action==="allow")||(l.delete(u),yield*t.publish(Co.Replied,{sessionID:p.info.sessionID,requestID:p.info.id,reply:"always"}),yield*pe.succeed(p.deferred,void 0))}}),o=a.fn("Permission.list")(function*(){let s=(yield*Q.get(e)).pending;return Array.from(s.values(),c=>c.info)});return _n.of({ask:r,reply:n,list:o})}));function V_(t){return t.startsWith("~/")?bs.homedir()+t.slice(1):t==="~"?bs.homedir():t.startsWith("$HOME/")?bs.homedir()+t.slice(5):t.startsWith("$HOME")?bs.homedir()+t.slice(5):t}i(V_,"expand");function F_(t){let e=[];for(let[r,n]of Object.entries(t)){if(typeof n=="string"){e.push({permission:r,action:n,pattern:"*"});continue}e.push(...Object.entries(n).map(([o,s])=>({permission:r,pattern:V_(o),action:s})))}return e}i(F_,"fromConfig");function H_(...t){return t.flat()}i(H_,"merge");function $p(t,e){let r=["edit","write","apply_patch"],n=["list_mcp_resources","list_mcp_resource_templates","read_mcp_resource"];return new Set(t.filter(o=>{let s=r.includes(o)?"edit":n.includes(o)?"read":o,c=e.findLast(l=>Bt.match(s,l.permission));return c?.pattern==="*"&&c.action==="deny"}))}i($p,"disabled");function Z_(t,e){let r=$p(Object.keys(t),e);return Object.fromEntries(Object.entries(t).filter(([n])=>!r.has(n)))}i(Z_,"visibleTools");var K_=ft.make({service:_n,layer:U_,deps:[Xt.node]});var Sn={};H(Sn,{Discovery:()=>Sn,Service:()=>vn,node:()=>B_});var G_=4,Tp=8,sc=class extends f.Class("IndexSkill")({name:f.String,files:f.Array(f.String),version:f.optional(f.String)}){static{i(this,"IndexSkill")}},ac=class extends f.Class("Index")({skills:f.Array(sc)}){static{i(this,"Index")}},vn=class extends te.Service()("@opencode/SkillDiscovery"){static{i(this,"Service")}},W_=V.effect(vn,a.gen(function*(){let t=yield*ae.Service,e=yield*Ou.Path,r=De.filterStatusOk(yp(yield*De.HttpClient)),n=e.join(se.Path.cache,"skills"),o=a.fn("Discovery.download")(function*(c,l){return(yield*t.exists(l).pipe(a.orDie))?!0:yield*be.get(c).pipe(r.execute,a.flatMap(d=>d.arrayBuffer),a.flatMap(d=>t.writeWithDirs(l,new Uint8Array(d))),a.as(!0),a.catch(d=>a.logError("failed to download",{url:c,error:d}).pipe(a.as(!1))))}),s=a.fn("Discovery.pull")(function*(c){let l=c.endsWith("/")?c:`${c}/`,d=new URL("index.json",l).href,u=l.slice(0,-1);yield*a.logInfo("fetching index",{url:d});let p=yield*be.get(d).pipe(be.acceptJson,r.execute,a.flatMap(Mt.schemaBodyJson(ac)),a.catch(h=>a.logError("failed to fetch index",{url:d,error:h}).pipe(a.as(null))));if(!p)return[];let m=p.skills.filter(h=>!h.files.includes("SKILL.md"));yield*a.forEach(m,h=>a.logWarning("skill entry missing SKILL.md",{url:d,skill:h.name}),{discard:!0});let g=p.skills.filter(h=>h.files.includes("SKILL.md"));return(yield*a.forEach(g,h=>a.gen(function*(){let _=e.join(n,h.name),S=e.join(_,".opencode-version"),E=h.version,x=E===void 0?void 0:yield*t.readFileStringSafe(S).pipe(a.catch(()=>a.succeed(void 0)));if(E===void 0||x===E)yield*a.forEach(h.files,w=>o(new URL(w,`${u}/${h.name}/`).href,e.join(_,w)),{concurrency:Tp,discard:!0});else{let w=crypto.randomUUID(),P=`${_}.tmp-${w}`,I=`${_}.old-${w}`;yield*a.gen(function*(){(yield*a.forEach(h.files,F=>o(new URL(F,`${u}/${h.name}/`).href,e.join(P,F)),{concurrency:Tp})).every(Boolean)&&(yield*t.exists(e.join(P,"SKILL.md")).pipe(a.orDie))&&(yield*t.writeFileString(e.join(P,".opencode-version"),E),yield*a.uninterruptible(a.gen(function*(){let F=yield*t.exists(_).pipe(a.orDie);F&&(yield*t.rename(_,I)),yield*t.rename(P,_).pipe(a.catch(Be=>a.gen(function*(){return F&&(yield*t.rename(I,_).pipe(a.ignore)),yield*a.fail(Be)}))),F&&(yield*t.remove(I,{recursive:!0,force:!0}).pipe(a.ignore))})))}).pipe(a.catch(L=>a.logError("failed to refresh skill",{skill:h.name,error:L})),a.ensuring(t.remove(P,{recursive:!0,force:!0}).pipe(a.ignore)))}return(yield*t.exists(e.join(_,"SKILL.md")).pipe(a.orDie))?_:null}),{concurrency:G_})).filter(h=>h!==null)});return vn.of({pull:s})})),B_=ft.make({service:vn,layer:W_,deps:[ae.node,Ju,fr]});var Dc={};H(Dc,{Info:()=>Fw,InvalidError:()=>Mc,NameMismatchError:()=>zc,NotFoundError:()=>As,Service:()=>Un,Skill:()=>Dc,fmt:()=>Jw,node:()=>Yw});import Ln from"path";var qr={};H(qr,{CustomizeOpencodeContent:()=>hm,Plugin:()=>Nw,SkillPlugin:()=>qr});var Ac={};H(Ac,{PluginInternal:()=>Ac,define:()=>G,locationLayer:()=>zw,node:()=>Dw});var gt={};H(gt,{CommandV2:()=>gt,Info:()=>Y_,Service:()=>wn,locationLayer:()=>X_,node:()=>Q_});var To={};H(To,{Command:()=>To,Info:()=>J_});var J_=f.Struct({name:f.String,template:f.String,description:f.String.pipe(Me),agent:f.String.pipe(Me),model:Lu.Ref.pipe(Me),subtask:f.Boolean.pipe(Me)}).annotate({identifier:"CommandV2.Info"});var Y_=To.Info,wn=class extends te.Service()("@opencode/v2/Command"){static{i(this,"Service")}},Op=V.effect(wn,a.sync(()=>{let t=mt.create({initial:i(()=>({commands:new Map}),"initial"),draft:i(e=>({list:i(()=>Array.from(e.commands.values()),"list"),get:i(r=>e.commands.get(r),"get"),update:i((r,n)=>{let o=e.commands.get(r)??{name:r,template:""};e.commands.has(r)||e.commands.set(r,o),n(o),o.name=r},"update"),remove:i(r=>{e.commands.delete(r)},"remove")}),"draft")});return wn.of({reload:t.reload,transform:t.transform,get:a.fn("CommandV2.get")(function*(e){return t.get().commands.get(e)}),list:a.fn("CommandV2.list")(function*(){return Array.from(t.get().commands.values())})})})),X_=Op,Q_=Qe({service:wn,layer:Op,deps:[]});var Ao={};H(Ao,{ConfigAgentPlugin:()=>Ao,Plugin:()=>kv});import gv from"path";var ct={};H(ct,{AskResult:()=>pv,AssertInput:()=>dv,BlockedError:()=>xs,CorrectedError:()=>Es,DeclinedError:()=>Pn,Effect:()=>Vu,Event:()=>Oo,ID:()=>In,NotFoundError:()=>Ps,PermissionV2:()=>ct,Reply:()=>zp,ReplyInput:()=>uv,Request:()=>lv,Rule:()=>Fu,Ruleset:()=>Hu,Service:()=>Rn,Source:()=>av,evaluate:()=>ks,locationLayer:()=>mv,merge:()=>fv,node:()=>hv});var xn={};H(xn,{AddInput:()=>nv,ID:()=>Mp,Info:()=>tv,ListInput:()=>rv,PermissionSaved:()=>xn,Service:()=>En,node:()=>iv});var bn=Zu("permission",{id:Po().$type().primaryKey(),project_id:Po().$type().notNull().references(()=>ep.id,{onDelete:"cascade"}),action:Po().notNull(),resource:Po().notNull(),...Qu},t=>[Ku("permission_project_action_resource_idx").on(t.project_id,t.action,t.resource)]);var kn={};H(kn,{ID:()=>Ap,Info:()=>ev,PermissionSaved:()=>kn});var Ap=f.String.pipe(f.brand("PermissionSaved.ID"),Nu(t=>({create:i(()=>t.make("psv_"+ju()),"create")}))),ev=f.Struct({id:Ap,projectID:qu,action:f.String,resource:f.String}).annotate({identifier:"PermissionSaved.Info"});var Mp=kn.ID,tv=kn.Info,rv=f.Struct({projectID:Xa.ID.pipe(f.optional)}).annotate({identifier:"PermissionSaved.ListInput"}),nv=f.Struct({projectID:Xa.ID,action:f.String,resources:f.Array(f.String)}).annotate({identifier:"PermissionSaved.AddInput"}),En=class extends te.Service()("@opencode/v2/PermissionSaved"){static{i(this,"Service")}},ov=V.effect(En,a.gen(function*(){let{db:t}=yield*Ja.Service,e=a.fn("PermissionSaved.list")(function*(o){return(yield*t.select().from(bn).where(o?.projectID?Wa(bn.project_id,o.projectID):void 0).all().pipe(a.orDie)).map(c=>({id:c.id,projectID:c.project_id,action:c.action,resource:c.resource}))}),r=a.fn("PermissionSaved.add")(function*(o){o.resources.length&&(yield*t.insert(bn).values(o.resources.map(s=>({id:Mp.create(),project_id:o.projectID,action:o.action,resource:s}))).onConflictDoNothing().run().pipe(a.orDie))}),n=a.fn("PermissionSaved.remove")(function*(o){yield*t.delete(bn).where(Wa(bn.id,o)).run().pipe(a.orDie)});return En.of({list:e,add:r,remove:n})})),iv=pr({service:En,layer:ov,deps:[Ja.node]});var sv=[{action:"*",resource:"*",effect:"deny"}],In=et.ID,av=et.Source,cv={sessionID:et.Request.fields.sessionID,action:et.Request.fields.action,resources:et.Request.fields.resources,save:et.Request.fields.save,metadata:et.Request.fields.metadata,source:et.Request.fields.source},lv=et.Request,zp=et.Reply,dv=f.Struct({id:In.pipe(f.optional),...cv,agent:de.ID.pipe(f.optional)}).annotate({identifier:"PermissionV2.AssertInput"}),uv=f.Struct({requestID:In,reply:zp,message:f.String.pipe(f.optional)}).annotate({identifier:"PermissionV2.ReplyInput"}),pv=f.Struct({id:In,effect:et.Effect}).annotate({identifier:"PermissionV2.AskResult"}),Oo=et.Event,Pn=class extends f.TaggedErrorClass()("PermissionV2.DeclinedError",{}){static{i(this,"DeclinedError")}},Es=class extends f.TaggedErrorClass()("PermissionV2.CorrectedError",{feedback:f.String}){static{i(this,"CorrectedError")}},xs=class extends f.TaggedErrorClass()("PermissionV2.BlockedError",{rules:et.Ruleset}){static{i(this,"BlockedError")}},Ps=class extends f.TaggedErrorClass()("PermissionV2.NotFoundError",{requestID:In}){static{i(this,"NotFoundError")}};function ks(t,e,...r){return r.flat().findLast(n=>Bt.match(t,n.action)&&Bt.match(e,n.resource))??{action:t,resource:"*",effect:"ask"}}i(ks,"evaluate");function fv(...t){return t.flat()}i(fv,"merge");var Rn=class extends te.Service()("@opencode/v2/Permission"){static{i(this,"Service")}},Dp=V.effect(Rn,a.gen(function*(){let t=yield*Ie.Service,e=yield*Ne.Service,r=yield*de.Service,n=yield*Qa.Service,o=yield*xn.Service,s=new Map;yield*a.addFinalizer(()=>a.forEach(s.values(),w=>pe.fail(w.deferred,new Pn),{discard:!0}).pipe(a.ensuring(a.sync(()=>{s.clear()}))));let c=a.fnUntraced(function*(){return(yield*o.list({projectID:e.project.id})).map(w=>({action:w.action,resource:w.resource,effect:"allow"}))}),l=a.fn("PermissionV2.configured")(function*(w,P){let I=yield*n.get(w);return I?(yield*r.resolve(P??I.agent))?.permissions??sv:yield*new ap.NotFoundError({sessionID:w})});function d(w,P){return w.resources.some(I=>ks(w.action,I,P).effect==="deny")}i(d,"denied");function u(w,P){return P.filter(I=>Bt.match(w.action,I.action))}i(u,"relevant");let p=a.fnUntraced(function*(w){let P=yield*l(w.sessionID,w.agent);if(d(w,P))return{effect:"deny",rules:P};let I=[...P,...yield*c()],L=w.resources.map(Be=>ks(w.action,Be,I).effect);return{effect:L.includes("deny")?"deny":L.includes("ask")?"ask":"allow",rules:I}});function m(w){return{id:w.id??In.create(),sessionID:w.sessionID,action:w.action,resources:w.resources,save:w.save,metadata:w.metadata,source:w.source}}i(m,"request");let g=i((w,P)=>a.uninterruptible(a.gen(function*(){let I=yield*pe.make(),L={request:w,agent:P,deferred:I};return s.has(w.id)?yield*a.die(`Duplicate pending permission ID: ${w.id}`):(s.set(w.id,L),yield*t.publish(Oo.Asked,w).pipe(a.onError(()=>a.sync(()=>s.delete(w.id)))),L)})),"create"),y=a.fn("PermissionV2.ask")(function*(w){let P=yield*p(w),I=m(w);return P.effect==="ask"&&(yield*g(I,w.agent)),{id:I.id,effect:P.effect}}),h=a.fn("PermissionV2.assert")(w=>a.uninterruptibleMask(P=>a.gen(function*(){let I=yield*p(w);if(I.effect==="deny")return yield*new xs({rules:u(w,I.rules)});if(I.effect==="allow")return;let L=yield*g(m(w),w.agent);return yield*P(pe.await(L.deferred)).pipe(a.catchTag("PermissionV2.DeclinedError",F=>a.die(F)),a.ensuring(a.sync(()=>{s.delete(L.request.id)})))}))),_=a.fn("PermissionV2.reply")(w=>a.uninterruptible(a.gen(function*(){let P=s.get(w.requestID);if(!P)return yield*new Ps({requestID:w.requestID});if(yield*t.publish(Oo.Replied,{sessionID:P.request.sessionID,requestID:P.request.id,reply:w.reply}),w.reply==="reject"){yield*pe.fail(P.deferred,w.message?new Es({feedback:w.message}):new Pn),s.delete(w.requestID);for(let[L,F]of s)F.request.sessionID===P.request.sessionID&&(yield*t.publish(Oo.Replied,{sessionID:F.request.sessionID,requestID:F.request.id,reply:"reject"}),yield*pe.fail(F.deferred,new Pn),s.delete(L));return}if(w.reply==="always"&&P.request.save?.length&&(yield*o.add({projectID:e.project.id,action:P.request.action,resources:P.request.save})),yield*pe.succeed(P.deferred,void 0),s.delete(w.requestID),w.reply!=="always"||!P.request.save?.length)return;let I=yield*c();for(let[L,F]of s){let Be={...F.request},Gt=yield*l(F.request.sessionID,F.agent).pipe(a.catchTag("Session.NotFoundError",()=>a.succeed(void 0)));if(!Gt||d(Be,Gt))continue;let xt=[...Gt,...I];F.request.resources.every(Tr=>ks(F.request.action,Tr,xt).effect==="allow")&&(yield*t.publish(Oo.Replied,{sessionID:F.request.sessionID,requestID:F.request.id,reply:"always"}),yield*pe.succeed(F.deferred,void 0),s.delete(L))}}))),S=a.fn("PermissionV2.list")(function*(){return Array.from(s.values(),w=>w.request)}),E=a.fn("PermissionV2.get")(function*(w){return s.get(w)?.request}),x=a.fn("PermissionV2.forSession")(function*(w){return Array.from(s.values(),P=>P.request).filter(P=>P.sessionID===w)});return Rn.of({ask:y,assert:h,reply:_,get:E,forSession:x,list:S})})),mv=Dp.pipe(V.provideMerge(de.locationLayer)),hv=Qe({service:Rn,layer:Dp,deps:[Ie.node,Ne.node,de.node,Qa.node,xn.node]});var yv=[{pattern:"{agent,agents}/**/*.md",primary:!1},{pattern:"{mode,modes}/*.md",primary:!0}],_v=f.decodeUnknownOption(tp.Info),vv=f.decodeUnknownOption(np.Info),Sv=f.decodeUnknownOption(Ee.Info),wv=["external_directory","read","edit"],bv=new Set(["model","variant","request","system","description","mode","hidden","color","steps","disabled","permissions"]),kv={id:"config-agent",effect:a.fn(function*(t){let e=yield*Ee.Service,r=yield*ae.Service,n=yield*se.Service;yield*t.agent.transform(a.fn(function*(o){let s=yield*a.forEach(yield*e.entries(),d=>d.type==="document"?a.succeed([d]):a.gen(function*(){let u=yield*Pv(r,d.path);return yield*a.forEach(u,p=>r.readFileStringSafe(p.filepath).pipe(a.map(m=>m&&Rv(p,m)),a.catch(()=>a.succeed(void 0)))).pipe(a.map(p=>p.filter(m=>m!==void 0)))})).pipe(a.map(d=>d.flat())),c=Np(s.flatMap(d=>d.info.permissions??[]),n.home),l=Ee.latest(s,"default_agent");l!==void 0&&o.default(de.ID.make(l));for(let d of o.list())o.update(d.id,u=>u.permissions.push(...c));for(let d of s)for(let[u,p]of Object.entries(d.info.agents??{})){let m=de.ID.make(u);if(p.disabled){o.remove(m);continue}let g=o.get(m)!==void 0;o.update(m,y=>{if(g||y.permissions.push(...c),p.model!==void 0){let h=ve.parse(p.model);y.model={id:h.modelID,providerID:h.providerID,variant:y.model?.variant}}p.variant!==void 0&&y.model!==void 0&&(y.model.variant=ve.VariantID.make(p.variant)),p.request!==void 0&&(Object.assign(y.request.headers,p.request.headers??{}),Object.assign(y.request.body,p.request.body??{})),p.system!==void 0&&(y.system=p.system),p.description!==void 0&&(y.description=p.description),p.mode!==void 0&&(y.mode=p.mode),p.hidden!==void 0&&(y.hidden=p.hidden),p.color!==void 0&&(y.color=p.color),p.steps!==void 0&&(y.steps=p.steps),p.permissions!==void 0&&y.permissions.push(...Np(p.permissions,n.home))})}}))})};function Np(t,e){return t.map(r=>Ev(r.action)?{...r,resource:xv(r.resource,e)}:r)}i(Np,"expandPermissions");function Ev(t){return wv.some(e=>e===t)}i(Ev,"isPathAction");function xv(t,e){return t.startsWith("~/")?e+t.slice(1):t==="~"||t==="$HOME"?e:t.startsWith("$HOME/")||t.startsWith("$HOME\\")?e+t.slice(5):t}i(xv,"expandHome");function Pv(t,e){return a.forEach(yv,r=>t.glob(r.pattern,{cwd:e,absolute:!0,dot:!0,symlink:!0}).pipe(a.map(n=>n.toSorted().map(o=>({directory:e,filepath:o,primary:r.primary}))))).pipe(a.map(r=>r.flat()),a.catch(()=>a.succeed([])))}i(Pv,"discover");function Rv(t,e){let r=hn.parseOption(e);if(!r)return;let n=gv.relative(t.directory,t.filepath).replaceAll("\\","/").replace(/^(agent|agents|mode|modes)\//,"").replace(/\.md$/,""),o=r.content.trim(),s=Object.keys(r.data).some(d=>!bv.has(d)),c=pt.getOrUndefined(s?pt.map(vv({name:n,...r.data,prompt:o},{errors:"all",propertyOrder:"original"}),sp.migrateAgent):_v({...r.data,system:o},{errors:"all",propertyOrder:"original"}));if(!c)return;let l=pt.getOrUndefined(Sv({agents:{[n]:t.primary?{...c,mode:"primary"}:c}}));if(l)return new Ee.Document({type:"document",path:t.filepath,info:l})}i(Rv,"decode");var Mo={};H(Mo,{ConfigCommandPlugin:()=>Mo,Plugin:()=>$v});import Iv from"path";var Cv=f.decodeUnknownOption(rp.Info),$v={id:"config-command",effect:a.fn(function*(t){let e=yield*Ee.Service,r=yield*ae.Service;yield*t.command.transform(a.fn(function*(n){let o=yield*a.forEach(yield*e.entries(),s=>s.type==="document"?a.succeed([{commands:s.info.commands}]):Tv(r,s.path).pipe(a.map(c=>[{commands:Object.fromEntries(c.map(l=>[l.name,l.info]))}]))).pipe(a.map(s=>s.flat()));for(let s of o)for(let[c,l]of Object.entries(s.commands??{}))n.update(c,d=>{if(d.template=l.template,l.description!==void 0&&(d.description=l.description),l.agent!==void 0&&(d.agent=l.agent),l.model!==void 0){let u=ve.parse(l.model);d.model={id:u.modelID,providerID:u.providerID,variant:d.model?.variant}}l.variant!==void 0&&d.model!==void 0&&(d.model.variant=ve.VariantID.make(l.variant)),l.subtask!==void 0&&(d.subtask=l.subtask)})}))})};function Tv(t,e){return a.gen(function*(){let r=yield*t.glob("{command,commands}/**/*.md",{cwd:e,absolute:!0,dot:!0,symlink:!0}).pipe(a.catch(()=>a.succeed([])));return yield*a.forEach(r.toSorted(),n=>t.readFileStringSafe(n).pipe(a.map(o=>o===void 0?void 0:Ov(e,n,o)),a.catch(()=>a.succeed(void 0)))).pipe(a.map(n=>n.filter(o=>o!==void 0)))})}i(Tv,"loadDirectory");function Ov(t,e,r){let n=hn.parseOption(r);if(!n)return;let o=pt.getOrUndefined(Cv({...n.data,template:n.content.trim()}));if(o)return{name:Iv.relative(t,e).replaceAll("\\","/").replace(/^(command|commands)\//,"").replace(/\.md$/,""),info:o}}i(Ov,"decode");var Do={};H(Do,{ConfigExternalPlugin:()=>Do,Plugin:()=>Dv});import lc from"path";import{fileURLToPath as Av,pathToFileURL as Mv}from"url";var zo={};H(zo,{PluginPromise:()=>zo,fromPromise:()=>jp});function jp(t){return{id:t.id,effect:i(e=>a.gen(function*(){let r=yield*He.Scope,n=yield*a.context(),o=i(d=>a.runPromiseWith(n)(He.provide(r)(d)).then(u=>({dispose:i(()=>a.runPromiseWith(n)(u.dispose),"dispose")})),"register"),s=i(d=>a.runPromiseWith(n)(d),"run"),c=i(d=>u=>o(d.transform(p=>a.promise(()=>Promise.resolve(u(p))))),"transform"),l={options:e.options,agent:{transform:c(e.agent),reload:i(()=>s(e.agent.reload()),"reload")},aisdk:{sdk:i(d=>o(e.aisdk.sdk(u=>a.promise(()=>Promise.resolve(d(u))))),"sdk"),language:i(d=>o(e.aisdk.language(u=>a.promise(()=>Promise.resolve(d(u))))),"language")},catalog:{transform:c(e.catalog),reload:i(()=>s(e.catalog.reload()),"reload")},command:{transform:c(e.command),reload:i(()=>s(e.command.reload()),"reload")},integration:{transform:c(e.integration),reload:i(()=>s(e.integration.reload()),"reload"),connection:{active:i(d=>a.runPromiseWith(n)(e.integration.connection.active(d)),"active"),resolve:i(d=>a.runPromiseWith(n)(e.integration.connection.resolve(d)),"resolve")}},plugin:{add:i(d=>{let u=jp(d);return s(e.plugin.add(u))},"add"),remove:i(d=>s(e.plugin.remove(d)),"remove")},reference:{transform:c(e.reference),reload:i(()=>s(e.reference.reload()),"reload")},skill:{transform:c(e.skill),reload:i(()=>s(e.skill.reload()),"reload")}};yield*a.promise(()=>Promise.resolve(t.setup(l)))}),"effect")}}i(jp,"fromPromise");var zv=f.Struct({default:f.Union([f.Struct({id:f.String,effect:f.declare(t=>typeof t=="function")}),f.Struct({id:f.String,setup:f.declare(t=>typeof t=="function")})])}),Dv={id:"config-plugin",effect:a.fn(function*(t){let e=yield*Ee.Service,r=yield*ae.Service,n=yield*Ne.Service,o=yield*Nt.Service;yield*a.gen(function*(){let s=[];for(let c of yield*e.entries()){if(c.type==="document"){let l=c.path?lc.dirname(c.path):n.directory;for(let d of c.info.plugins??[]){let u=typeof d=="string"?{package:d}:d,p=u.package.startsWith("file://")?Av(u.package):u.package.startsWith("./")||u.package.startsWith("../")?lc.resolve(l,u.package):u.package;s.push({package:p,options:u.options})}}if(c.type==="directory"){let l=yield*r.glob("{plugin,plugins}/*.{ts,js}",{cwd:c.path,absolute:!0,include:"file",dot:!0,symlink:!0}).pipe(a.orElseSucceed(()=>[]));l.sort();for(let d of l)s.push({package:d})}}for(let c of s)yield*a.gen(function*(){let l=lc.isAbsolute(c.package)?Mv(c.package).href:(yield*o.add(c.package)).entrypoint;if(!l)return;let d=yield*a.promise(()=>import(l)),u=(yield*f.decodeUnknownEffect(zv)(d)).default,p="effect"in u?u:zo.fromPromise(u);yield*t.plugin.add({id:p.id,effect:i(m=>p.effect({...m,options:c.options??{}}),"effect")})}).pipe(a.ignoreCause)}).pipe(a.forkScoped({startImmediately:!0}))})};var No={};H(No,{ConfigProviderPlugin:()=>No,Plugin:()=>Nv});var Nv={id:"config-provider",effect:a.fn(function*(t){let e=yield*Ee.Service;yield*t.integration.transform(a.fn(function*(r){let n=(yield*e.entries()).filter(s=>s.type==="document"),o=new Set(n.flatMap(s=>Object.entries(s.info.providers??{}).flatMap(([c,l])=>l.env===void 0?[]:[c])));for(let s of n)for(let[c,l]of Object.entries(s.info.providers??{})){let d=c;!o.has(c)&&!r.get(d)||(r.update(d,u=>{u.name=l.name??u.name}),l.env!==void 0&&r.method.update({integrationID:d,method:{type:"env",names:[...l.env]}}))}})),yield*t.catalog.transform(a.fn(function*(r){let n=yield*e.entries(),o=n.filter(c=>c.type==="document"),s=Ee.latest(n,"model");if(s!==void 0){let c=ve.parse(s);r.model.default.set(c.providerID,c.modelID)}for(let c of o)for(let[l,d]of Object.entries(c.info.providers??{})){let u=l;r.provider.update(u,p=>{d.name!==void 0&&(p.name=d.name),d.api!==void 0&&(p.api={...d.api}),d.request!==void 0&&(Object.assign(p.request.headers,d.request.headers),Object.assign(p.request.body,d.request.body))});for(let[p,m]of Object.entries(d.models??{}))r.model.update(u,p,g=>{if(m.family!==void 0&&(g.family=m.family),m.name!==void 0&&(g.name=m.name),m.api!==void 0&&(g.api={...g.api,...m.api}),m.capabilities!==void 0&&(g.capabilities={tools:m.capabilities.tools,input:[...m.capabilities.input],output:[...m.capabilities.output]}),m.request!==void 0&&(Object.assign(g.request.headers,m.request.headers),Object.assign(g.request.body,m.request.body),m.request.variant!==void 0&&(g.request.variant=m.request.variant)),m.variants!==void 0)for(let y of m.variants){let h=g.variants.find(_=>_.id===y.id);h||(h={id:y.id,headers:{},body:{}},g.variants.push(h)),Object.assign(h.headers,y.headers),Object.assign(h.body,y.body)}m.cost!==void 0&&(g.cost=(Array.isArray(m.cost)?m.cost:[m.cost]).map(y=>({tier:y.tier&&{...y.tier},input:y.input,output:y.output,cache:{read:y.cache?.read??0,write:y.cache?.write??0}}))),m.disabled!==void 0&&(g.enabled=!m.disabled),m.limit!==void 0&&(g.limit={...g.limit,...m.limit})})}}))})};var Bo={};H(Bo,{ConfigReferencePlugin:()=>Bo,Plugin:()=>sS});import Is from"path";var Ze={};H(Ze,{Event:()=>Yp,GitSource:()=>rS,Info:()=>mc,LocalSource:()=>tS,Reference:()=>Ze,Service:()=>Tn,Source:()=>nS,locationLayer:()=>oS,node:()=>iS});var Qt={};H(Qt,{Event:()=>jv,GitSource:()=>Up,Info:()=>dc,LocalSource:()=>Lp,Reference:()=>Qt,Source:()=>Vp});var qp=pn({type:"reference.updated",schema:{}}),jv={Updated:qp,Definitions:fn(qp)},Lp=f.Struct({type:f.Literal("local"),path:_e,description:f.String.pipe(Me),hidden:f.Boolean.pipe(Me)}).annotate({identifier:"Reference.LocalSource"}),Up=f.Struct({type:f.Literal("git"),repository:f.String,branch:f.String.pipe(Me),description:f.String.pipe(Me),hidden:f.Boolean.pipe(Me)}).annotate({identifier:"Reference.GitSource"}),Vp=f.Union([Lp,Up]).pipe(f.toTaggedUnion("type")).annotate({identifier:"Reference.Source"}),dc=class extends f.Class("Reference.Info")({name:f.String,path:_e,description:f.String.pipe(Me),hidden:f.Boolean.pipe(Me),source:Vp}){static{i(this,"Info")}};var Je={};H(Je,{InvalidBranchError:()=>Uo,InvalidReferenceError:()=>qo,Repository:()=>Je,UnsupportedLocalRepositoryError:()=>Lo,cacheIdentity:()=>pc,cachePath:()=>Fv,isError:()=>Lv,isFile:()=>Zp,isRemote:()=>Kp,parse:()=>Hp,parseRemote:()=>Uv,same:()=>Hv,validateBranch:()=>Vv});import Fp from"path";import{fileURLToPath as qv}from"url";var qo=class extends f.TaggedErrorClass()("RepositoryInvalidReferenceError",{repository:f.String,message:f.String}){static{i(this,"InvalidReferenceError")}},Lo=class extends f.TaggedErrorClass()("RepositoryUnsupportedLocalRepositoryError",{repository:f.String,message:f.String}){static{i(this,"UnsupportedLocalRepositoryError")}},Uo=class extends f.TaggedErrorClass()("RepositoryInvalidBranchError",{branch:f.String,message:f.String}){static{i(this,"InvalidBranchError")}};function Lv(t){return t instanceof qo||t instanceof Lo||t instanceof Uo}i(Lv,"isError");function Hp(t){let e=Zv(t);if(!e)return;let r=e.match(/^github:([^/\s]+)\/([^/\s]+)$/);if(r)return jo({host:"github.com",segments:[r[1],r[2]]});if(!e.includes("://")){let n=e.match(/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/);if(n)return jo({host:n[1],segments:uc(n[2]),remote:e});let o=uc(e);if(o.length>=2&&Wv(o[0]))return jo({host:o[0],segments:o.slice(1)});if(o.length===2)return jo({host:"github.com",segments:o})}try{let n=new URL(e);if(n.protocol==="file:")return Jv({url:n,remote:e});let o=uc(n.pathname);return jo({host:n.host,segments:o,remote:n.host==="github.com"?Gp(o.join("/")):e,protocol:n.protocol})}catch{return}}i(Hp,"parse");function Uv(t){let e=Hp(t);if(!e)throw new qo({repository:t,message:"Repository must be a git URL, host/path reference, or GitHub owner/repo shorthand"});if(!Kp(e))throw new Lo({repository:t,message:"Local file repositories are not supported"});return e}i(Uv,"parseRemote");function Vv(t){if(!(/^[A-Za-z0-9/_.-]+$/.test(t)&&!t.startsWith("-")&&!t.includes("..")))throw new Uo({branch:t,message:"Branch must contain only alphanumeric characters, /, _, ., and -, and cannot start with - or contain .."})}i(Vv,"validateBranch");function Zp(t){return t.protocol==="file:"}i(Zp,"isFile");function Kp(t){return!Zp(t)}i(Kp,"isRemote");function Fv(t,e,r){let n=Fp.join(t,...e.host.split(":"),...e.segments);return r?`${n}@${encodeURIComponent(r)}`:n}i(Fv,"cachePath");function pc(t){return`${t.host}/${t.path}`}i(pc,"cacheIdentity");function Hv(t,e){return pc(t)===pc(e)}i(Hv,"same");function Zv(t){return t.trim().replace(/^git\+/,"").replace(/#.*$/,"").replace(/\/+$/,"")}i(Zv,"normalizeInput");function fc(t){return t.replace(/\.git$/,"")}i(fc,"trimGitSuffix");function uc(t){return t.split("/").map(e=>fc(e.trim())).filter(Boolean)}i(uc,"parts");function Kv(t){return!!t&&!t.startsWith("-")&&!/[\s/\\]/.test(t)}i(Kv,"safeHost");function Gv(t){return t!=="."&&t!==".."&&!t.includes(":")&&!/[\s/\\]/.test(t)}i(Gv,"safeSegment");function Wv(t){return t.includes(".")||t.includes(":")||t==="localhost"}i(Wv,"hostLike");function Bv(t){return t.endsWith("/")?t:`${t}/`}i(Bv,"withSlash");function Gp(t){let e=process.env.OPENCODE_REPO_CLONE_GITHUB_BASE_URL;return e?new URL(`${t}.git`,Bv(e)).href:`https://github.com/${t}.git`}i(Gp,"githubRemote");function jo(t){let e=t.segments.map(fc).filter(Boolean);if(!Kv(t.host)||!e.length||e.some(o=>!Gv(o)))return;let r=e.join("/"),n=t.host.toLowerCase();return{host:n,path:r,segments:e,owner:e.length===2?e[0]:void 0,repo:e[e.length-1],remote:t.remote??(n==="github.com"?Gp(r):`https://${n}/${r}.git`),label:n==="github.com"&&e.length===2?r:`${n}/${r}`,protocol:t.protocol}}i(jo,"buildRemote");function Jv(t){let e=Fp.normalize(qv(t.url)),r=e.split(/[\\/]+/).filter(Boolean);if(r.length)return{host:"file",path:e,segments:r.map(n=>n.replace(/:$/,"")),owner:void 0,repo:fc(r[r.length-1]),remote:t.remote,label:e,protocol:"file:"}}i(Jv,"buildFile");var $n={};H($n,{CacheOperationError:()=>Wo,CheckoutFailedError:()=>Zo,CloneFailedError:()=>Ho,FetchFailedError:()=>Dr,InvalidBranchError:()=>Fo,InvalidRepositoryError:()=>Vo,LockFailedError:()=>Go,RepositoryCache:()=>$n,ResetFailedError:()=>Ko,Service:()=>Cn,isError:()=>Bp,node:()=>eS,parseRemote:()=>Xv,validateBranch:()=>Jp});import Yv from"path";var Vo=class extends f.TaggedErrorClass()("RepositoryCacheInvalidRepositoryError",{repository:f.String,message:f.String}){static{i(this,"InvalidRepositoryError")}},Fo=class extends f.TaggedErrorClass()("RepositoryCacheInvalidBranchError",{branch:f.String,message:f.String}){static{i(this,"InvalidBranchError")}},Ho=class extends f.TaggedErrorClass()("RepositoryCacheCloneFailedError",{repository:f.String,message:f.String}){static{i(this,"CloneFailedError")}},Dr=class extends f.TaggedErrorClass()("RepositoryCacheFetchFailedError",{repository:f.String,message:f.String}){static{i(this,"FetchFailedError")}},Zo=class extends f.TaggedErrorClass()("RepositoryCacheCheckoutFailedError",{repository:f.String,branch:f.String,message:f.String}){static{i(this,"CheckoutFailedError")}},Ko=class extends f.TaggedErrorClass()("RepositoryCacheResetFailedError",{repository:f.String,message:f.String}){static{i(this,"ResetFailedError")}},Go=class extends f.TaggedErrorClass()("RepositoryCacheLockFailedError",{localPath:f.String,message:f.String}){static{i(this,"LockFailedError")}},Wo=class extends f.TaggedErrorClass()("RepositoryCacheOperationError",{operation:f.String,path:f.String,message:f.String}){static{i(this,"CacheOperationError")}},Cn=class extends te.Service()("@opencode/RepositoryCache"){static{i(this,"Service")}};function Bp(t){return t instanceof Vo||t instanceof Fo||t instanceof Ho||t instanceof Dr||t instanceof Zo||t instanceof Ko||t instanceof Go||t instanceof Wo}i(Bp,"isError");var Xv=a.fn("RepositoryCache.parseRemote")(function*(t){return yield*a.try({try:i(()=>Je.parseRemote(t),"try"),catch:i(e=>new Vo({repository:t,message:Rs(e)}),"catch")})}),Jp=a.fn("RepositoryCache.validateBranch")(function*(t){return yield*a.try({try:i(()=>Je.validateBranch(t),"try"),catch:i(e=>new Fo({branch:t,message:Rs(e)}),"catch")})}),Qv=V.effect(Cn,a.gen(function*(){let t=yield*ae.Service,e=yield*Ya.Service,r=yield*mn.Service,n=yield*se.Service;return Cn.of({ensure:a.fn("RepositoryCache.ensure")(function*(o){o.branch&&(yield*Jp(o.branch));let s=o.reference.label,c=Je.cachePath(n.repos,o.reference,o.branch),l=Je.parse(o.reference.remote)??o.reference;return yield*r.withLock(a.gen(function*(){yield*Wp(t.ensureDir(Yv.dirname(c)),"ensure cache directory",c);let d=yield*e.repo.discover(_e.make(c)),u=d?yield*e.remote.get(d):void 0,p=u?Je.parse(u):void 0,m=d?yield*t.resolve(c):void 0,g=!!(d&&d.worktree===m&&p&&Je.same(p,l));!g&&(yield*t.existsSafe(c))&&(yield*Wp(t.remove(c,{recursive:!0}),"remove stale cache",c));let y=g?o.refresh?"refreshed":"cached":"cloned";if(y==="cloned"&&(yield*e.repo.clone({remote:o.reference.remote,directory:_e.make(c),branch:o.branch}).pipe(a.mapError(_=>new Ho({repository:s,message:_.message})))),y==="refreshed"){if(!d)return yield*new Dr({repository:s,message:"Repository is unavailable"});yield*e.sync.fetchRemotes(d).pipe(a.mapError(E=>new Dr({repository:s,message:E.message}))),o.branch&&(yield*e.sync.fetchBranch(d,{branch:o.branch}).pipe(a.mapError(E=>new Dr({repository:s,message:E.message}))));let _=o.branch??(yield*e.history.defaultRemoteBranch(d));_&&(yield*e.sync.checkoutRemoteBranch(d,{branch:_}).pipe(a.mapError(E=>new Zo({repository:s,branch:_,message:E.message}))));let S=_??(yield*e.history.branch(d));yield*e.sync.resetHard(d,S?`origin/${S}`:"HEAD").pipe(a.mapError(E=>new Ko({repository:s,message:E.message})))}let h=yield*e.repo.discover(_e.make(c));return{repository:s,host:o.reference.host,remote:o.reference.remote,localPath:c,status:y,head:h?yield*e.history.head(h):void 0,branch:h?yield*e.history.branch(h):void 0}}),`repository-cache:${c}`).pipe(a.mapError(d=>Bp(d)?d:new Go({localPath:c,message:Rs(d)})))})})})),eS=pr({service:Cn,layer:Qv,deps:[mn.node,ae.node,Ya.node,se.node]});function Rs(t){return t instanceof globalThis.Error?t.message:String(t)}i(Rs,"errorMessage");function Wp(t,e,r){return t.pipe(a.mapError(n=>new Wo({operation:e,path:r,message:Rs(n)})))}i(Wp,"cacheOperation");var tS=Qt.LocalSource,rS=Qt.GitSource,nS=Qt.Source,Yp=Qt.Event,mc=Qt.Info,Tn=class extends te.Service()("@opencode/v2/Reference"){static{i(this,"Service")}},Xp=V.effect(Tn,a.gen(function*(){let t=yield*se.Service,e=yield*Ie.Service,r=yield*$n.Service,n=yield*He.Scope,o=new Map,s=mt.create({initial:i(()=>({sources:new Map}),"initial"),draft:i(c=>({add:i((l,d)=>c.sources.set(l,d),"add"),remove:i(l=>c.sources.delete(l),"remove"),list:i(()=>Array.from(c.sources.entries()),"list")}),"draft"),finalize:i(c=>a.gen(function*(){o.clear();for(let[l,d]of c.list()){if(d.type==="local"){o.set(l,new mc({name:l,path:d.path,...d.description===void 0?{}:{description:d.description},...d.hidden===void 0?{}:{hidden:d.hidden},source:d}));continue}let u=Je.parse(d.repository);if(!(!u||!Je.isRemote(u))){if(d.branch)try{Je.validateBranch(d.branch)}catch{continue}o.set(l,new mc({name:l,path:_e.make(Je.cachePath(t.repos,u,d.branch)),...d.description===void 0?{}:{description:d.description},...d.hidden===void 0?{}:{hidden:d.hidden},source:d})),yield*r.ensure({reference:u,branch:d.branch,refresh:!0}).pipe(a.catchCause(p=>a.logWarning("failed to materialize reference",{name:l,repository:d.repository,cause:p})),a.forkIn(n))}}yield*e.publish(Yp.Updated,{})}),"finalize")});return Tn.of({transform:s.transform,reload:s.reload,list:a.fn("Reference.list")(function*(){return Array.from(o.values())})})})),oS=Xp,iS=Qe({service:Tn,layer:Xp,deps:[se.node,Ie.node,$n.node]});var sS={id:"core/config-reference",effect:a.fn(function*(t){let e=yield*Ee.Service,r=yield*Ne.Service,n=yield*se.Service;yield*t.reference.transform(a.fn(function*(o){let s=new Map;for(let c of(yield*e.entries()).filter(l=>l.type==="document")){let l=c.path?Is.dirname(c.path):r.directory;for(let[d,u]of Object.entries(c.info.references??{})){if(!aS(d))continue;let p=typeof u=="string"?void 0:u.description,m=typeof u=="string"?void 0:u.hidden;s.set(d,cS(u)?Ze.LocalSource.make({type:"local",path:_e.make(lS(l,n.home,typeof u=="string"?u:u.path)),...p===void 0?{}:{description:p},...m===void 0?{}:{hidden:m}}):Ze.GitSource.make({type:"git",repository:typeof u=="string"?u:u.repository,...u.branch===void 0?{}:{branch:u.branch},...p===void 0?{}:{description:p},...m===void 0?{}:{hidden:m}}))}}for(let[c,l]of s)o.add(c,l)}))})};function aS(t){return t.length>0&&!/[\/\s`,]/.test(t)}i(aS,"validAlias");function cS(t){return typeof t=="string"?t.startsWith(".")||t.startsWith("/")||t.startsWith("~"):"path"in t}i(cS,"local");function lS(t,e,r){return r.startsWith("~/")?Is.join(e,r.slice(2)):Is.isAbsolute(r)?r:Is.resolve(t,r)}i(lS,"localPath");var Yo={};H(Yo,{ConfigSkillPlugin:()=>Yo,Plugin:()=>xS});import Jo from"path";var Ce={};H(Ce,{DirectorySource:()=>gS,EmbeddedSource:()=>_S,Info:()=>vS,Service:()=>Mn,SkillV2:()=>Ce,Source:()=>yc,UrlSource:()=>yS,available:()=>SS,node:()=>ES});import of from"path";var er={};H(er,{DirectorySource:()=>Qp,EmbeddedSource:()=>rf,Info:()=>tf,Skill:()=>er,Source:()=>dS,UrlSource:()=>ef});var Qp=f.Struct({type:f.Literal("directory"),path:_e}).annotate({identifier:"SkillV2.DirectorySource"}),ef=f.Struct({type:f.Literal("url"),url:f.String}).annotate({identifier:"SkillV2.UrlSource"}),tf=f.Struct({name:f.String,description:f.String.pipe(Me),slash:f.Boolean.pipe(Me),location:_e,content:f.String}).annotate({identifier:"SkillV2.Info"}),rf=f.Struct({type:f.Literal("embedded"),skill:f.suspend(()=>tf)}).annotate({identifier:"SkillV2.EmbeddedSource"}),dS=Object.assign(f.Union([Qp,ef,rf]).pipe(f.toTaggedUnion("type"),f.annotate({identifier:"SkillV2.Source"})),{equals:i((t,e)=>t.type!==e.type?!1:t.type==="directory"&&e.type==="directory"?t.path===e.path:t.type==="url"&&e.type==="url"?t.url===e.url:t.type==="embedded"&&e.type==="embedded"?t.skill.name===e.skill.name:!1,"equals"),key:i(t=>t.type==="directory"?`directory:${t.path}`:t.type==="url"?`url:${t.url}`:`embedded:${t.skill.name}`,"key")});var An={};H(An,{Service:()=>On,SkillDiscovery:()=>An,node:()=>hS});import yt from"path";var uS=4,nf=8;function pS(t){return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}i(pS,"isSafeSegment");function fS(t){let e=t.split("/");return t.length>0&&!t.includes("\\")&&!t.includes("\0")&&!t.includes("?")&&!t.includes("#")&&!URL.canParse(t)&&!yt.posix.isAbsolute(t)&&!yt.win32.isAbsolute(t)&&e.every(r=>{try{let n=decodeURIComponent(r);return n.length>0&&n!=="."&&n!==".."&&!n.includes("/")&&!n.includes("\\")&&!n.includes("\0")}catch{return!1}})}i(fS,"isSafeRelativePath");var hc=class extends f.Class("SkillDiscovery.IndexSkill")({name:f.String,version:f.optional(f.String),files:f.Array(f.String)}){static{i(this,"IndexSkill")}},gc=class extends f.Class("SkillDiscovery.Index")({skills:f.Array(hc)}){static{i(this,"Index")}},On=class extends te.Service()("@opencode/v2/SkillDiscovery"){static{i(this,"Service")}},mS=V.effect(On,a.gen(function*(){let t=yield*ae.Service,e=yield*se.Service,r=(yield*De.HttpClient).pipe(De.retryTransient({retryOn:"errors-and-responses",times:2,schedule:Ar.exponential(200).pipe(Ar.jittered)}),De.filterStatusOk),n=a.fn("SkillDiscovery.download")(function*(o,s){return(yield*t.exists(s).pipe(a.orDie))?!0:yield*be.get(o).pipe(r.execute,a.flatMap(c=>c.arrayBuffer),a.flatMap(c=>t.writeWithDirs(s,new Uint8Array(c))),a.as(!0),a.catch(c=>a.logError("failed to download skill file",{url:o,error:c}).pipe(a.as(!1))))});return On.of({pull:a.fn("SkillDiscovery.pull")(function*(o){let s=o.endsWith("/")?o:`${o}/`,c=new URL(s),l=new URL("index.json",c).href,d=yield*be.get(l).pipe(be.acceptJson,r.execute,a.flatMap(Mt.schemaBodyJson(gc)),a.catch(p=>a.logError("failed to fetch skill index",{url:l,error:p}).pipe(a.as(void 0))));if(!d)return[];let u=yt.resolve(e.cache,"skills",Bun.hash(s).toString(16));return yield*a.forEach(d.skills.flatMap(p=>{if(!pS(p.name))return[];if(!p.files.includes("SKILL.md")&&!p.files.includes(`${p.name}.md`))return[];let m=yt.resolve(u,p.name);if(!ae.contains(u,m)||m===u)return[];let g=new URL(`${encodeURIComponent(p.name)}/`,c),y=yt.join(m,".opencode-version"),h=p.files.map(_=>{if(!fS(_))return;let S;try{S=new URL(_,g)}catch{return}if(S.origin!==c.origin)return;let E=yt.resolve(m,_);if(!(!ae.contains(m,E)||E===m))return{url:S.href,destination:E,file:_}});return h.some(_=>_===void 0)?[]:[{skill:p,root:m,versionFile:y,files:h}]}),({skill:p,root:m,versionFile:g,files:y})=>a.gen(function*(){let h=p.version,_=h===void 0?void 0:yield*t.readFileStringSafe(g).pipe(a.catch(()=>a.succeed(void 0)));if(h===void 0||_===h)yield*a.forEach(y,E=>n(E.url,E.destination),{concurrency:nf,discard:!0});else{let E=crypto.randomUUID(),x=`${m}.tmp-${E}`,w=`${m}.old-${E}`;yield*a.gen(function*(){!(yield*a.forEach(y,L=>n(L.url,yt.resolve(x,L.file)),{concurrency:nf})).every(Boolean)||!((yield*t.exists(yt.join(x,"SKILL.md")).pipe(a.orDie))||(yield*t.exists(yt.join(x,`${p.name}.md`)).pipe(a.orDie)))||(yield*t.writeFileString(yt.join(x,".opencode-version"),h),yield*a.uninterruptible(a.gen(function*(){let L=yield*t.exists(m).pipe(a.orDie);L&&(yield*t.rename(m,w)),yield*t.rename(x,m).pipe(a.catch(F=>a.gen(function*(){return L&&(yield*t.rename(w,m).pipe(a.ignore)),yield*a.fail(F)}))),L&&(yield*t.remove(w,{recursive:!0,force:!0}).pipe(a.ignore))})))}).pipe(a.catch(P=>a.logError("failed to refresh skill",{skill:p.name,error:P})),a.ensuring(t.remove(x,{recursive:!0,force:!0}).pipe(a.ignore)))}return(yield*t.exists(yt.join(m,"SKILL.md")).pipe(a.orDie))||(yield*t.exists(yt.join(m,`${p.name}.md`)).pipe(a.orDie))?[_e.make(m)]:[]}),{concurrency:uS}).pipe(a.map(p=>p.flat()))})})})),hS=pr({service:On,layer:mS,deps:[fr,ae.node,se.node]});var gS=er.DirectorySource,yS=er.UrlSource,_S=er.EmbeddedSource,yc=er.Source,vS=er.Info,SS=i((t,e)=>t.filter(r=>ct.evaluate("skill",r.name,e.permissions).effect!=="deny"),"available"),wS=f.Struct({name:f.String.pipe(f.optional),description:f.String.pipe(f.optional),slash:f.Boolean.pipe(f.optional)}),bS=f.decodeUnknownOption(wS),Mn=class extends te.Service()("@opencode/v2/Skill"){static{i(this,"Service")}},kS=V.effect(Mn,a.gen(function*(){let t=yield*An.Service,e=yield*ae.Service,r=mt.create({initial:i(()=>({sources:[]}),"initial"),draft:i(c=>({source:i(l=>{c.sources.some(d=>yc.equals(d,l))||c.sources.push(l)},"source"),list:i(()=>c.sources,"list")}),"draft")}),n=a.fn("SkillV2.load")(function*(c){let l=[];if(c.type==="embedded")return[c.skill];let d=c.type==="directory"?[c.path]:yield*t.pull(c.url);for(let u of d){let p=yield*e.glob("{*.md,**/SKILL.md}",{cwd:u,absolute:!0,include:"file",symlink:!0,dot:!0}).pipe(a.catch(()=>a.succeed([])));for(let m of p.toSorted()){let g=yield*e.readFileStringSafe(m).pipe(a.catch(()=>a.succeed(void 0)));if(!g)continue;let y=hn.parseOption(g);if(!y)continue;let h=bS(y.data).valueOrUndefined;if(!h)continue;let _=h.name!==void 0?h.name:of.dirname(m)===u?of.basename(m,".md"):void 0;_&&l.push({name:_,description:h.description,slash:h.slash,location:_e.make(m),content:y.content})}}return l}),o=new Map,s=a.fn("SkillV2.list")(function*(){let c=new Map;for(let l of r.get().sources){let d=yc.key(l),u=o.get(d)??(yield*n(l));o.set(d,u);for(let p of u)c.set(p.name,p)}return Array.from(c.values())});return Mn.of({transform:r.transform,reload:r.reload,sources:a.fn("SkillV2.sources")(function*(){return r.get().sources}),list:s})})),ES=Qe({service:Mn,layer:kS,deps:[An.node,ae.node]});var xS={id:"config-skill",effect:a.fn(function*(t){let e=yield*Ee.Service,r=yield*se.Service,n=yield*Ne.Service;yield*t.skill.transform(a.fn(function*(o){let s=yield*e.entries(),c=s.flatMap(d=>d.type==="directory"?[d.path]:[]),l=s.flatMap(d=>d.type==="document"?d.info.skills??[]:[]);for(let d of c)o.source(Ce.DirectorySource.make({type:"directory",path:_e.make(Jo.join(d,"skill"))})),o.source(Ce.DirectorySource.make({type:"directory",path:_e.make(Jo.join(d,"skills"))}));for(let d of l){if(URL.canParse(d)&&/^(https?:)$/.test(new URL(d).protocol)){o.source(Ce.UrlSource.make({type:"url",url:d}));continue}let u=d.startsWith("~/")?Jo.join(r.home,d.slice(2)):d;o.source(Ce.DirectorySource.make({type:"directory",path:_e.make(Jo.isAbsolute(u)?u:Jo.join(n.directory,u))}))}}))})};var Lt={};H(Lt,{Event:()=>lf,ID:()=>TS,PluginV2:()=>Lt,Service:()=>jn,locationLayer:()=>OS,node:()=>AS});var zn={};H(zn,{Event:()=>PS,ID:()=>af,Plugin:()=>zn});var af=f.String.pipe(f.brand("Plugin.ID")),sf=pn({type:"plugin.added",schema:{id:af}}),PS={Added:sf,Definitions:fn(sf)};var hr={};H(hr,{AISDK:()=>hr,InitError:()=>Dn,Service:()=>Nn,locationLayer:()=>cf,node:()=>CS});function RS(t,e,r){if(typeof e!="number"||e<=0||!t.body||!t.headers.get("content-type")?.includes("text/event-stream"))return t;let n=t.body.getReader(),o=new ReadableStream({async pull(s){let c=await new Promise((l,d)=>{let u=setTimeout(()=>{let p=new Error("SSE read timed out");r.abort(p),n.cancel(p).catch(()=>{}),d(p)},e);n.read().then(p=>{clearTimeout(u),l(p)},p=>{clearTimeout(u),d(p)})});if(c.done){s.close();return}s.enqueue(c.value)},async cancel(s){r.abort(s),await n.cancel(s)}});return new Response(o,{headers:new Headers(t.headers),status:t.status,statusText:t.statusText})}i(RS,"wrapSSE");function IS(t,e){let r={name:t.providerID,...t.api.type==="aisdk"?t.api.settings??{}:{},...t.request.body};t.api.type==="aisdk"&&t.api.url&&(r.baseURL=t.api.url);let n=r.fetch,o=r.chunkTimeout;return delete r.chunkTimeout,r.fetch=async(s,c)=>{let l={...c??{}},d=[l.signal,typeof o=="number"&&o>0?new AbortController:void 0,r.timeout!==void 0&&r.timeout!==null&&r.timeout!==!1?AbortSignal.timeout(r.timeout):void 0].filter(g=>!!g),u=d.find(g=>g instanceof AbortController),p=d.map(g=>g instanceof AbortController?g.signal:g);if(p.length===1&&(l.signal=p[0]),p.length>1&&(l.signal=AbortSignal.any(p)),(e==="@ai-sdk/openai"||e==="@ai-sdk/azure"||e==="@ai-sdk/amazon-bedrock/mantle")&&l.body&&l.method==="POST"){let g=JSON.parse(l.body);if(g.store!==!0&&Array.isArray(g.input)){for(let y of g.input)"id"in y&&delete y.id;l.body=JSON.stringify(g)}}let m=await(typeof n=="function"?n:fetch)(s,{...l,timeout:!1});return!u||typeof o!="number"?m:RS(m,o,u)},r}i(IS,"prepareOptions");var Dn=class extends f.TaggedErrorClass()("AISDK.InitError",{providerID:K.ID,cause:f.Defect()}){static{i(this,"InitError")}};function _c(t){return a.catchCause(e=>a.fail(new Dn({providerID:t,cause:xo.squash(e)})))}i(_c,"initError");var Nn=class extends te.Service()("@opencode/v2/AISDK"){static{i(this,"Service")}},cf=V.effect(Nn,a.gen(function*(){let t=[],e=[],r=new Map,n=new Map,o=i((l,d)=>a.fn("AISDK.hook")(function*(u){let p=yield*He.Scope,m=!0;d([...l(),u]);let g=a.sync(()=>{m&&(m=!1,d(l().filter(y=>y!==u)))});return yield*He.addFinalizer(p,g),{dispose:g}}),"register"),s=a.fnUntraced(function*(l,d){for(let u of l){let p=u(d);a.isEffect(p)&&(yield*p)}return d}),c=Nn.of({hook:{sdk:o(()=>t,l=>t=l),language:o(()=>e,l=>e=l)},runSDK:i(l=>s(t,l),"runSDK"),runLanguage:i(l=>s(e,l),"runLanguage"),language:a.fn("AISDK.language")(function*(l){let d=`${l.providerID}/${l.id}/${l.request.variant??"default"}`,u=r.get(d);if(u)return u;if(l.api.type!=="aisdk")return yield*new Dn({providerID:l.providerID,cause:new Error(`Unsupported api ${l.api.type}`)});let p=IS(l,l.api.package),m=JSON.stringify({providerID:l.providerID,api:l.api,options:p}),g=n.get(m)??(yield*c.runSDK({model:l,package:l.api.package,options:p}).pipe(_c(l.providerID))).sdk;if(!g)return yield*new Dn({providerID:l.providerID,cause:new Error("No AISDK provider plugin returned an SDK")});n.set(m,g);let y=yield*c.runLanguage({model:l,sdk:g,options:p}).pipe(_c(l.providerID)),h=yield*a.sync(()=>y.language??g.languageModel(l.api.id)).pipe(_c(l.providerID));return r.set(d,h),h})});return c})),CS=Qe({service:Nn,layer:cf,deps:[]});var Xo={};H(Xo,{PluginHost:()=>Xo,make:()=>$S});var qt=i(t=>t,"mutable"),$S=a.fn("PluginHost.make")(function*(t){let e=yield*de.Service,r=yield*hr.Service,n=yield*Jt.Service,o=yield*gt.Service,s=yield*X.Service,c=yield*Ze.Service,l=yield*Ce.Service;return{options:{},agent:{reload:e.reload,transform:i(d=>e.transform(u=>d({list:i(()=>qt(u.list()),"list"),get:i(p=>qt(u.get(de.ID.make(p))),"get"),default:i(p=>u.default(p===void 0?void 0:de.ID.make(p)),"default"),update:i((p,m)=>u.update(de.ID.make(p),m),"update"),remove:i(p=>u.remove(de.ID.make(p)),"remove")})),"transform")},aisdk:{sdk:i(d=>r.hook.sdk(u=>{let p={model:qt(u.model),package:u.package,options:u.options,sdk:u.sdk},m=d(p);return a.suspend(()=>a.isEffect(m)?m:a.void).pipe(a.tap(()=>a.sync(()=>u.sdk=p.sdk)))}),"sdk"),language:i(d=>r.hook.language(u=>{let p={model:qt(u.model),sdk:u.sdk,options:u.options,language:u.language},m=d(p);return a.suspend(()=>a.isEffect(m)?m:a.void).pipe(a.tap(()=>a.sync(()=>u.language=p.language)))}),"language")},catalog:{reload:n.reload,transform:i(d=>n.transform(u=>d({provider:{list:i(()=>qt(u.provider.list()),"list"),get:i(p=>qt(u.provider.get(K.ID.make(p))),"get"),update:i((p,m)=>u.provider.update(K.ID.make(p),m),"update"),remove:i(p=>u.provider.remove(K.ID.make(p)),"remove")},model:{get:i((p,m)=>qt(u.model.get(K.ID.make(p),ve.ID.make(m))),"get"),update:i((p,m,g)=>u.model.update(K.ID.make(p),ve.ID.make(m),g),"update"),remove:i((p,m)=>u.model.remove(K.ID.make(p),ve.ID.make(m)),"remove"),default:{get:u.model.default.get,set:i((p,m)=>u.model.default.set(K.ID.make(p),ve.ID.make(m)),"set")}}})),"transform")},command:{reload:o.reload,transform:o.transform},integration:{reload:s.reload,connection:{active:i(d=>s.connection.active(X.ID.make(d)),"active"),resolve:i(d=>s.connection.resolve(d.type==="credential"?{...d,id:Dt.ID.make(d.id)}:d),"resolve")},transform:i(d=>s.transform(u=>d({list:i(()=>qt(u.list()),"list"),get:i(p=>qt(u.get(X.ID.make(p))),"get"),update:i((p,m)=>u.update(X.ID.make(p),m),"update"),remove:i(p=>u.remove(X.ID.make(p)),"remove"),method:{list:i(p=>qt(u.method.list(X.ID.make(p))),"list"),update:i(p=>{if("authorize"in p){let m=X.MethodID.make(p.method.id),g=p.refresh;u.method.update({integrationID:X.ID.make(p.integrationID),method:{...p.method,id:m},authorize:i(y=>p.authorize(y).pipe(a.map(h=>h.mode==="auto"?{...h,callback:h.callback.pipe(a.map(_=>Dt.OAuth.make({..._,methodID:X.MethodID.make(_.methodID)})))}:{...h,callback:i(_=>h.callback(_).pipe(a.map(S=>Dt.OAuth.make({...S,methodID:X.MethodID.make(S.methodID)}))),"callback")})),"authorize"),...g?{refresh:i(y=>g(y).pipe(a.map(h=>Dt.OAuth.make({...h,methodID:X.MethodID.make(h.methodID)}))),"refresh")}:{},...p.label?{label:p.label}:{}});return}if(p.method.type==="env"){u.method.update({integrationID:X.ID.make(p.integrationID),method:{type:"env",names:p.method.names}});return}u.method.update({integrationID:X.ID.make(p.integrationID),method:{type:"key",label:p.method.label}})},"update"),remove:i((p,m)=>u.method.remove(X.ID.make(p),f.decodeUnknownSync(X.Method)(m)),"remove")}})),"transform")},plugin:{add:i(d=>t.add(Lt.ID.make(d.id),d.effect),"add"),remove:i(d=>t.remove(Lt.ID.make(d)),"remove")},reference:{reload:c.reload,transform:i(d=>c.transform(u=>d({add:i((p,m)=>u.add(p,f.decodeUnknownSync(Ze.Source)(m)),"add"),remove:u.remove,list:u.list})),"transform")},skill:{reload:l.reload,transform:i(d=>l.transform(u=>d({source:i(p=>u.source(f.decodeUnknownSync(Ce.Source)(p)),"source"),list:u.list})),"transform")}}});var TS=zn.ID,lf=zn.Event,jn=class extends te.Service()("@opencode/v2/Plugin"){static{i(this,"Service")}},df=V.effect(jn,a.gen(function*(){let t=yield*Ie.Service,e=Xu.makeUnsafe(),r=yield*He.make(),n=new Map,o=new Set,s=new Map,c=new Map,l,d=a.fn("Plugin.add")(function*(g,y){if(o.has(g))return yield*a.die(`Plugin load cycle detected for ${g}`);yield*e.withLock(g)(a.sync(()=>{o.add(g),c.delete(g)}).pipe(a.andThen(mt.batch(a.gen(function*(){let h=n.get(g);n.delete(g),h&&(yield*He.close(h,Wt.void).pipe(a.ignore));let _=yield*He.fork(r);yield*y(l).pipe(He.provide(_),a.withSpan("Plugin.load",{attributes:{"plugin.id":g}}),a.onExit(S=>Wt.isFailure(S)?He.close(_,S):a.void)),yield*t.publish(lf.Added,{id:g}),n.set(g,_),yield*a.forEach(s.get(g)??[],S=>pe.succeed(S,void 0),{discard:!0}),s.delete(g)}))),a.onExit(h=>Wt.isSuccess(h)?a.void:(c.set(g,h),a.forEach(s.get(g)??[],_=>pe.done(_,h),{discard:!0}).pipe(a.ensuring(a.sync(()=>s.delete(g)))))),a.ensuring(a.sync(()=>o.delete(g)))))}),u=a.fn("Plugin.remove")(function*(g){if(o.has(g))return yield*a.die(`Cannot remove plugin ${g} while it is loading`);yield*e.withLock(g)(mt.batch(a.gen(function*(){let y=n.get(g);n.delete(g),c.delete(g),y&&(yield*He.close(y,Wt.void).pipe(a.ignore))})))}),p=a.fn("Plugin.wait")(function*(g){let y=yield*pe.make(),h=yield*e.withLock(g)(a.sync(()=>{if(n.has(g))return!1;let _=c.get(g);if(_)return _;let S=s.get(g)??new Set;return S.add(y),s.set(g,S),!0}));if(h){if(typeof h!="boolean")return yield*h;yield*pe.await(y).pipe(a.ensuring(e.withLock(g)(a.sync(()=>{let _=s.get(g);_?.delete(y),_?.size===0&&s.delete(g)}))))}});yield*a.addFinalizer(g=>a.gen(function*(){n.clear(),yield*mt.batch(He.close(r,g))}));let m=jn.of({add:d,remove:u,wait:p});return l=yield*Xo.make(m),m})),OS=df.pipe(V.provideMerge(de.locationLayer),V.provideMerge(hr.locationLayer),V.provideMerge(Jt.locationLayer),V.provideMerge(gt.locationLayer),V.provideMerge(X.locationLayer),V.provideMerge(Ze.locationLayer)),AS=Qe({service:jn,layer:df,deps:[Ie.node,de.node,hr.node,Jt.node,gt.node,X.node,Ze.node,Ce.node]});var Qo={};H(Qo,{AgentPlugin:()=>Qo,Plugin:()=>LS});import qn from"path";var MS=qn.join(se.Path.data,"tool-output","*"),zS="You are an AI coding agent. Help the user accomplish software engineering tasks by inspecting the workspace, making targeted changes, and using tools according to the configured permissions.",DS=`You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
26
+
27
+ Your strengths:
28
+ - Rapidly finding files using glob patterns
29
+ - Searching code and text with powerful regex patterns
30
+ - Reading and analyzing file contents
31
+
32
+ Guidelines:
33
+ - Use Glob for broad file pattern matching
34
+ - Use Grep for searching file contents with regex
35
+ - Use Read when you know the specific file path you need to read
36
+ - Adapt your search approach based on the thoroughness level specified by the caller
37
+ - Return file paths as absolute paths in your final response
38
+ - For clear communication, avoid using emojis
39
+ - Do not create any files, or run bash commands that modify the user's system state in any way
40
+
41
+ Complete the user's search request efficiently and report your findings clearly.`,NS=`You are a context summarization agent. You are given a conversation between a user and an agent. Your goal is to produce a structured summary matching the format specified so another coding agent can continue the work.
42
+
43
+ Always follow the exact output structure requested by the user prompt. Keep every section, preserve exact file paths and identifiers when known, and prefer terse bullets over paragraphs.
44
+
45
+ Do not continue the conversation. Do not respond to any questions in the conversation. Only output the structured summary in the exact format requested by the user prompt. Respond in the same language as the conversation.`,jS=`You are a title generator. You output ONLY a thread title. Nothing else.
46
+
47
+ <task>
48
+ Generate a brief title that would help the user find this conversation later.
49
+
50
+ Follow all rules in <rules>
51
+ Use the <examples> so you know what a good title looks like.
52
+ Your output must be:
53
+ - A single line
54
+ - <=50 characters
55
+ - No explanations
56
+ </task>
57
+
58
+ <rules>
59
+ - you MUST use the same language as the user message you are summarizing
60
+ - Title must be grammatically correct and read naturally - no word salad
61
+ - Never include tool names in the title (e.g. "read tool", "bash tool", "edit tool")
62
+ - Focus on the main topic or question the user needs to retrieve
63
+ - Vary your phrasing - avoid repetitive patterns like always starting with "Analyzing"
64
+ - When a file is mentioned, focus on WHAT the user wants to do WITH the file, not just that they shared it
65
+ - Keep exact: technical terms, numbers, filenames, HTTP codes
66
+ - Remove: the, this, my, a, an
67
+ - Never assume tech stack
68
+ - Never use tools
69
+ - NEVER respond to questions, just generate a title for the conversation
70
+ - The title should NEVER include "summarizing" or "generating" when generating a title
71
+ - DO NOT SAY YOU CANNOT GENERATE A TITLE OR COMPLAIN ABOUT THE INPUT
72
+ - Always output something meaningful, even if the input is minimal.
73
+ - If the user message is short or conversational (e.g. "hello", "lol", "what's up", "hey"):
74
+ -> create a title that reflects the user's tone or intent (such as Greeting, Quick check-in, Light chat, Intro message, etc.)
75
+ </rules>
76
+
77
+ <examples>
78
+ "debug 500 errors in production" -> Debugging production 500 errors
79
+ "refactor user service" -> Refactoring user service
80
+ "why is app.js failing" -> app.js failure investigation
81
+ "implement rate limiting" -> Rate limiting implementation
82
+ "how do I connect postgres to my API" -> Postgres API connection
83
+ "best practices for React hooks" -> React hooks best practices
84
+ "@src/credential.ts can you add refresh token support" -> Credential refresh token support
85
+ "@utils/parser.ts this is broken" -> Parser bug fix
86
+ "look at @config.json" -> Config review
87
+ "@App.tsx add dark mode toggle" -> Dark mode toggle in App
88
+ </examples>`,qS=`Summarize what was done in this conversation. Write like a pull request description.
89
+
90
+ Rules:
91
+ - 2-3 sentences max
92
+ - Describe the changes made, not the process
93
+ - Do not mention running tests, builds, or other validation steps
94
+ - Do not explain what the user asked for
95
+ - Write in first person (I added..., I fixed...)
96
+ - Never ask questions or add new questions
97
+ - If the conversation ends with an unanswered question to the user, preserve that exact question
98
+ - If the conversation ends with an imperative statement or request to the user (e.g. "Now please run the command and paste the console output"), always include that exact request in the summary`,LS={id:"agent",effect:a.fn(function*(t){let r=(yield*Ne.Service).directory,n=[MS,qn.join(se.Path.tmp,"*")],o=[{action:"external_directory",resource:"*",effect:"ask"},...n.map(c=>({action:"external_directory",resource:c,effect:"allow"}))],s=[{action:"*",resource:"*",effect:"allow"},...o,{action:"question",resource:"*",effect:"deny"},{action:"plan_enter",resource:"*",effect:"deny"},{action:"plan_exit",resource:"*",effect:"deny"},{action:"read",resource:"*",effect:"allow"},{action:"read",resource:"*.env",effect:"ask"},{action:"read",resource:"*.env.*",effect:"ask"},{action:"read",resource:"*.env.example",effect:"allow"}];yield*t.agent.transform(c=>{c.update(de.defaultID,l=>{l.description="The default agent. Executes tools based on configured permissions.",l.system??=zS,l.mode="primary",l.permissions.push(...ct.merge(s,[{action:"question",resource:"*",effect:"allow"},{action:"plan_enter",resource:"*",effect:"allow"}]))}),c.update(de.ID.make("plan"),l=>{l.description="Plan mode. Disallows all edit tools.",l.mode="primary",l.permissions.push(...ct.merge(s,[{action:"question",resource:"*",effect:"allow"},{action:"plan_exit",resource:"*",effect:"allow"},{action:"external_directory",resource:qn.join(se.Path.data,"plans","*"),effect:"allow"},{action:"edit",resource:"*",effect:"deny"},{action:"edit",resource:qn.join(".opencode","plans","*.md"),effect:"allow"},{action:"edit",resource:qn.relative(r,qn.join(se.Path.data,"plans","*.md")),effect:"allow"}]))}),c.update(de.ID.make("general"),l=>{l.description="General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel.",l.mode="subagent",l.permissions.push(...ct.merge(s,[{action:"todowrite",resource:"*",effect:"deny"}]))}),c.update(de.ID.make("explore"),l=>{l.description='Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',l.system=DS,l.mode="subagent",l.permissions.push(...ct.merge(s,[{action:"*",resource:"*",effect:"deny"},{action:"grep",resource:"*",effect:"allow"},{action:"glob",resource:"*",effect:"allow"},{action:"webfetch",resource:"*",effect:"allow"},{action:"websearch",resource:"*",effect:"allow"},{action:"read",resource:"*",effect:"allow"}],o))}),c.update(de.ID.make("compaction"),l=>{l.mode="primary",l.hidden=!0,l.system=NS,l.permissions.push(...ct.merge(s,[{action:"*",resource:"*",effect:"deny"}]))}),c.update(de.ID.make("title"),l=>{l.mode="primary",l.hidden=!0,l.system=jS,l.permissions.push(...ct.merge(s,[{action:"*",resource:"*",effect:"deny"}]))}),c.update(de.ID.make("summary"),l=>{l.mode="primary",l.hidden=!0,l.system=qS,l.permissions.push(...ct.merge(s,[{action:"*",resource:"*",effect:"deny"}]))})})})};var ei={};H(ei,{CommandPlugin:()=>ei,Plugin:()=>US});var uf=`Create or update \`AGENTS.md\` for this repository.
99
+
100
+ The goal is a compact instruction file that helps future OpenCode sessions avoid mistakes and ramp up quickly. Every line should answer: "Would an agent likely miss this without help?" If not, leave it out.
101
+
102
+ User-provided focus or constraints (honor these):
103
+ $ARGUMENTS
104
+
105
+ ## How to investigate
106
+
107
+ Read the highest-value sources first:
108
+ - \`README*\`, root manifests, workspace config, lockfiles
109
+ - build, test, lint, formatter, typecheck, and codegen config
110
+ - CI workflows and pre-commit / task runner config
111
+ - existing instruction files (\`AGENTS.md\`, \`CLAUDE.md\`, \`.cursor/rules/\`, \`.cursorrules\`, \`.github/copilot-instructions.md\`)
112
+ - repo-local OpenCode config such as \`opencode.json\`
113
+
114
+ If architecture is still unclear after reading config and docs, inspect a small number of representative code files to find the real entrypoints, package boundaries, and execution flow. Prefer reading the files that explain how the system is wired together over random leaf files.
115
+
116
+ Prefer executable sources of truth over prose. If docs conflict with config or scripts, trust the executable source and only keep what you can verify.
117
+
118
+ ## What to extract
119
+
120
+ Look for the highest-signal facts for an agent working in this repo:
121
+ - exact developer commands, especially non-obvious ones
122
+ - how to run a single test, a single package, or a focused verification step
123
+ - required command order when it matters, such as \`lint -> typecheck -> test\`
124
+ - monorepo or multi-package boundaries, ownership of major directories, and the real app/library entrypoints
125
+ - framework or toolchain quirks: generated code, migrations, codegen, build artifacts, special env loading, dev servers, infra deploy flow
126
+ - testing quirks: fixtures, integration test prerequisites, snapshot workflows, required services, flaky or expensive suites
127
+ - important constraints from existing instruction files worth preserving
128
+
129
+ Good \`AGENTS.md\` content is usually hard-earned context that took reading multiple files to infer.
130
+
131
+ ## Questions
132
+
133
+ Only ask the user questions if the repo cannot answer something important. Use the \`question\` tool for one short batch at most.
134
+
135
+ Good questions:
136
+ - undocumented team conventions
137
+ - branch / PR / release expectations
138
+ - missing setup or test prerequisites that are known but not written down
139
+
140
+ Do not ask about anything the repo already makes clear.
141
+
142
+ ## Writing rules
143
+
144
+ Include only high-signal, repo-specific guidance such as:
145
+ - exact commands and shortcuts the agent would otherwise guess wrong
146
+ - architecture notes that are not obvious from filenames
147
+ - conventions that differ from language or framework defaults
148
+ - setup requirements, environment quirks, and operational gotchas
149
+ - references to existing instruction sources that matter
150
+
151
+ Exclude:
152
+ - generic software advice
153
+ - long tutorials or exhaustive file trees
154
+ - obvious language conventions
155
+ - speculative claims or anything you could not verify
156
+ - content better stored in another file referenced via \`opencode.json\` \`instructions\`
157
+
158
+ When in doubt, omit.
159
+
160
+ Prefer short sections and bullets. If the repo is simple, keep the file simple. If the repo is large, summarize the few structural facts that actually change how an agent should work.
161
+
162
+ If \`AGENTS.md\` already exists at \`\${path}\`, improve it in place rather than rewriting blindly. Preserve verified useful guidance, delete fluff or stale claims, and reconcile it with the current codebase.
163
+ `;var pf=`You are a code reviewer. Your job is to review code changes and provide actionable feedback.
164
+
165
+ ---
166
+
167
+ Input: $ARGUMENTS
168
+
169
+ ---
170
+
171
+ ## Determining What to Review
172
+
173
+ Based on the input provided, determine which type of review to perform:
174
+
175
+ 1. **No arguments (default)**: Review all uncommitted changes
176
+ - Run: \`git diff\` for unstaged changes
177
+ - Run: \`git diff --cached\` for staged changes
178
+ - Run: \`git status --short\` to identify untracked (net new) files
179
+
180
+ 2. **Commit hash** (40-char SHA or short hash): Review that specific commit
181
+ - Run: \`git show $ARGUMENTS\`
182
+
183
+ 3. **Branch name**: Compare current branch to the specified branch
184
+ - Run: \`git diff $ARGUMENTS...HEAD\`
185
+
186
+ 4. **PR URL or number** (contains "github.com" or "pull" or looks like a PR number): Review the pull request
187
+ - Run: \`gh pr view $ARGUMENTS\` to get PR context
188
+ - Run: \`gh pr diff $ARGUMENTS\` to get the diff
189
+
190
+ Use best judgement when processing input.
191
+
192
+ ---
193
+
194
+ ## Gathering Context
195
+
196
+ **Diffs alone are not enough.** After getting the diff, read the entire file(s) being modified to understand the full context. Code that looks wrong in isolation may be correct given surrounding logic\u2014and vice versa.
197
+
198
+ - Use the diff to identify which files changed
199
+ - Use \`git status --short\` to identify untracked files, then read their full contents
200
+ - Read the full file to understand existing patterns, control flow, and error handling
201
+ - Check for existing style guide or conventions files (CONVENTIONS.md, AGENTS.md, .editorconfig, etc.)
202
+
203
+ ---
204
+
205
+ ## What to Look For
206
+
207
+ **Bugs** - Your primary focus.
208
+ - Logic errors, off-by-one mistakes, incorrect conditionals
209
+ - If-else guards: missing guards, incorrect branching, unreachable code paths
210
+ - Edge cases: null/empty/undefined inputs, error conditions, race conditions
211
+ - Security issues: injection, auth bypass, data exposure
212
+ - Broken error handling that swallows failures, throws unexpectedly or returns error types that are not caught.
213
+
214
+ **Structure** - Does the code fit the codebase?
215
+ - Does it follow existing patterns and conventions?
216
+ - Are there established abstractions it should use but doesn't?
217
+ - Excessive nesting that could be flattened with early returns or extraction
218
+
219
+ **Performance** - Only flag if obviously problematic.
220
+ - O(n\xB2) on unbounded data, N+1 queries, blocking I/O on hot paths
221
+
222
+ **Behavior Changes** - If a behavioral change is introduced, raise it (especially if it's possibly unintentional).
223
+
224
+ ---
225
+
226
+ ## Before You Flag Something
227
+
228
+ **Be certain.** If you're going to call something a bug, you need to be confident it actually is one.
229
+
230
+ - Only review the changes - do not review pre-existing code that wasn't modified
231
+ - Don't flag something as a bug if you're unsure - investigate first
232
+ - Don't invent hypothetical problems - if an edge case matters, explain the realistic scenario where it breaks
233
+ - If you need more context to be sure, use the tools below to get it
234
+
235
+ **Don't be a zealot about style.** When checking code against conventions:
236
+
237
+ - Verify the code is *actually* in violation. Don't complain about else statements if early returns are already being used correctly.
238
+ - Some "violations" are acceptable when they're the simplest option. A \`let\` statement is fine if the alternative is convoluted.
239
+ - Excessive nesting is a legitimate concern regardless of other style choices.
240
+
241
+ ---
242
+
243
+ ## Tools
244
+
245
+ Use these to inform your review:
246
+
247
+ - **Explore agent** - Find how existing code handles similar problems. Check patterns, conventions, and prior art before claiming something doesn't fit.
248
+ - **Exa Code Context** - Verify correct usage of libraries/APIs before flagging something as wrong.
249
+ - **Web Search** - Research best practices if you're unsure about a pattern.
250
+
251
+ If you're uncertain about something and can't verify it with these tools, say "I'm not sure about X" rather than flagging it as a definite issue.
252
+
253
+ ---
254
+
255
+ ## Output
256
+
257
+ 1. If there is a bug, be direct and clear about why it is a bug.
258
+ 2. Clearly communicate severity of issues. Do not overstate severity.
259
+ 3. Critiques should clearly and explicitly communicate the scenarios, environments, or inputs that are necessary for the bug to arise. The comment should immediately indicate that the issue's severity depends on these factors.
260
+ 4. Your tone should be matter-of-fact and not accusatory or overly positive. It should read as a helpful AI assistant suggestion without sounding too much like a human reviewer.
261
+ 5. Write so the reader can quickly understand the issue without reading too closely.
262
+ 6. AVOID flattery, do not give any comments that are not helpful to the reader.
263
+ `;var US={id:"command",effect:a.fn(function*(t){let e=yield*Ne.Service;yield*t.command.transform(r=>{r.update("init",n=>{n.template=uf.replace("${path}",e.project.directory),n.description="guided AGENTS.md setup"}),r.update("review",n=>{n.template=pf.replace("${path}",e.project.directory),n.description="review changes [commit|branch|pr], defaults to uncommitted",n.subtask=!0})})})};function VS(t){let e=Date.parse(t);return Number.isFinite(e)?e:0}i(VS,"released");function vc(t){return[{input:t?.input??0,output:t?.output??0,cache:{read:t?.cache_read??0,write:t?.cache_write??0}},...t?.tiers?.map(r=>({tier:r.tier,input:r.input,output:r.output,cache:{read:r.cache_read??0,write:r.cache_write??0}}))??[],...t?.context_over_200k?[{tier:{type:"context",size:2e5},input:t.context_over_200k.input,output:t.context_over_200k.output,cache:{read:t.context_over_200k.cache_read??0,write:t.context_over_200k.cache_write??0}}]:[]]}i(vc,"cost");function FS(t,e){if(!e)return t;let r=vc(e),[n,...o]=t,[s,...c]=r,l=i(p=>`${p.tier?.type??"base"}:${p.tier?.size??0}`,"tierKey"),d=i((p,m)=>({...p,...m,tier:m.tier??p.tier,cache:{...p.cache,...m.cache}}),"merge"),u=new Map(o.map(p=>[l(p),p]));for(let p of c){let m=u.get(l(p));u.set(l(p),m?d(m,p):p)}return[d(n??{input:0,output:0,cache:{read:0,write:0}},s),...u.values()]}i(FS,"mergeCost");function HS(t,e){return`${t.name} ${e.charAt(0).toUpperCase()}${e.slice(1)}`}i(HS,"modeName");function ff(t,e,r={}){t.name=r.name??e.name,t.family=e.family,t.api=e.provider?.npm?{id:e.id,type:"aisdk",package:e.provider.npm,url:e.provider.api}:{id:e.id,type:"native",url:e.provider?.api,settings:{}},t.capabilities={tools:e.tool_call,input:[...e.modalities?.input??[]],output:[...e.modalities?.output??[]]},t.variants=[],t.time.released=VS(e.release_date),t.cost=r.cost??vc(e.cost),t.status=e.status??"active",t.enabled=!0,t.limit={context:e.limit.context,input:e.limit.input,output:e.limit.output},Object.assign(t.request.headers,r.request?.headers??{}),Object.assign(t.request.body,r.request?.body??{})}i(ff,"applyModel");var mf={id:"models-dev",effect:a.fn(function*(t){let e=yield*jt.Service,r=yield*Ie.Service;yield*t.integration.transform(a.fn(function*(n){let o=yield*e.get();for(let s of Object.values(o)){if(s.env.length===0)continue;let c=s.id;n.update(c,l=>l.name=s.name),n.method.update({integrationID:c,method:{type:"key"}}),n.method.update({integrationID:c,method:{type:"env",names:[...s.env]}})}})),yield*t.catalog.transform(a.fn(function*(n){let o=yield*e.get();for(let s of Object.values(o)){let c=K.ID.make(s.id);n.provider.update(c,l=>{l.name=s.name,l.api=s.npm?{type:"aisdk",package:s.npm,url:s.api}:{type:"native",url:s.api,settings:{}}});for(let l of Object.values(s.models)){let d=vc(l.cost);n.model.update(c,l.id,u=>ff(u,l,{cost:d}));for(let[u,p]of Object.entries(l.experimental?.modes??{}))n.model.update(c,`${l.id}-${u}`,m=>ff(m,l,{name:HS(l,u),cost:FS(d,p.cost),request:p.provider}))}}})),yield*r.subscribe(jt.Event.Refreshed).pipe(ur.runForEach(()=>t.integration.reload().pipe(a.andThen(t.catalog.reload()))),a.forkScoped({startImmediately:!0}))})};var hf={id:"alibaba",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/alibaba")return;let r=yield*a.promise(()=>import("./dist-QYH62TCJ.js"));e.sdk=r.createAlibaba(e.options)}))})};function ZS(t,e){if(t.startsWith("arn:")||["global.","us.","eu.","jp.","apac.","au."].some(l=>t.startsWith(l)))return t;let n=e??"us-east-1",o=n.split("-")[0];if(o==="us")return["nova-micro","nova-lite","nova-pro","nova-premier","nova-2","claude","deepseek.r1"].some(d=>t.includes(d))&&!n.startsWith("us-gov")?`${o}.${t}`:t;if(o==="eu"){let l=["eu-west-1","eu-west-2","eu-west-3","eu-north-1","eu-central-1","eu-south-1","eu-south-2"].some(u=>n.includes(u)),d=["claude","nova-lite","nova-micro","llama3","pixtral"].some(u=>t.includes(u));return l&&d?`${o}.${t}`:t}if(o!=="ap")return t;if(["ap-southeast-2","ap-southeast-4"].includes(n)&&["anthropic.claude-sonnet-4-5","anthropic.claude-haiku"].some(l=>t.includes(l)))return`au.${t}`;let c=n==="ap-northeast-1"?"jp":"apac";return["claude","nova-lite","nova-micro","nova-pro"].some(l=>t.includes(l))?`${c}.${t}`:t}i(ZS,"resolveModelID");function KS(t,e){return e==="openai.gpt-oss-safeguard-20b"||e==="openai.gpt-oss-safeguard-120b"?t.chat(e):t.responses(e)}i(KS,"selectMantleModel");var gf={id:"amazon-bedrock",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list())r.provider.api.type==="aisdk"&&r.provider.api.package==="@ai-sdk/amazon-bedrock"&&e.provider.update(r.provider.id,n=>{n.api.type==="aisdk"&&typeof n.request.body.endpoint=="string"&&(n.api.url=n.request.body.endpoint,delete n.request.body.endpoint)})})),yield*t.aisdk.sdk(a.fn(function*(e){if(!["@ai-sdk/amazon-bedrock","@ai-sdk/amazon-bedrock/mantle"].includes(e.package))return;let r={...e.options},n=typeof r.profile=="string"?r.profile:process.env.AWS_PROFILE,o=typeof r.region=="string"?r.region:process.env.AWS_REGION??"us-east-1",s=process.env.AWS_BEARER_TOKEN_BEDROCK??(typeof r.bearerToken=="string"?r.bearerToken:void 0);s&&!process.env.AWS_BEARER_TOKEN_BEDROCK&&(process.env.AWS_BEARER_TOKEN_BEDROCK=s);let c=!!(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI||process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI);if(r.region=o,typeof r.endpoint=="string"&&(r.baseURL=r.endpoint),!s&&r.credentialProvider===void 0){let{fromNodeProviderChain:d}=yield*a.promise(()=>import("./dist-es-G5UIJOU7.js"));r.credentialProvider=d(n?{profile:n}:{})}if(e.package==="@ai-sdk/amazon-bedrock/mantle"){let d=yield*a.promise(()=>import("./mantle-IJXDXT4M.js"));e.sdk=d.createBedrockMantle(r);return}let l=yield*a.promise(()=>import("./dist-KZ5R5QM5.js"));e.sdk=l.createAmazonBedrock(r)})),yield*t.aisdk.language(a.fn(function*(e){if(e.model.providerID!==K.ID.amazonBedrock)return;if(e.model.api.type==="aisdk"&&e.model.api.package==="@ai-sdk/amazon-bedrock/mantle"){e.language=KS(e.sdk,e.model.api.id);return}let r=typeof e.options.region=="string"?e.options.region:process.env.AWS_REGION;e.language=e.sdk.languageModel(ZS(e.model.api.id,r))}))})};var yf={id:"anthropic",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list())r.provider.api.type==="aisdk"&&r.provider.api.package==="@ai-sdk/anthropic"&&e.provider.update(r.provider.id,n=>{n.request.headers["anthropic-beta"]="interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"})})),yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/anthropic")return;let r=yield*a.promise(()=>import("./dist-CL46WFZG.js"));e.sdk=r.createAnthropic(e.options)}))})};function _f(t,e,r){return r&&t.chat?t.chat(e):t.responses?t.responses(e):t.messages?t.messages(e):t.chat?t.chat(e):t.languageModel(e)}i(_f,"selectLanguage");var vf={id:"azure",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list()){if(r.provider.api.type!=="aisdk"||r.provider.api.package!=="@ai-sdk/azure")continue;let n=r.provider.request.body.resourceName,o=typeof n=="string"&&n.trim()!==""?n:process.env.AZURE_RESOURCE_NAME;o&&e.provider.update(r.provider.id,s=>{s.request.body.resourceName=o})}})),yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/azure")return;if(e.model.providerID===K.ID.azure&&!e.options.resourceName&&!e.options.baseURL&&(e.model.api.type!=="aisdk"||!e.model.api.url))throw new Error("AZURE_RESOURCE_NAME is missing, set it using env var or reconnecting the azure provider and setting it");let r=yield*a.promise(()=>import("./dist-7CT3XCNN.js"));e.sdk=r.createAzure(e.options)})),yield*t.aisdk.language(a.fn(function*(e){e.model.providerID===K.ID.azure&&(e.language=_f(e.sdk,e.model.api.id,!!e.options.useCompletionUrls))}))})},Sf={id:"azure-cognitive-services",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){let r=process.env.AZURE_COGNITIVE_SERVICES_RESOURCE_NAME;if(r)for(let n of e.provider.list())n.provider.api.type==="aisdk"&&n.provider.api.package==="@ai-sdk/openai-compatible"&&n.provider.id.includes("azure-cognitive-services")&&e.provider.update(n.provider.id,o=>{o.request.body.baseURL=`https://${r}.cognitiveservices.azure.com/openai`})})),yield*t.aisdk.language(a.fn(function*(e){e.model.providerID===K.ID.make("azure-cognitive-services")&&(e.language=_f(e.sdk,e.model.api.id,!!e.options.useCompletionUrls))}))})};var wf={id:"cerebras",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list())r.provider.api.type==="aisdk"&&r.provider.api.package==="@ai-sdk/cerebras"&&e.provider.update(r.provider.id,n=>{n.request.headers["X-Cerebras-3rd-Party-Integration"]="opencode"})})),yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/cerebras")return;let r=yield*a.promise(()=>import("./dist-O4DF72J2.js"));e.sdk=r.createCerebras(e.options)}))})};import Sc from"os";var bf={id:"cloudflare-ai-gateway",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="ai-gateway-provider"||e.options.baseURL)return;let r=WS(e.options);if(!r)return;let n=BS(e.options),{createAiGateway:o}=yield*a.promise(()=>import("./dist-5NQOHNPL.js")).pipe(a.orDie),{createUnified:s}=yield*a.promise(()=>import("./unified-W3ZKZ4HG.js")).pipe(a.orDie),c=o({accountId:r.accountId,gateway:r.gatewayId,apiKey:r.apiKey,options:JS(e.options,n)});e.sdk={languageModel(l){let d=l.startsWith("workers-ai/")||l.startsWith("@cf/"),u=s(d?{apiKey:r.apiKey}:{});return c(u(l))}}}))})},GS=f.decodeUnknownOption(f.UnknownFromJsonString);function WS(t){let e=process.env.CLOUDFLARE_ACCOUNT_ID??Cs(t,"accountId"),r=process.env.CLOUDFLARE_GATEWAY_ID??Cs(t,"gatewayId")??Cs(t,"gateway"),n=process.env.CLOUDFLARE_API_TOKEN??process.env.CF_AIG_TOKEN??Cs(t,"apiKey");if(!(!e||!r||!n))return{accountId:e,gatewayId:r,apiKey:n}}i(WS,"gatewayConfig");function BS(t){if(t.metadata!==void 0)return t.metadata;let e=t.headers?.["cf-aig-metadata"];return e?pt.getOrUndefined(GS(e)):void 0}i(BS,"gatewayMetadata");function JS(t,e){return{metadata:e,cacheTtl:t.cacheTtl,cacheKey:t.cacheKey,skipCache:t.skipCache,collectLog:t.collectLog,headers:{"User-Agent":`opencode/${ht} cloudflare-ai-gateway (${Sc.platform()} ${Sc.release()}; ${Sc.arch()})`}}}i(JS,"gatewayOptions");function Cs(t,e){return typeof t[e]=="string"?t[e]:void 0}i(Cs,"stringOption");import wc from"os";var $s=K.ID.make("cloudflare-workers-ai"),xf={id:"cloudflare-workers-ai",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){let r=e.provider.get($s);r&&e.provider.update(r.provider.id,n=>{if(n.api.type!=="aisdk"||n.api.url)return;let o=kf(n.request.body);o&&(n.api.url=Ef(o))})})),yield*t.aisdk.sdk(a.fn(function*(e){if(e.model.providerID!==$s||e.package!=="@ai-sdk/openai-compatible")return;let r=kf(e.options);if(!YS(e.model.api)&&!r)return;let n=yield*a.promise(()=>import("./dist-QJPOJCLB.js"));e.sdk=n.createOpenAICompatible(XS({...e.options,baseURL:e.options.baseURL??(r?Ef(r):void 0)}))})),yield*t.aisdk.language(a.fn(function*(e){e.model.providerID===$s&&(e.language=e.sdk.languageModel(e.model.api.id))}))})};function kf(t){return process.env.CLOUDFLARE_ACCOUNT_ID??ew(t,"accountId")}i(kf,"resolveAccountId");function Ef(t){return`https://api.cloudflare.com/client/v4/accounts/${t}/ai/v1`}i(Ef,"workersEndpoint");function YS(t){return t.type==="aisdk"&&!!t.url}i(YS,"hasWorkersEndpoint");function XS(t){return{...t,baseURL:QS(t.baseURL),apiKey:process.env.CLOUDFLARE_API_KEY??t.apiKey,headers:{"User-Agent":`opencode/${ht} cloudflare-workers-ai (${wc.platform()} ${wc.release()}; ${wc.arch()})`,...t.headers},name:$s}}i(XS,"sdkOptions");function QS(t){return typeof t!="string"?t:t.replaceAll("${CLOUDFLARE_ACCOUNT_ID}",process.env.CLOUDFLARE_ACCOUNT_ID??"${CLOUDFLARE_ACCOUNT_ID}")}i(QS,"expandAccountId");function ew(t,e){return typeof t[e]=="string"?t[e]:void 0}i(ew,"stringOption");var Pf={id:"cohere",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/cohere")return;let r=yield*a.promise(()=>import("./dist-PH4MEGVR.js"));e.sdk=r.createCohere(e.options)}))})};var Rf={id:"deepinfra",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/deepinfra")return;let r=yield*a.promise(()=>import("./dist-XPFB35TX.js"));e.sdk=r.createDeepInfra(e.options)}))})};import{pathToFileURL as tw}from"url";var If={id:"dynamic-provider",effect:a.fn(function*(t){let e=yield*Nt.Service;yield*t.aisdk.sdk(a.fn(function*(r){if(r.sdk)return;let n=r.package.startsWith("file://")?r.package:(yield*e.add(r.package).pipe(a.orDie)).entrypoint;if(!n)throw new Error(`Package ${r.package} has no import entrypoint`);let o=yield*a.promise(async()=>await(n.startsWith("file://")?import(n):import(tw(n).href))).pipe(a.orDie),s=Object.keys(o).find(c=>c.startsWith("create"));if(!s)throw new Error(`Package ${r.package} has no provider factory export`);r.sdk=o[s](r.options)}))})};var Cf={id:"gateway",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/gateway")return;let r=yield*a.promise(()=>import("./dist-KM5HCPZX.js"));e.sdk=r.createGateway(e.options)}))})};var $f={id:"github-copilot",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){let r=e.provider.get(K.ID.githubCopilot);!r||!r.models.has(ve.ID.make("gpt-5-chat-latest"))||e.model.update(r.provider.id,ve.ID.make("gpt-5-chat-latest"),n=>{n.enabled=!1})})),yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/github-copilot")return;let r=yield*a.promise(()=>import("./copilot-provider-QVMLQZZC.js"));e.sdk=r.createOpenaiCompatible(e.options)})),yield*t.aisdk.language(a.fn(function*(e){if(e.model.providerID!==K.ID.githubCopilot)return;if(e.sdk.responses===void 0&&e.sdk.chat===void 0){e.language=e.sdk.languageModel(e.model.api.id);return}if(e.options.endpoint==="responses"&&e.sdk.responses){e.language=e.sdk.responses(e.model.api.id);return}if(e.options.endpoint==="chat"&&e.sdk.chat){e.language=e.sdk.chat(e.model.api.id);return}let r=/^gpt-(\d+)/.exec(e.model.api.id);e.language=r&&Number(r[1])>=5&&!e.model.api.id.startsWith("gpt-5-mini")&&e.sdk.responses?e.sdk.responses(e.model.api.id):e.sdk.chat(e.model.api.id)}))})};import bc from"os";var Tf={id:"gitlab",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="gitlab-ai-provider")return;let r=yield*a.promise(()=>import("./dist-KTNLTEHB.js"));e.sdk=r.createGitLab({...e.options,instanceUrl:typeof e.options.instanceUrl=="string"?e.options.instanceUrl:process.env.GITLAB_INSTANCE_URL??"https://gitlab.com",apiKey:typeof e.options.apiKey=="string"?e.options.apiKey:process.env.GITLAB_TOKEN,aiGatewayHeaders:{"User-Agent":`opencode/${ht} gitlab-ai-provider/${r.VERSION} (${bc.platform()} ${bc.release()}; ${bc.arch()})`,"anthropic-beta":"context-1m-2025-08-07",...e.options.aiGatewayHeaders},featureFlags:{duo_agent_platform_agentic_chat:!0,duo_agent_platform:!0,...e.options.featureFlags}})})),yield*t.aisdk.language(a.fn(function*(e){if(e.model.providerID!==K.ID.gitlab)return;let r=typeof e.options.featureFlags=="object"&&e.options.featureFlags?e.options.featureFlags:{};if(e.model.api.id.startsWith("duo-workflow-")){let n=yield*a.promise(()=>import("./dist-KTNLTEHB.js")).pipe(a.orDie),o=typeof e.model.request.body.workflowRef=="string"?e.model.request.body.workflowRef:void 0,s=typeof e.model.request.body.workflowDefinition=="string"?e.model.request.body.workflowDefinition:void 0,c=e.sdk.workflowChat(n.isWorkflowModel(e.model.api.id)?e.model.api.id:"duo-workflow",{featureFlags:r,workflowDefinition:s});o&&(c.selectedModelRef=o),e.language=c;return}e.language=e.sdk.agenticChat(e.model.api.id,{aiGatewayHeaders:e.options.aiGatewayHeaders,featureFlags:r})}))})};var Of={id:"google",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/google")return;let r=yield*a.promise(()=>import("./dist-HXJTF22W.js"));e.sdk=r.createGoogleGenerativeAI(e.options)}))})};function Af(t){return t.project??process.env.GOOGLE_VERTEX_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??process.env.GCLOUD_PROJECT}i(Af,"resolveProject");function Mf(t){return t.location??process.env.GOOGLE_VERTEX_LOCATION??process.env.GOOGLE_CLOUD_LOCATION??process.env.VERTEX_LOCATION??"us-central1"}i(Mf,"resolveLocation");function rw(t){return t==="global"?"aiplatform.googleapis.com":`${t}-aiplatform.googleapis.com`}i(rw,"vertexEndpoint");function nw(t,e,r){return t.replaceAll("${GOOGLE_VERTEX_PROJECT}",e??"${GOOGLE_VERTEX_PROJECT}").replaceAll("${GOOGLE_VERTEX_LOCATION}",r).replaceAll("${GOOGLE_VERTEX_ENDPOINT}",rw(r))}i(nw,"replaceVertexVars");function zf(t){return async(e,r)=>{let{GoogleAuth:n}=await import("./src-3NCXEROI.js"),c=await(await new n({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken(),l=new Headers(r?.headers);return l.set("Authorization",`Bearer ${c.token}`),typeof t=="function"?t(e,{...r,headers:l}):fetch(e,{...r,headers:l})}}i(zf,"authFetch");var Df={id:"google-vertex",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list()){if(r.provider.api.type!=="aisdk"||r.provider.api.package!=="@ai-sdk/google-vertex"&&!(r.provider.id===K.ID.googleVertex&&r.provider.api.package.includes("@ai-sdk/openai-compatible")))continue;let n=Af(r.provider.request.body),o=String(Mf(r.provider.request.body));e.provider.update(r.provider.id,s=>{n&&(s.request.body.project=n),s.request.body.location=o,s.api.type==="aisdk"&&s.api.url&&(s.api.url=nw(s.api.url,n,o)),s.api.type==="aisdk"&&s.api.package.includes("@ai-sdk/openai-compatible")&&(s.request.body.fetch=zf(s.request.body.fetch))})}})),yield*t.aisdk.sdk(a.fn(function*(e){if(e.model.providerID===K.ID.googleVertex&&e.package.includes("@ai-sdk/openai-compatible")){e.options.fetch=zf(e.options.fetch);return}if(e.package!=="@ai-sdk/google-vertex")return;let r=yield*a.promise(()=>import("./dist-YUH4RKR5.js")),n=Af(e.options),o=Mf(e.options),s={...e.options};delete s.fetch,e.sdk=r.createVertex({...s,project:n,location:o})})),yield*t.aisdk.language(a.fn(function*(e){e.model.providerID===K.ID.googleVertex&&(e.language=e.sdk.languageModel(String(e.model.api.id).trim()))}))})},Nf={id:"google-vertex-anthropic",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list()){if(r.provider.api.type!=="aisdk"||r.provider.api.package!=="@ai-sdk/google-vertex/anthropic")continue;let n=r.provider.request.body.project??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??process.env.GCLOUD_PROJECT,o=r.provider.request.body.location??process.env.GOOGLE_CLOUD_LOCATION??process.env.VERTEX_LOCATION??"global";e.provider.update(r.provider.id,s=>{n&&(s.request.body.project=n),s.request.body.location=o})}})),yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/google-vertex/anthropic")return;let r=yield*a.promise(()=>import("./anthropic-FVULF7C3.js")),n=typeof e.options.project=="string"?e.options.project:process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??process.env.GCLOUD_PROJECT,o=typeof e.options.location=="string"?e.options.location:process.env.GOOGLE_CLOUD_LOCATION??process.env.VERTEX_LOCATION??"global";e.sdk=r.createVertexAnthropic({...e.options,project:n,location:o,...(o==="eu"||o==="us")&&n&&!e.options.baseURL?{baseURL:`https://aiplatform.${o}.rep.googleapis.com/v1/projects/${n}/locations/${o}/publishers/anthropic/models`}:{}})})),yield*t.aisdk.language(a.fn(function*(e){e.model.providerID===K.ID.make("google-vertex-anthropic")&&(e.language=e.sdk.languageModel(String(e.model.api.id).trim()))}))})};var jf={id:"groq",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/groq")return;let r=yield*a.promise(()=>import("./dist-T776XKTM.js"));e.sdk=r.createGroq(e.options)}))})};var qf={id:"kilo",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list())r.provider.api.type==="aisdk"&&r.provider.api.package==="@ai-sdk/openai-compatible"&&r.provider.api.url==="https://api.kilo.ai/api/gateway"&&e.provider.update(r.provider.id,n=>{n.request.headers["HTTP-Referer"]="https://opencode.ai/",n.request.headers["X-Title"]="opencode"})}))})};var Lf={id:"llmgateway",effect:a.fn(function*(t){let e=yield*X.Service;yield*t.catalog.transform(a.fn(function*(r){for(let n of r.provider.list())n.provider.disabled||n.provider.api.type==="aisdk"&&n.provider.api.package==="@ai-sdk/openai-compatible"&&n.provider.api.url==="https://api.llmgateway.io/v1"&&(yield*e.get(X.ID.make(n.provider.id)))&&r.provider.update(n.provider.id,o=>{o.request.headers["HTTP-Referer"]="https://opencode.ai/",o.request.headers["X-Title"]="opencode",o.request.headers["X-Source"]="opencode"})}))})};var Uf={id:"mistral",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/mistral")return;let r=yield*a.promise(()=>import("./dist-TCE5MKZQ.js"));e.sdk=r.createMistral(e.options)}))})};var Vf={id:"nvidia",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list())r.provider.api.type==="aisdk"&&r.provider.api.package==="@ai-sdk/openai-compatible"&&r.provider.api.url==="https://integrate.api.nvidia.com/v1"&&e.provider.update(r.provider.id,n=>{n.request.headers["HTTP-Referer"]="https://opencode.ai/",n.request.headers["X-Title"]="opencode",n.request.headers["X-BILLING-INVOKE-ORIGIN"]??="OpenCode"})}))})};import{createServer as mw}from"node:http";var lt={};H(lt,{OauthCallbackPage:()=>lt,bootstrap:()=>sw,error:()=>iw,success:()=>ow});function ow(t){let e=t?.provider;return Ec({title:"Authorization successful",body:kc({status:"success",headline:"Authorization successful",message:e?`OpenCode is now connected to ${Nr(e)}.`:"OpenCode is now authorized.",footnote:"You can close this window."}),script:t?.autoClose===!1?void 0:aw})}i(ow,"success");function iw(t,e){let r=e?.provider;return Ec({title:"Authorization failed",body:kc({status:"error",headline:"Authorization failed",message:r?`OpenCode couldn't finish connecting to ${Nr(r)}.`:"OpenCode couldn't complete authorization.",detail:t,footnote:"Close this window and try again from OpenCode."})})}i(iw,"error");function sw(t){return Ec({title:"Finishing sign-in",body:kc({status:"pending",headline:"Finishing sign-in",message:t.provider?`Completing your ${Nr(t.provider)} authorization.`:"Completing authorization.",footnote:"You can close this window once sign-in finishes."}),script:cw(t)})}i(sw,"bootstrap");function kc(t){let e=t.detail?.trim();return`<main class="card" id="oc-card" data-status="${t.status}" role="status" aria-live="polite">
264
+ <div class="brand">${dw}</div>
265
+ <div class="status" aria-hidden="true">
266
+ <span class="icon icon-pending">${fw}</span>
267
+ <span class="icon icon-success">${uw}</span>
268
+ <span class="icon icon-error">${pw}</span>
269
+ </div>
270
+ <h1 class="headline" id="oc-headline">${Nr(t.headline)}</h1>
271
+ <p class="message" id="oc-message">${t.message}</p>
272
+ <pre class="detail" id="oc-detail"${e?"":" hidden"}>${e?Nr(e):""}</pre>
273
+ <p class="footnote" id="oc-footnote">${Nr(t.footnote)}</p>
274
+ </main>`}i(kc,"renderCard");function Ec(t){return`<!doctype html>
275
+ <html lang="en">
276
+ <head>
277
+ <meta charset="utf-8" />
278
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
279
+ <meta name="robots" content="noindex" />
280
+ <title>${Nr(t.title)} \xB7 OpenCode</title>
281
+ <style>${lw}</style>
282
+ </head>
283
+ <body>
284
+ ${t.body}${t.script?`
285
+ <script>${t.script}</script>`:""}
286
+ </body>
287
+ </html>`}i(Ec,"renderDocument");var aw="setTimeout(function(){try{window.close()}catch(e){}},2500)";function cw(t){return`var PROVIDER=${Ff(t.provider??"")};
288
+ var TOKEN_URL=new URL(${Ff(t.tokenPath)},window.location.origin).href;
289
+ (function(){
290
+ var card=document.getElementById("oc-card"),headline=document.getElementById("oc-headline"),message=document.getElementById("oc-message"),detail=document.getElementById("oc-detail"),footnote=document.getElementById("oc-footnote");
291
+ function fail(text){card.dataset.status="error";headline.textContent="Authorization failed";message.textContent=PROVIDER?("OpenCode couldn't finish connecting to "+PROVIDER+"."):"OpenCode couldn't complete authorization.";if(text){detail.textContent=text;detail.hidden=false}footnote.textContent="Close this window and try again from OpenCode."}
292
+ function ok(){card.dataset.status="success";headline.textContent="Authorization successful";message.textContent=PROVIDER?("OpenCode is now connected to "+PROVIDER+"."):"OpenCode is now authorized.";detail.hidden=true;footnote.textContent="You can close this window.";setTimeout(function(){try{window.close()}catch(e){}},2500)}
293
+ try{
294
+ var hash=new URLSearchParams((window.location.hash||"").slice(1));
295
+ var search=new URLSearchParams(window.location.search||"");
296
+ var err=hash.get("error")||search.get("error");
297
+ var errDescription=hash.get("error_description")||search.get("error_description");
298
+ var body=err?{error:err,error_description:errDescription||""}:{access_token:hash.get("access_token")||"",expires_in:hash.get("expires_in")||"0",state:hash.get("state")||""};
299
+ fetch(TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}).then(function(res){
300
+ if(!res.ok)return res.text().catch(function(){return""}).then(function(t){throw new Error(t||("callback failed ("+res.status+")"))});
301
+ if(err){fail(errDescription||err);return}
302
+ ok();
303
+ }).catch(function(e){fail(String(e&&e.message?e.message:e))});
304
+ }catch(e){fail(String(e&&e.message?e.message:e))}
305
+ })()`}i(cw,"bootstrapScript");function Ff(t){return JSON.stringify(t).replaceAll("<","\\u003c")}i(Ff,"scriptString");function Nr(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}i(Nr,"escapeHtml");var Hf=`
306
+ --oc-bg: #f8f8f8;
307
+ --oc-card: #fcfcfc;
308
+ --oc-text-strong: #171717;
309
+ --oc-text-base: #6f6f6f;
310
+ --oc-text-weak: #8f8f8f;
311
+ --oc-border-weak: #e5e5e5;
312
+ --oc-icon-strong: #171717;
313
+ --oc-icon-base: #8f8f8f;
314
+ --oc-icon-weak: #dbdbdb;
315
+ --oc-success: #2dba26;
316
+ --oc-error: #ed4831;
317
+ --oc-detail-bg: #fff8f6;
318
+ --oc-detail-border: #fdc3b7;
319
+ --oc-shadow: 0 16px 48px -6px rgba(0,0,0,.10), 0 6px 12px -2px rgba(0,0,0,.05), 0 1px 2px rgba(0,0,0,.06);`,Zf=`
320
+ --oc-bg: #101010;
321
+ --oc-card: #161616;
322
+ --oc-text-strong: rgba(255,255,255,.936);
323
+ --oc-text-base: rgba(255,255,255,.618);
324
+ --oc-text-weak: rgba(255,255,255,.422);
325
+ --oc-border-weak: #282828;
326
+ --oc-icon-strong: #ededed;
327
+ --oc-icon-base: #7e7e7e;
328
+ --oc-icon-weak: #343434;
329
+ --oc-success: #12c905;
330
+ --oc-error: #fc533a;
331
+ --oc-detail-bg: #28110c;
332
+ --oc-detail-border: #6a1206;
333
+ --oc-shadow: 0 16px 48px -6px rgba(0,0,0,.55), 0 6px 12px -2px rgba(0,0,0,.35), 0 1px 2px rgba(0,0,0,.4);`,lw=`
334
+ :root { color-scheme: light dark;${Hf}
335
+ --oc-font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
336
+ --oc-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
337
+ }
338
+ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) {${Zf} } }
339
+ :root[data-theme="dark"] {${Zf} }
340
+ :root[data-theme="light"] {${Hf} }
341
+
342
+ * { box-sizing: border-box; }
343
+ html, body { margin: 0; height: 100%; }
344
+ body {
345
+ min-height: 100vh;
346
+ display: grid;
347
+ place-items: center;
348
+ padding: 24px;
349
+ background: var(--oc-bg);
350
+ color: var(--oc-text-base);
351
+ font-family: var(--oc-font-sans);
352
+ line-height: 1.5;
353
+ -webkit-font-smoothing: antialiased;
354
+ text-rendering: optimizeLegibility;
355
+ }
356
+ .card {
357
+ width: min(100%, 28rem);
358
+ padding: 2.25rem 2rem 1.75rem;
359
+ background: var(--oc-card);
360
+ border: 1px solid var(--oc-border-weak);
361
+ border-radius: 14px;
362
+ box-shadow: var(--oc-shadow);
363
+ text-align: center;
364
+ }
365
+ .brand { display: flex; justify-content: center; margin-bottom: 1.75rem; }
366
+ .brand svg { height: 19px; width: auto; }
367
+ .status { display: flex; justify-content: center; margin-bottom: 1.125rem; }
368
+ .icon { display: none; line-height: 0; }
369
+ .icon svg { display: block; }
370
+ .card[data-status="pending"] .icon-pending,
371
+ .card[data-status="success"] .icon-success,
372
+ .card[data-status="error"] .icon-error { display: block; }
373
+ .icon-success { color: var(--oc-success); }
374
+ .icon-error { color: var(--oc-error); }
375
+ .icon-pending { color: var(--oc-text-weak); }
376
+ .headline { margin: 0; font-size: 1.1875rem; font-weight: 500; line-height: 1.3; letter-spacing: -0.012em; color: var(--oc-text-strong); }
377
+ .message { margin: 0.5rem 0 0; font-size: 0.9375rem; color: var(--oc-text-base); }
378
+ .detail {
379
+ margin: 1.25rem 0 0;
380
+ padding: 0.75rem 0.875rem;
381
+ text-align: left;
382
+ font-family: var(--oc-font-mono);
383
+ font-size: 0.8125rem;
384
+ line-height: 1.55;
385
+ color: var(--oc-text-strong);
386
+ background: var(--oc-detail-bg);
387
+ border: 1px solid var(--oc-detail-border);
388
+ border-radius: 8px;
389
+ white-space: pre-wrap;
390
+ word-break: break-word;
391
+ max-height: 9.5rem;
392
+ overflow: auto;
393
+ }
394
+ .detail[hidden] { display: none; }
395
+ .footnote { margin: 1.5rem 0 0; font-size: 0.8125rem; color: var(--oc-text-weak); }
396
+ .spinner { animation: oc-spin 0.8s linear infinite; transform-origin: center; }
397
+ @keyframes oc-spin { to { transform: rotate(360deg); } }
398
+ @media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }
399
+ `,dw=`<svg class="wordmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 234 42" fill="none" aria-label="OpenCode" role="img">
400
+ <path d="M18 30H6V18H18V30Z" fill="var(--oc-icon-weak)" />
401
+ <path d="M18 12H6V30H18V12ZM24 36H0V6H24V36Z" fill="var(--oc-icon-base)" />
402
+ <path d="M48 30H36V18H48V30Z" fill="var(--oc-icon-weak)" />
403
+ <path d="M36 30H48V12H36V30ZM54 36H36V42H30V6H54V36Z" fill="var(--oc-icon-base)" />
404
+ <path d="M84 24V30H66V24H84Z" fill="var(--oc-icon-weak)" />
405
+ <path d="M84 24H66V30H84V36H60V6H84V24ZM66 18H78V12H66V18Z" fill="var(--oc-icon-base)" />
406
+ <path d="M108 36H96V18H108V36Z" fill="var(--oc-icon-weak)" />
407
+ <path d="M108 12H96V36H90V6H108V12ZM114 36H108V12H114V36Z" fill="var(--oc-icon-base)" />
408
+ <path d="M144 30H126V18H144V30Z" fill="var(--oc-icon-weak)" />
409
+ <path d="M144 12H126V30H144V36H120V6H144V12Z" fill="var(--oc-icon-strong)" />
410
+ <path d="M168 30H156V18H168V30Z" fill="var(--oc-icon-weak)" />
411
+ <path d="M168 12H156V30H168V12ZM174 36H150V6H174V36Z" fill="var(--oc-icon-strong)" />
412
+ <path d="M198 30H186V18H198V30Z" fill="var(--oc-icon-weak)" />
413
+ <path d="M198 12H186V30H198V12ZM204 36H180V6H198V0H204V36Z" fill="var(--oc-icon-strong)" />
414
+ <path d="M234 24V30H216V24H234Z" fill="var(--oc-icon-weak)" />
415
+ <path d="M216 12V18H228V12H216ZM234 24H216V30H234V36H210V6H234V24Z" fill="var(--oc-icon-strong)" />
416
+ </svg>`,uw='<svg viewBox="0 0 24 24" width="30" height="30" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9" /><path d="m8.5 12.5 2.4 2.4 4.6-5.4" /></svg>',pw='<svg viewBox="0 0 24 24" width="30" height="30" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9" /><path d="m9 9 6 6m0-6-6 6" /></svg>',fw='<svg class="spinner" viewBox="0 0 24 24" width="30" height="30" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="9" opacity="0.2" /><path d="M21 12a9 9 0 0 0-9-9" /></svg>';var Os="app_EMoamEEZ73f0CkXaXp7hrann",jr="https://auth.openai.com",xc=1455,hw=3e3,Pc=X.MethodID.make("chatgpt-browser"),Rc=X.MethodID.make("chatgpt-headless"),gw={integrationID:X.ID.make("openai"),method:{id:Pc,type:"oauth",label:"ChatGPT Pro/Plus (browser)"},authorize:i(()=>a.gen(function*(){let t=yield*a.promise(_w),e=Jf(crypto.getRandomValues(new Uint8Array(32)).buffer),r=yield*pe.make(),n=`http://localhost:${xc}/auth/callback`,o=mw((s,c)=>{let l=new URL(s.url??"/",`http://localhost:${xc}`);if(l.pathname!=="/auth/callback"){c.writeHead(404).end("Not found");return}let d=l.searchParams.get("error_description")??l.searchParams.get("error"),u=l.searchParams.get("code");if(d){a.runFork(pe.fail(r,new Error(d))),c.writeHead(400,{"Content-Type":"text/html"}).end(lt.error(d,{provider:"ChatGPT"}));return}if(!u||l.searchParams.get("state")!==e){let p=u?"Invalid OAuth state":"Missing authorization code";a.runFork(pe.fail(r,new Error(p))),c.writeHead(400,{"Content-Type":"text/html"}).end(lt.error(p,{provider:"ChatGPT"}));return}a.runFork(pe.succeed(r,u)),c.writeHead(200,{"Content-Type":"text/html"}).end(lt.success({provider:"ChatGPT"}))});return yield*a.callback(s=>{o.once("error",c=>s(a.fail(c))),o.listen(xc,"localhost",()=>s(a.void))}),yield*a.addFinalizer(()=>a.sync(()=>o.close())),{mode:"auto",url:vw(n,t,e),instructions:"Complete authorization in your browser. This window will close automatically.",callback:pe.await(r).pipe(a.flatMap(s=>Wf(s,n,t)),a.map(s=>Cc(Pc,s)))}}),"authorize"),refresh:i(t=>Bf(Pc,t),"refresh")},yw={integrationID:X.ID.make("openai"),method:{id:Rc,type:"oauth",label:"ChatGPT Pro/Plus (headless)"},authorize:i(()=>a.gen(function*(){let t=yield*Ic(`${jr}/api/accounts/deviceauth/usercode`,{method:"POST",headers:Ts("application/json"),body:JSON.stringify({client_id:Os})}),e=Math.max(Number.parseInt(t.interval)||5,1)*1e3;return{mode:"auto",url:`${jr}/codex/device`,instructions:`Enter code: ${t.user_code}`,callback:a.gen(function*(){for(;;){let r=yield*a.tryPromise({try:i(n=>fetch(`${jr}/api/accounts/deviceauth/token`,{method:"POST",headers:Ts("application/json"),body:JSON.stringify({device_auth_id:t.device_auth_id,user_code:t.user_code}),signal:n}),"try"),catch:i(n=>n,"catch")});if(r.ok){let n=yield*a.promise(()=>r.json());return Cc(Rc,yield*Wf(n.authorization_code,`${jr}/deviceauth/callback`,{verifier:n.code_verifier,challenge:""}))}if(r.status!==403&&r.status!==404)return yield*a.fail(new Error(`Device authorization failed: ${r.status}`));yield*a.sleep(e+hw)}})}}),"authorize"),refresh:i(t=>Bf(Rc,t),"refresh")},Gf={id:"openai",effect:a.fn(function*(t){yield*t.integration.transform(e=>{e.method.update(gw),e.method.update(yw)}),yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list())r.provider.api.type==="aisdk"&&r.provider.api.package==="@ai-sdk/openai"&&r.models.has(ve.ID.make("gpt-5-chat-latest"))&&e.model.update(r.provider.id,ve.ID.make("gpt-5-chat-latest"),n=>{n.enabled=!1})})),yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/openai")return;let r=yield*a.promise(()=>import("./dist-RIC4WKHC.js"));e.sdk=r.createOpenAI(e.options)})),yield*t.aisdk.language(a.fn(function*(e){e.model.providerID===K.ID.openai&&(e.language=e.sdk.responses(e.model.api.id))}))})};function Ts(t){return{"Content-Type":t,"User-Agent":`opencode/${ht}`}}i(Ts,"headers");function Wf(t,e,r){return Ic(`${jr}/oauth/token`,{method:"POST",headers:Ts("application/x-www-form-urlencoded"),body:new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e,client_id:Os,code_verifier:r.verifier}).toString()})}i(Wf,"exchange");function Bf(t,e){return Ic(`${jr}/oauth/token`,{method:"POST",headers:Ts("application/x-www-form-urlencoded"),body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refresh,client_id:Os}).toString()}).pipe(a.map(r=>{let n=Cc(t,r);return Dt.OAuth.make({...n,metadata:n.metadata??e.metadata})}))}i(Bf,"refresh");function Ic(t,e){return a.tryPromise({try:i(async r=>{let n=await fetch(t,{...e,signal:r});if(!n.ok)throw new Error(`Request failed: ${n.status}`);return n.json()},"try"),catch:i(r=>r,"catch")})}i(Ic,"request");function Cc(t,e){let r=Sw(e);return Dt.OAuth.make({type:"oauth",methodID:t,refresh:e.refresh_token,access:e.access_token,expires:Date.now()+(e.expires_in??3600)*1e3,metadata:r?{accountID:r}:void 0})}i(Cc,"credential");async function _w(){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",e=Array.from(crypto.getRandomValues(new Uint8Array(43)),n=>t[n%t.length]).join(""),r=Jf(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)));return{verifier:e,challenge:r}}i(_w,"generatePKCE");function Jf(t){return Buffer.from(t).toString("base64url")}i(Jf,"base64UrlEncode");function vw(t,e,r){return`${jr}/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:Os,redirect_uri:t,scope:"openid profile email offline_access",code_challenge:e.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:r,originator:"opencode"})}`}i(vw,"authorizeURL");function Sw(t){return Kf(t.id_token)??Kf(t.access_token)}i(Sw,"extractAccountID");function Kf(t){let e=t.split(".")[1];if(e)try{let r=JSON.parse(Buffer.from(e,"base64url").toString());return r.chatgpt_account_id??r["https://api.openai.com/auth"]?.chatgpt_account_id??r.organizations?.[0]?.id}catch{return}}i(Kf,"claim");function ww(t=fetch){return async(e,r)=>{if(r?.body&&typeof r.body=="string")try{let o=JSON.parse(r.body);"max_tokens"in o&&(o.max_completion_tokens=o.max_tokens,delete o.max_tokens,r={...r,body:JSON.stringify(o)})}catch{}let n=await t(e,r);if(!n.ok&&n.status===400)try{let o=await n.clone().json();if(String(o.message||o.error||"").toLowerCase().includes("conversation complete"))return new Response(JSON.stringify({choices:[{finish_reason:"stop",message:{content:"",role:"assistant"}}]}),{status:200,headers:new Headers({"content-type":"application/json"})})}catch{}if(n.body&&n.headers.get("content-type")?.includes("text/event-stream")){let o=n.body.getReader(),s=new TextEncoder,c=new TextDecoder,l=new ReadableStream({async pull(d){let{done:u,value:p}=await o.read();if(u){d.close();return}d.enqueue(s.encode(c.decode(p,{stream:!0}).replace(/"role"\s*:\s*""/g,'"role":"assistant"')))},cancel(){o.cancel()}});return new Response(l,{headers:n.headers,status:n.status})}return n}}i(ww,"cortexFetch");var Yf={id:"snowflake-cortex",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.model.providerID!==K.ID.make("snowflake-cortex"))return;let r=process.env.SNOWFLAKE_CORTEX_TOKEN??process.env.SNOWFLAKE_CORTEX_PAT??(typeof e.options.token=="string"?e.options.token:void 0)??(typeof e.options.apiKey=="string"?e.options.apiKey:void 0),n=typeof e.options.fetch=="function"?e.options.fetch:void 0;e.options.includeUsage!==!1&&(e.options.includeUsage=!0);let o=yield*a.promise(()=>import("./dist-QJPOJCLB.js"));e.sdk=o.createOpenAICompatible({...e.options,...r?{apiKey:r}:{},fetch:ww(n)})}))})};var Xf={id:"openai-compatible",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.sdk||!e.package.includes("@ai-sdk/openai-compatible"))return;e.options.includeUsage!==!1&&(e.options.includeUsage=!0);let r=yield*a.promise(()=>import("./dist-QJPOJCLB.js"));e.sdk=r.createOpenAICompatible(e.options)}))})};var ti="https://opencode.ai/console",Tc="opencode-cli",em=X.MethodID.make("device"),bw=f.Struct({config:op.Info}),kw=f.Struct({device_code:f.String,user_code:f.String,verification_uri_complete:f.String,expires_in:f.Number,interval:f.Number}),tm=f.Struct({access_token:f.String,refresh_token:f.String,expires_in:f.Number}),Ew=f.Struct({error:f.String}),xw=f.Union([tm,Ew]),Pw=f.Struct({id:f.String,email:f.String}),Rw=f.Struct({id:f.String,name:f.String});function Iw(t){return{integrationID:X.ID.make("opencode"),method:{id:em,type:"oauth",label:"OpenCode Console account"},authorize:i(()=>a.gen(function*(){let e=yield*Oc(t,`${ti}/auth/device/code`,{client_id:Tc},kw);return{mode:"auto",url:(yield*a.try({try:i(()=>{let n=new URL(e.verification_uri_complete,`${ti}/`);if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error("expected HTTP(S)");return n},"try"),catch:i(n=>new Error(`Invalid device verification URL: ${n instanceof Error?n.message:String(n)}`),"catch")})).href,instructions:`Enter code: ${e.user_code}`,callback:Tw(t,ti,e.device_code,dr.seconds(e.interval))}}),"authorize"),refresh:i(e=>a.gen(function*(){let r=typeof e.metadata?.server=="string"?e.metadata.server:ti,n=yield*Oc(t,`${r}/auth/device/token`,{grant_type:"refresh_token",refresh_token:e.refresh,client_id:Tc},tm);return{...e,access:n.access_token,refresh:n.refresh_token,expires:Date.now()+n.expires_in*1e3}}),"refresh"),label:i(e=>typeof e.metadata?.orgName=="string"?e.metadata.orgName:void 0,"label")}}i(Iw,"oauth");var rm={id:"opencode",effect:a.fn(function*(t){let e=yield*Ie.Service,r=yield*De.HttpClient,n=Tu.makeUnsafe(1),o=!1,s,c=a.fn("OpencodePlugin.load")(function*(){let d=yield*t.integration.connection.active("opencode"),u=d?yield*t.integration.connection.resolve(d).pipe(a.catch(()=>a.succeed(void 0))):void 0;o=d!==void 0,s=u?yield*Cw(r,u).pipe(a.catch(p=>a.logWarning("failed to load OpenCode provider config",{cause:p}).pipe(a.as(void 0)))):void 0});yield*t.integration.transform(d=>{d.update("opencode",u=>{u.name="OpenCode"}),d.method.update(Iw(r)),d.method.update({integrationID:"opencode",method:{type:"key",label:"API key (service account)"}})}),o=(yield*t.integration.connection.active("opencode"))!==void 0,yield*t.catalog.transform(d=>{for(let[m,g]of Object.entries(s??{})){d.provider.update(m,y=>{y.integrationID=X.ID.make("opencode"),g.name!==void 0&&(y.name=g.name),y.api=g.npm?{type:"aisdk",package:g.npm,url:g.api}:{type:"native",url:g.api,settings:{}},Object.assign(y.request.headers,g.options?.headers),Object.assign(y.request.body,$c(g.options))});for(let[y,h]of Object.entries(g.models??{}))d.model.update(m,y,_=>{h.family!==void 0&&(_.family=h.family),h.name!==void 0&&(_.name=h.name),h.id!==void 0&&(_.api.id=h.id),h.provider!==void 0&&(_.api=h.provider.npm?{id:_.api.id,type:"aisdk",package:h.provider.npm,url:h.provider.api}:{id:_.api.id,type:"native",url:h.provider.api,settings:{}}),h.tool_call!==void 0&&(_.capabilities.tools=h.tool_call),h.modalities?.input!==void 0&&(_.capabilities.input=[...h.modalities.input]),h.modalities?.output!==void 0&&(_.capabilities.output=[...h.modalities.output]);let S=h.provider?.npm??g.npm,E=ip.get(S);if(Object.assign(_.request.headers,h.headers),Object.assign(_.request.body,E.request($c(h.options))),h.variants!==void 0&&(_.variants=Object.entries(h.variants).map(([x,w])=>({id:ve.VariantID.make(x),headers:{...w.headers??{}},body:E.request($c(w))}))),h.release_date!==void 0){let x=Date.parse(h.release_date);_.time.released=Number.isFinite(x)?x:0}h.cost!==void 0&&(_.cost=$w(h.cost)),_.status=h.status??"active",_.enabled=h.status!=="deprecated",h.limit!==void 0&&(_.limit={...h.limit})})}let u=d.provider.get(K.ID.opencode);if(!u)return;let p=!!(process.env.OPENCODE_API_KEY||o||u.provider.request.body.apiKey);if(d.provider.update(u.provider.id,m=>{p||(m.request.body.apiKey="public")}),!p)for(let m of u.models.values())m.cost.some(g=>g.input>0)&&d.model.update(u.provider.id,m.id,g=>{g.enabled=!1})});let l=i(()=>n.withPermit(c().pipe(a.andThen(t.catalog.reload()))),"refresh");yield*e.subscribe(X.Event.ConnectionUpdated).pipe(ur.filter(d=>d.data.integrationID===X.ID.make("opencode")),ur.runForEach(l),a.forkScoped({startImmediately:!0})),yield*l().pipe(a.forkScoped)})};function Cw(t,e){let r=e.metadata,n=typeof r?.server=="string"?r.server:ti,o=typeof r?.orgID=="string"?r.orgID:void 0,s=e.type==="oauth"?e.access:e.key;return t.execute(be.get(`${n}/api/config`).pipe(be.acceptJson,be.bearerToken(s),be.setHeaders(o?{"x-org-id":o}:{}))).pipe(a.flatMap(c=>c.status===404?a.succeed(void 0):Mt.filterStatusOk(c).pipe(a.flatMap(Mt.schemaBodyJson(bw)),a.map(l=>l.config.provider))))}i(Cw,"fetchProviders");function $c(t){return Object.fromEntries(Object.entries(t??{}).filter(([e])=>e!=="apiKey"&&e!=="headers"))}i($c,"withoutCredentials");function $w(t){let e={input:t.input,output:t.output,cache:{read:t.cache_read??0,write:t.cache_write??0}};return t.context_over_200k?[e,{tier:{type:"context",size:2e5},input:t.context_over_200k.input,output:t.context_over_200k.output,cache:{read:t.context_over_200k.cache_read??0,write:t.context_over_200k.cache_write??0}}]:[e]}i($w,"remoteCost");function Tw(t,e,r,n){let o=i(s=>a.gen(function*(){yield*a.sleep(s);let c=yield*Oc(t,`${e}/auth/device/token`,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:r,client_id:Tc},xw,!1);return"access_token"in c?yield*Ow(t,e,c):c.error==="authorization_pending"?yield*o(s):c.error==="slow_down"?yield*o(dr.sum(s,dr.seconds(5))):yield*a.fail(new Error(`Device authorization failed: ${c.error}`))}),"loop");return o(n)}i(Tw,"poll");function Ow(t,e,r){return a.gen(function*(){let[n,o]=yield*a.all([Qf(t,`${e}/api/user`,r.access_token,Pw),Qf(t,`${e}/api/orgs`,r.access_token,f.Array(Rw))],{concurrency:2}),s=o.toSorted((c,l)=>c.name.localeCompare(l.name)||c.id.localeCompare(l.id))[0];return Dt.OAuth.make({type:"oauth",methodID:em,access:r.access_token,refresh:r.refresh_token,expires:Date.now()+r.expires_in*1e3,metadata:{server:e,accountID:n.id,email:n.email,orgID:s?.id,orgName:s?.name}})})}i(Ow,"credential");function Qf(t,e,r,n){return De.filterStatusOk(t).execute(be.get(e).pipe(be.acceptJson,be.bearerToken(r))).pipe(a.flatMap(Mt.schemaBodyJson(n)))}i(Qf,"get");function Oc(t,e,r,n,o=!0){return be.post(e).pipe(be.acceptJson,be.schemaBodyJson(f.Record(f.String,f.String))(r),a.flatMap(s=>t.execute(s)),a.flatMap(s=>o?Mt.filterStatusOk(s):a.succeed(s)),a.flatMap(Mt.schemaBodyJson(n)))}i(Oc,"post");var nm={id:"openrouter",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list())if(r.provider.api.type==="aisdk"&&r.provider.api.package==="@openrouter/ai-sdk-provider"){e.provider.update(r.provider.id,n=>{n.request.headers["HTTP-Referer"]="https://opencode.ai/",n.request.headers["X-Title"]="opencode"});for(let n of[ve.ID.make("gpt-5-chat-latest"),ve.ID.make("openai/gpt-5-chat")])r.models.has(n)&&e.model.update(r.provider.id,n,o=>{o.enabled=!1})}})),yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@openrouter/ai-sdk-provider")return;let r=yield*a.promise(()=>import("./dist-TH2Q44RX.js"));e.sdk=r.createOpenRouter(e.options)}))})};var om={id:"perplexity",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/perplexity")return;let r=yield*a.promise(()=>import("./dist-KBYKWVT5.js"));e.sdk=r.createPerplexity(e.options)}))})};import{pathToFileURL as Aw}from"url";var im={id:"sap-ai-core",effect:a.fn(function*(t){let e=yield*Nt.Service;yield*t.aisdk.sdk(a.fn(function*(r){if(r.model.providerID!==K.ID.make("sap-ai-core"))return;let n=process.env.AICORE_SERVICE_KEY??(typeof r.options.serviceKey=="string"?r.options.serviceKey:void 0);n&&!process.env.AICORE_SERVICE_KEY&&(process.env.AICORE_SERVICE_KEY=n);let o=r.package.startsWith("file://")?r.package:(yield*e.add(r.package).pipe(a.orDie)).entrypoint;if(!o)throw new Error(`Package ${r.package} has no import entrypoint`);let s=yield*a.promise(async()=>await(o.startsWith("file://")?import(o):import(Aw(o).href))).pipe(a.orDie),c=Object.keys(s).find(l=>l.startsWith("create"));if(!c)throw new Error(`Package ${r.package} has no provider factory export`);r.sdk=s[c](n?{deploymentId:process.env.AICORE_DEPLOYMENT_ID,resourceGroup:process.env.AICORE_RESOURCE_GROUP}:{})})),yield*t.aisdk.language(a.fn(function*(r){r.model.providerID===K.ID.make("sap-ai-core")&&(r.language=r.sdk(r.model.api.id))}))})};var sm={id:"togetherai",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/togetherai")return;let r=yield*a.promise(()=>import("./dist-NLXUYBW7.js"));e.sdk=r.createTogetherAI(e.options)}))})};var am={id:"vercel",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list())r.provider.api.type==="aisdk"&&r.provider.api.package==="@ai-sdk/vercel"&&e.provider.update(r.provider.id,n=>{n.request.headers["http-referer"]="https://opencode.ai/",n.request.headers["x-title"]="opencode"})})),yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/vercel")return;let r=yield*a.promise(()=>import("./dist-XAFENVUS.js"));e.sdk=r.createVercel(e.options)}))})};var cm={id:"venice",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="venice-ai-sdk-provider")return;let r=yield*a.promise(()=>import("./dist-VV5FV5RT.js"));e.sdk=r.createVenice(e.options)}))})};var lm={id:"xai",effect:a.fn(function*(t){yield*t.aisdk.sdk(a.fn(function*(e){if(e.package!=="@ai-sdk/xai")return;let r=yield*a.promise(()=>import("./dist-JFXI53ZF.js"));e.sdk=r.createXai(e.options)})),yield*t.aisdk.language(a.fn(function*(e){e.model.providerID===K.ID.make("xai")&&(e.language=e.sdk.responses(e.model.api.id))}))})};var dm={id:"zenmux",effect:a.fn(function*(t){yield*t.catalog.transform(a.fn(function*(e){for(let r of e.provider.list())r.provider.api.type==="aisdk"&&r.provider.api.package==="@ai-sdk/openai-compatible"&&r.provider.api.url==="https://zenmux.ai/api/v1"&&e.provider.update(r.provider.id,n=>{n.request.headers["HTTP-Referer"]??="https://opencode.ai/",n.request.headers["X-Title"]??="opencode"})}))})};var um=[hf,gf,yf,Sf,vf,wf,bf,xf,Pf,Rf,Cf,$f,Tf,Of,Nf,Df,jf,qf,Lf,Uf,Vf,rm,Yf,Xf,Gf,nm,om,im,sm,am,cm,lm,dm,If];var ri={};H(ri,{Plugin:()=>Mw,VariantPlugin:()=>ri,generate:()=>pm});var Mw={id:"variant",effect:a.fn(function*(t){yield*t.catalog.transform(e=>{for(let r of e.provider.list())for(let n of r.models.values())e.model.update(n.providerID,n.id,o=>{let s=pm(o);if(s.length===0)return;let c=new Map(o.variants.map(d=>[d.id,d])),l=new Set(s.map(d=>d.id));o.variants=[...s.map(d=>c.get(d.id)??d),...o.variants.filter(d=>!l.has(d.id))]})})})};function pm(t){if(t.api.type!=="aisdk"||t.api.package!=="@ai-sdk/openai-compatible")return[];let e=`${t.id} ${t.api.id}`.toLowerCase();return["glm-5.2","glm-5-2","glm-5p2"].some(r=>e.includes(r))?["high","max"].map(r=>({id:r,headers:{},body:{reasoning_effort:r}})):[]}i(pm,"generate");function G(t){return t}i(G,"define");var fm=V.effectDiscard(a.gen(function*(){let t=yield*Jt.Service,e=yield*gt.Service,r=yield*Lt.Service,n=yield*X.Service,o=yield*de.Service,s=yield*Ee.Service,c=yield*Ne.Service,l=yield*jt.Service,d=yield*Nt.Service,u=yield*Ie.Service,p=yield*ae.Service,m=yield*_s.Service,g=yield*se.Service,y=yield*De.HttpClient,h=yield*Ce.Service,_=yield*Ze.Service,S=i(E=>{let x={id:E.id,effect:i(w=>E.effect(w).pipe(a.provideService(Jt.Service,t),a.provideService(gt.Service,e),a.provideService(X.Service,n),a.provideService(de.Service,o),a.provideService(Ee.Service,s),a.provideService(Ne.Service,c),a.provideService(jt.Service,l),a.provideService(Nt.Service,d),a.provideService(Ie.Service,u),a.provideService(ae.Service,p),a.provideService(_s.Service,m),a.provideService(se.Service,g),a.provideService(De.HttpClient,y),a.provideService(Ce.Service,h),a.provideService(Ze.Service,_)),"effect")};return r.add(Lt.ID.make(x.id),x.effect)},"add");yield*mt.batch(a.gen(function*(){yield*S(Bo.Plugin),yield*S(Qo.Plugin),yield*S(ei.Plugin),yield*S(qr.Plugin),yield*S(mf),yield*S(Ao.Plugin),yield*S(Mo.Plugin),yield*S(Yo.Plugin);for(let E of um)yield*S(E);yield*S(Do.Plugin),yield*S(No.Plugin),yield*S(ri.Plugin)})).pipe(a.withSpan("PluginInternal.boot"),a.forkScoped({startImmediately:!0}))})),zw=fm.pipe(V.provideMerge(Ee.locationLayer),V.provideMerge(zu.layer)),Dw=Qe({name:"plugin-internal",layer:fm,deps:[Jt.node,gt.node,Lt.node,X.node,de.node,Ee.node,Ne.node,jt.node,Nt.node,Ie.node,ae.node,_s.node,se.node,fr,Ce.node,Ze.node]});var mm=`<!--
417
+ Built-in skill. Name and description are registered in code at
418
+ packages/core/src/plugin/skill.ts
419
+ and CUSTOMIZE_OPENCODE_SKILL_DESCRIPTION). The body below becomes the
420
+ skill's content.
421
+ -->
422
+
423
+ # Customizing opencode
424
+
425
+ opencode validates its own config strictly and refuses to start when a field
426
+ is wrong. The shapes below cover the common surface area, but they are a
427
+ **summary, not the source of truth**.
428
+
429
+ ## Full schema reference
430
+
431
+ The authoritative list of every config option \u2014 with field types, enums,
432
+ defaults, and descriptions \u2014 lives in the published JSON Schema:
433
+
434
+ **<https://opencode.ai/config.json>**
435
+
436
+ If a field is not documented in this skill, or you need to confirm an exact
437
+ shape before writing config, **fetch that URL and read the schema directly**
438
+ rather than guessing. opencode hard-fails on invalid config, so the cost of a
439
+ wrong shape is a broken startup.
440
+
441
+ Independently, every \`opencode.json\` should declare
442
+ \`"$schema": "https://opencode.ai/config.json"\` so the user's editor catches
443
+ mistakes as they type.
444
+
445
+ ## Applying changes
446
+
447
+ Config is loaded once when opencode starts and is not hot-reloaded. After
448
+ saving changes to \`opencode.json\`, an agent file, a skill, a plugin, or any
449
+ other config-time file, **tell the user to quit and restart opencode** for
450
+ the changes to take effect. The running session will keep using the
451
+ already-loaded config until then.
452
+
453
+ ## Where files live
454
+
455
+ | Scope | Path |
456
+ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
457
+ | Project config | \`./opencode.json\`, \`./opencode.jsonc\`, or \`.opencode/opencode.json\` (opencode walks up from the cwd to the worktree root) |
458
+ | Global config | \`~/.config/opencode/opencode.json\` or \`~/.config/opencode/opencode.jsonc\` (NOT \`~/.opencode/\`) |
459
+ | Project agents | \`.opencode/agent/<name>.md\` or \`.opencode/agents/<name>.md\` |
460
+ | Global agents | \`~/.config/opencode/agent(s)/<name>.md\` |
461
+ | Project commands | \`.opencode/command/<name>.md\` or \`.opencode/commands/<name>.md\` |
462
+ | Global commands | \`~/.config/opencode/command(s)/<name>.md\` |
463
+ | Project skills | \`.opencode/skill(s)/<name>/SKILL.md\` |
464
+ | Global skills | \`~/.config/opencode/skill(s)/<name>/SKILL.md\` |
465
+ | External skills (auto-loaded) | \`~/.claude/skills/<name>/SKILL.md\`, \`~/.agents/skills/<name>/SKILL.md\` |
466
+
467
+ Configs from each scope are deep-merged. Project overrides global. Unknown
468
+ top-level keys in \`opencode.json\` are rejected with \`ConfigInvalidError\`.
469
+
470
+ ## opencode.json
471
+
472
+ Every field is optional.
473
+
474
+ \`\`\`json
475
+ {
476
+ "$schema": "https://opencode.ai/config.json",
477
+ "username": "string",
478
+ "model": "provider/model-id",
479
+ "small_model": "provider/model-id",
480
+ "default_agent": "agent-name",
481
+ "shell": "/bin/zsh",
482
+ "logLevel": "DEBUG" | "INFO" | "WARN" | "ERROR",
483
+ "share": "manual" | "auto" | "disabled",
484
+ "autoupdate": true | false | "notify",
485
+ "snapshot": true,
486
+ "instructions": ["AGENTS.md", "docs/style.md"],
487
+
488
+ "skills": {
489
+ "paths": [".opencode/skills", "/abs/path/to/skills"],
490
+ "urls": ["https://example.com/.well-known/skills/"]
491
+ },
492
+
493
+ "references": {
494
+ "docs": {
495
+ "path": "../docs",
496
+ "description": "Use for product behavior and documentation conventions"
497
+ },
498
+ "sdk": {
499
+ "repository": "owner/sdk",
500
+ "branch": "main",
501
+ "description": "Use for SDK implementation details",
502
+ "hidden": true
503
+ }
504
+ },
505
+
506
+ "agent": {
507
+ "my-agent": {
508
+ "model": "anthropic/claude-sonnet-4-6",
509
+ "mode": "subagent",
510
+ "description": "...",
511
+ "permission": { "edit": "deny" }
512
+ }
513
+ },
514
+
515
+ "command": {
516
+ "deploy": { "description": "...", "template": "..." }
517
+ },
518
+
519
+ "provider": {
520
+ "anthropic": { "options": { "apiKey": "..." } }
521
+ },
522
+ "disabled_providers": ["openai"],
523
+ "enabled_providers": ["anthropic"],
524
+
525
+ "mcp": {
526
+ "playwright": {
527
+ "type": "local",
528
+ "command": ["npx", "-y", "@playwright/mcp"],
529
+ "enabled": true,
530
+ "environment": {}
531
+ },
532
+ "remote-thing": {
533
+ "type": "remote",
534
+ "url": "https://...",
535
+ "headers": { "Authorization": "Bearer ..." }
536
+ }
537
+ },
538
+
539
+ "plugin": [
540
+ "opencode-gemini-auth",
541
+ "opencode-foo@1.2.3",
542
+ "./local-plugin.ts",
543
+ ["opencode-bar", { "option": "value" }]
544
+ ],
545
+
546
+ "permission": {
547
+ "edit": "deny",
548
+ "bash": { "git *": "allow", "*": "ask" }
549
+ },
550
+
551
+ "formatter": false,
552
+ "lsp": false,
553
+
554
+ "experimental": {
555
+ "primary_tools": ["edit"],
556
+ "mcp_timeout": 30000
557
+ },
558
+
559
+ "tool_output": { "max_lines": 200, "max_bytes": 8192 },
560
+
561
+ "compaction": { "auto": true, "tail_turns": 15 }
562
+ }
563
+ \`\`\`
564
+
565
+ Shape notes worth being explicit about:
566
+
567
+ - \`model\` always carries a provider prefix: \`"anthropic/claude-sonnet-4-6"\`.
568
+ - \`skills\` is an object with \`paths\` and/or \`urls\`, not an array.
569
+ - \`references\` is an object keyed by alias. Each value is a local path, Git repository, or string shorthand.
570
+ - \`agent\` is an object keyed by agent name, not an array.
571
+ - \`command\` is an object keyed by command name, not an array.
572
+ - \`plugin\` is an array of strings or \`[name, options]\` tuples, not an object.
573
+ - \`mcp[name].command\` is an array of strings, never a single string. \`type\` is required.
574
+ - \`permission\` is either a string action or an object keyed by tool name.
575
+
576
+ ## Skills
577
+
578
+ opencode's skill loader scans for \`**/SKILL.md\` inside skill directories. The
579
+ file is named \`SKILL.md\` exactly, and lives in its own folder named after the
580
+ skill:
581
+
582
+ \`\`\`
583
+ .opencode/skills/my-skill/SKILL.md
584
+ \`\`\`
585
+
586
+ Frontmatter:
587
+
588
+ \`\`\`markdown
589
+ ---
590
+ name: my-skill
591
+ description: One sentence covering what this skill does AND when to trigger it. Front-load the literal keywords or filenames the user is likely to say.
592
+ ---
593
+
594
+ # My Skill
595
+
596
+ (skill body in markdown: instructions, examples, references)
597
+ \`\`\`
598
+
599
+ - \`name\` is required, lowercase hyphen-separated, up to 64 chars, and matches the folder name.
600
+ - \`description\` is effectively required: skills without one are filtered out and never surfaced to the model. Cover both _what_ the skill does and _when_ to use it. Write in third person ("Use when...", not "I help with..."). Front-load concrete trigger keywords and filenames; gate with "Use ONLY when..." if the skill should stay quiet on adjacent topics.
601
+ - Optional: \`license\`, \`compatibility\`, \`metadata\` (string-string map).
602
+
603
+ Register skills from non-default locations via \`skills.paths\` (scanned
604
+ recursively for \`**/SKILL.md\`) and \`skills.urls\` (each URL serves a list of
605
+ skills).
606
+
607
+ ## References
608
+
609
+ References make local directories and Git repositories outside the active
610
+ project available as supporting context. Configure them under \`references\`,
611
+ keyed by the alias used in \`@\` autocomplete:
612
+
613
+ \`\`\`json
614
+ {
615
+ "references": {
616
+ "docs": {
617
+ "path": "../product-docs",
618
+ "description": "Use for product behavior and terminology"
619
+ },
620
+ "effect": {
621
+ "repository": "Effect-TS/effect",
622
+ "branch": "main",
623
+ "description": "Use for Effect implementation details"
624
+ }
625
+ }
626
+ }
627
+ \`\`\`
628
+
629
+ Local \`path\` values may be relative to the declaring config, absolute, or use
630
+ \`~/\`. Git \`repository\` values accept Git URLs, host/path references, and GitHub
631
+ \`owner/repo\` shorthand; \`branch\` is optional. Both forms support optional
632
+ \`description\` and \`hidden\` fields.
633
+
634
+ - Only references with a \`description\` are advertised to agents in system context.
635
+ - \`hidden: true\` removes a reference from TUI \`@\` autocomplete only. It remains available to agents and by direct path.
636
+ - Reference directories are automatically allowed through the external-directory boundary; normal read/edit/tool permissions still apply.
637
+ - String shorthand is supported: use \`"docs": "../docs"\` for local paths or \`"effect": "Effect-TS/effect"\` for Git repositories.
638
+
639
+ ## Agents
640
+
641
+ Two ways to define an agent. Use the file form for anything non-trivial.
642
+
643
+ ### Inline (in \`opencode.json\`)
644
+
645
+ \`\`\`json
646
+ {
647
+ "agent": {
648
+ "my-reviewer": {
649
+ "description": "Reviews PRs for style violations.",
650
+ "mode": "subagent",
651
+ "model": "anthropic/claude-sonnet-4-6",
652
+ "permission": { "edit": "deny", "bash": "ask" },
653
+ "prompt": "You are a strict PR reviewer..."
654
+ }
655
+ }
656
+ }
657
+ \`\`\`
658
+
659
+ ### File
660
+
661
+ \`\`\`
662
+ .opencode/agent/my-reviewer.md OR .opencode/agents/my-reviewer.md
663
+ \`\`\`
664
+
665
+ \`\`\`markdown
666
+ ---
667
+ description: Reviews PRs for style violations.
668
+ mode: subagent
669
+ model: anthropic/claude-sonnet-4-6
670
+ permission:
671
+ edit: deny
672
+ bash: ask
673
+ ---
674
+
675
+ You are a strict PR reviewer. Focus on...
676
+ \`\`\`
677
+
678
+ The file body becomes the agent's \`prompt\`. Do not also put \`prompt:\` in the
679
+ frontmatter.
680
+
681
+ \`mode\` is one of \`"primary"\`, \`"subagent"\`, \`"all"\`.
682
+
683
+ Allowed top-level frontmatter fields: \`name, model, variant, description, mode,
684
+ hidden, color, steps, options, permission, disable, temperature, top_p\`. Any
685
+ unknown field is silently routed into \`options\`.
686
+
687
+ To disable a built-in agent: \`agent: { build: { disable: true } }\`, or in a
688
+ file, \`disable: true\` in frontmatter.
689
+
690
+ \`default_agent\` must point to a non-hidden, primary-mode agent.
691
+
692
+ ### Built-in agents
693
+
694
+ opencode ships with \`build\`, \`plan\`, \`general\`, \`explore\`. Hidden internal agents:
695
+ \`compaction\`, \`title\`, \`summary\`. To override a built-in's fields, define the
696
+ same key in \`agent: { <name>: { ... } }\`.
697
+
698
+ ## Commands
699
+
700
+ opencode's command loader scans for \`**/*.md\` inside command directories. The
701
+ file is named after the command, and lives directly inside the \`command\` folder:
702
+
703
+ \`\`\`
704
+ .opencode/command/deploy.md
705
+ \`\`\`
706
+
707
+ Frontmatter:
708
+
709
+ \`\`\`markdown
710
+ ---
711
+ description: One sentence describing what the command does.
712
+ agent: build
713
+ model: anthropic/claude-sonnet-4-6
714
+ ---
715
+
716
+ (command body in markdown: the prompt opencode runs, with $ARGUMENTS for the user's input)
717
+ \`\`\`
718
+
719
+ - \`template\` is the command body \u2014 everything below the frontmatter \u2014 and is required: it is the prompt opencode runs when the command is invoked. Do not also put a \`template:\` key in the frontmatter.
720
+ - \`$ARGUMENTS\` is replaced with everything the user typed after the command; \`$1\`, \`$2\`, \u2026 pull individual positional arguments.
721
+ - Optional: \`description\`, \`agent\`, \`model\`, \`variant\`, \`subtask\`.
722
+
723
+ ## Plugins
724
+
725
+ \`plugin:\` is an array. Each entry is one of:
726
+
727
+ \`\`\`json
728
+ "plugin": [
729
+ "opencode-gemini-auth", // npm spec, latest
730
+ "opencode-foo@1.2.3", // npm spec, pinned
731
+ "./local-plugin.ts", // file path, relative to the declaring config
732
+ "file:///abs/path/plugin.js", // file URL
733
+ ["opencode-bar", { "key": "val" }] // tuple form with options
734
+ ]
735
+ \`\`\`
736
+
737
+ Auto-discovered plugins (no config entry needed): any \`*.ts\` or \`*.js\` file in
738
+ \`.opencode/plugin/\` or \`.opencode/plugins/\`.
739
+
740
+ A plugin module exports \`default\` (or any named export) of type
741
+ \`Plugin = (input: PluginInput, options?) => Promise<Hooks>\`. The export is a
742
+ function, not a plain object literal, and the function returns an object
743
+ (return \`{}\` if there is nothing to register).
744
+
745
+ \`\`\`ts
746
+ import type { Plugin } from "@opencode-ai/plugin"
747
+
748
+ export default (async ({ client, project, directory, $ }) => {
749
+ return {
750
+ config: (cfg) => {
751
+ // cfg is the live merged config; mutate fields here.
752
+ },
753
+ "tool.execute.before": async (input, output) => {
754
+ // mutate output.args before the tool runs
755
+ },
756
+ }
757
+ }) satisfies Plugin
758
+ \`\`\`
759
+
760
+ Hook surface (mutate \`output\` in place; return \`void\`):
761
+
762
+ - \`event(input)\`: every bus event
763
+ - \`config(cfg)\`: once on init with the merged config
764
+ - \`chat.message\`, \`chat.params\`, \`chat.headers\`
765
+ - \`tool.execute.before\`, \`tool.execute.after\`
766
+ - \`tool.definition\`
767
+ - \`command.execute.before\`
768
+ - \`shell.env\`
769
+ - \`permission.ask\`
770
+ - \`experimental.chat.messages.transform\`, \`experimental.chat.system.transform\`,
771
+ \`experimental.session.compacting\`, \`experimental.compaction.autocontinue\`,
772
+ \`experimental.text.complete\`
773
+
774
+ Special object-shaped (not callbacks): \`tool: { my_tool: { ... } }\`,
775
+ \`auth: { ... }\`, \`provider: { ... }\`.
776
+
777
+ ## MCP servers
778
+
779
+ \`mcp:\` is an object keyed by server name. Each server is discriminated by
780
+ \`type\`:
781
+
782
+ \`\`\`json
783
+ {
784
+ "mcp": {
785
+ "playwright": {
786
+ "type": "local",
787
+ "command": ["npx", "-y", "@playwright/mcp"],
788
+ "enabled": true,
789
+ "environment": { "BROWSER": "chromium" }
790
+ },
791
+ "github": {
792
+ "type": "remote",
793
+ "url": "https://...",
794
+ "enabled": true,
795
+ "headers": { "Authorization": "Bearer {env:GITHUB_TOKEN}" }
796
+ },
797
+ "old-server": { "enabled": false }
798
+ }
799
+ }
800
+ \`\`\`
801
+
802
+ \`command\` is an array of strings. \`environment\` sets environment variables for
803
+ a local MCP server. \`type\` is required. Use \`enabled: false\` to
804
+ disable a server inherited from a parent config. String values such as header
805
+ tokens support \`{env:VAR}\` interpolation (and \`{file:path}\`); the shell-style
806
+ \`\${VAR}\` is not substituted.
807
+
808
+ ## Permissions
809
+
810
+ \`\`\`json
811
+ "permission": {
812
+ "edit": "deny",
813
+ "bash": { "git *": "allow", "rm *": "deny", "*": "ask" },
814
+ "external_directory": { "~/secrets/**": "deny", "*": "allow" }
815
+ }
816
+ \`\`\`
817
+
818
+ Actions: \`"allow"\`, \`"ask"\`, \`"deny"\`.
819
+
820
+ Per-tool value forms: \`"allow"\` shorthand (treated as \`{"*": "allow"}\`), or an
821
+ object \`{ pattern: action }\`. Within an object, **insertion order matters**.
822
+ opencode evaluates the LAST matching rule, so put broad rules first and narrow
823
+ rules last.
824
+
825
+ \`permission: "allow"\` (a string at the top level) is shorthand for "allow
826
+ everything" and is rarely what the user wants.
827
+
828
+ Known permission keys: \`read, edit, glob, grep, list, bash, task,
829
+ external_directory, todowrite, question, webfetch, websearch, lsp, doom_loop,
830
+ skill\`. Some of these (\`todowrite,
831
+ question, webfetch, websearch, doom_loop\`) only accept a flat
832
+ action, not a per-pattern object.
833
+
834
+ \`external_directory\` patterns are filesystem paths (use \`~/\`, absolute paths,
835
+ or globs like \`~/projects/**\`).
836
+
837
+ Per-agent \`permission:\` overrides top-level \`permission:\`. Plan Mode lives on
838
+ the \`plan\` agent's permission ruleset (\`edit: deny *\`).
839
+
840
+ ## Escape hatches
841
+
842
+ When a user's config is broken and opencode won't start, these env vars help:
843
+
844
+ - \`OPENCODE_DISABLE_PROJECT_CONFIG=1\`: skip the project's local \`opencode.json\`
845
+ and start from globals only. Run from the project directory, opencode loads,
846
+ the user edits the broken file, then they restart without the flag.
847
+ - \`OPENCODE_CONFIG=/path/to/file.json\`: load an additional explicit config.
848
+ - \`OPENCODE_CONFIG_CONTENT='{"$schema":"https://opencode.ai/config.json"}'\`:
849
+ inject inline JSON as a final local-scope merge.
850
+ - \`OPENCODE_DISABLE_DEFAULT_PLUGINS=1\`: skip default plugins.
851
+ - \`OPENCODE_PURE=1\`: skip external plugins entirely.
852
+ - \`OPENCODE_DISABLE_EXTERNAL_SKILLS=1\`,
853
+ \`OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1\`: skip the external skill scans under
854
+ \`~/.claude/\` and \`~/.agents/\`.
855
+
856
+ ## When proposing edits
857
+
858
+ - Validate against the schema before writing. If you are unsure of a field's
859
+ exact shape, or the field is not covered in this skill, fetch
860
+ \`https://opencode.ai/config.json\` and read the schema rather than guessing.
861
+ - Preserve \`$schema\` and any existing fields the user did not ask to change.
862
+ - For agent, command, skill, and plugin definitions, prefer creating new files
863
+ in the correct location over inlining everything in \`opencode.json\`.
864
+ - If the user's existing config is malformed, point them at the env-var escape
865
+ hatches above so they can edit from inside opencode without breaking their
866
+ session.
867
+ - After saving any config change, remind the user to quit and restart opencode
868
+ \u2014 running sessions keep using the already-loaded config.
869
+ `;var hm=mm,Nw={id:"skill",effect:a.fn(function*(t){yield*t.skill.transform(e=>{e.source(Ce.EmbeddedSource.make({type:"embedded",skill:Ce.Info.make({name:"customize-opencode",description:"Use ONLY when the user is editing or creating opencode's own configuration: opencode.json, opencode.jsonc, files under .opencode/, or files under ~/.config/opencode/. Also use when creating or fixing opencode agents, subagents, commands, skills, plugins, MCP servers, or permission rules. Do not use for the user's own application code, or for any project that is not configuring opencode itself.",location:_e.make("/builtin/customize-opencode.md"),content:hm})}))})})};function gm(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}i(gm,"escapeHtml");var jw=".claude",qw=".agents",ym="skills/**/SKILL.md",Lw="{skill,skills}/**/SKILL.md",_m="**/SKILL.md",vm="customize-opencode",Uw="Use ONLY when the user is editing or creating opencode's own configuration: opencode.json, opencode.jsonc, files under .opencode/, or files under ~/.config/opencode/. Also use when creating or fixing opencode agents, subagents, skills, plugins, MCP servers, or permission rules. Do not use for the user's own application code, or for any project that is not configuring opencode itself.",Vw=qr.CustomizeOpencodeContent,Fw=f.Struct({name:f.String,description:f.optional(f.String),location:f.String,content:f.String}),Hw=f.StructWithRest(f.Struct({message:f.String,path:f.Array(f.String)}),[f.Record(f.String,f.Unknown)]);function Zw(t){return _p(t)&&typeof t.name=="string"&&(t.description===void 0||typeof t.description=="string")}i(Zw,"isSkillFrontmatter");var Mc=class extends f.TaggedErrorClass()("SkillInvalidError",{path:f.String,message:f.optional(f.String),issues:f.optional(f.Array(Hw))}){static{i(this,"InvalidError")}},zc=class extends f.TaggedErrorClass()("SkillNameMismatchError",{path:f.String,expected:f.String,actual:f.String}){static{i(this,"NameMismatchError")}},As=class extends f.TaggedErrorClass()("Skill.NotFoundError",{name:f.String,available:f.Array(f.String)}){static{i(this,"NotFoundError")}get message(){return`Skill "${this.name}" not found. Available skills: ${this.available.join(", ")||"none"}`}},Kw=a.fnUntraced(function*(t,e,r){let n=yield*a.tryPromise({try:i(()=>Sp.parse(e),"try"),catch:i(o=>o,"catch")}).pipe(a.catch(a.fnUntraced(function*(o){let s=vp.isInstance(o)?o.data.message:`Failed to parse skill ${e}`,{Session:c}=yield*a.promise(()=>import("./session-6OPJNJMK.js"));yield*r.publish(c.Event.Error,{error:new vs.Unknown({message:s}).toObject()}),yield*a.logError("failed to load skill",{skill:e,error:o})})));n&&Zw(n.data)&&(t.skills[n.data.name]&&(yield*a.logWarning("duplicate skill name",{name:n.data.name,existing:t.skills[n.data.name].location,duplicate:e})),t.dirs.add(Ln.dirname(e)),t.skills[n.data.name]={name:n.data.name,description:n.data.description,location:e,content:n.content})}),ni=a.fnUntraced(function*(t,e,r,n){let o=yield*a.tryPromise({try:i(()=>Bu.scan(r,{cwd:e,absolute:!0,include:"file",symlink:!0,dot:n?.dot}),"try"),catch:i(s=>s,"catch")}).pipe(a.catch(s=>n?.scope?a.logError(`failed to scan ${n.scope} skills`,{dir:e,error:s}).pipe(a.as([])):a.die(s)));for(let s of o)t.matches.add(s),t.dirs.add(Ln.dirname(s))}),Gw=a.fnUntraced(function*(t,e,r,n,o,s,c,l){let d={matches:new Set,dirs:new Set},u=[];if(!o){s||u.push(jw),u.push(qw);for(let y of u){let h=Ln.join(n.home,y);(yield*r.isDir(h))&&(yield*ni(d,h,ym,{dot:!0,scope:"global"}))}let g=yield*r.up({targets:u,start:c,stop:l}).pipe(a.catch(()=>a.succeed([])));for(let y of g)yield*ni(d,y,ym,{dot:!0,scope:"project"})}let p=yield*t.directories();for(let g of p)yield*ni(d,g,Lw);let m=yield*t.get();for(let g of m.skills?.paths??[]){let y=g.startsWith("~/")?Ln.join(n.home,g.slice(2)):g,h=Ln.isAbsolute(y)?y:Ln.join(c,y);if(!(yield*r.isDir(h))){yield*a.logWarning("skill path not found",{path:h});continue}yield*ni(d,h,_m)}for(let g of m.skills?.urls??[]){let y=yield*e.pull(g);for(let h of y)yield*ni(d,h,_m)}return{matches:Array.from(d.matches),dirs:Array.from(d.dirs)}}),Ww=a.fnUntraced(function*(t,e,r){yield*a.forEach(e.matches,n=>Kw(t,n,r),{concurrency:"unbounded",discard:!0}),yield*a.logInfo("init",{count:Object.keys(t.skills).length})}),Un=class extends te.Service()("@opencode/Skill"){static{i(this,"Service")}},Bw=V.effect(Un,a.gen(function*(){let t=yield*Sn.Service,e=yield*gn.Service,r=yield*Xt.Service,n=yield*ae.Service,o=yield*se.Service,s=yield*oc.Service,c=yield*Q.make(a.fn("Skill.discovery")(function*(y){return yield*Gw(e,t,n,o,s.disableExternalSkills,s.disableClaudeCodeSkills,y.directory,y.worktree)})),l=yield*Q.make(a.fn("Skill.state")(function*(){let y={skills:{},dirs:new Set};return y.skills[vm]={name:vm,description:Uw,location:"<built-in>",content:Vw},yield*Ww(y,yield*Q.get(c),r),y})),d=a.fn("Skill.get")(function*(y){return(yield*Q.get(l)).skills[y]}),u=a.fn("Skill.require")(function*(y){let h=yield*Q.get(l),_=h.skills[y];return _||(yield*new As({name:y,available:Object.keys(h.skills).toSorted()}))}),p=a.fn("Skill.all")(function*(){let y=yield*Q.get(l);return Object.values(y.skills)}),m=a.fn("Skill.dirs")(function*(){return(yield*Q.get(c)).dirs}),g=a.fn("Skill.available")(function*(y){let h=yield*Q.get(l),_=Object.values(h.skills).toSorted((S,E)=>S.name.localeCompare(E.name));return y?_.filter(S=>$o.evaluate("skill",S.name,y.permission).action!=="deny"):_});return Un.of({get:d,require:u,all:p,dirs:m,available:g})}));function Jw(t,e){let r=t.filter(n=>n.description!==void 0);return r.length===0?"No skills are currently available.":e.verbose?["<available_skills>",...r.toSorted((n,o)=>n.name.localeCompare(o.name)).flatMap(n=>[" <skill>",` <name>${n.name}</name>`,` <description>${n.description}</description>`,` <location>${gm(n.location)}</location>`," </skill>"]),"</available_skills>"].join(`
870
+ `):["## Available Skills",...r.toSorted((n,o)=>n.name.localeCompare(o.name)).map(n=>`- **${n.name}**: ${n.description}`)].join(`
871
+ `)}i(Jw,"fmt");var Yw=ft.make({service:Un,layer:Bw,deps:[Sn.node,gn.node,Xt.node,ae.node,se.node,oc.node]});var Fn="2025-11-25";var Sm=[Fn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],gr="io.modelcontextprotocol/related-task",zs="2.0",Oe=pp(t=>t!==null&&(typeof t=="object"||typeof t=="function")),wm=Se([v(),ce().int()]),bm=v(),Ij=Te({ttl:ce().optional(),pollInterval:ce().optional()}),Qw=T({ttl:ce().optional()}),eb=T({taskId:v()}),jc=Te({progressToken:wm.optional(),[gr]:eb.optional()}),dt=T({_meta:jc.optional()}),oi=dt.extend({task:Qw.optional()}),km=i(t=>oi.safeParse(t).success,"isTaskAugmentedRequestParams"),je=T({method:v(),params:dt.loose().optional()}),_t=T({_meta:jc.optional()}),vt=T({method:v(),params:_t.loose().optional()}),qe=Te({_meta:jc.optional()}),Ds=Se([v(),ce().int()]),Em=T({jsonrpc:M(zs),id:Ds,...je.shape}).strict(),ii=i(t=>Em.safeParse(t).success,"isJSONRPCRequest"),xm=T({jsonrpc:M(zs),...vt.shape}).strict(),Pm=i(t=>xm.safeParse(t).success,"isJSONRPCNotification"),qc=T({jsonrpc:M(zs),id:Ds,result:qe}).strict(),Lr=i(t=>qc.safeParse(t).success,"isJSONRPCResultResponse");var q;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(q||(q={}));var Lc=T({jsonrpc:M(zs),id:Ds.optional(),error:T({code:ce().int(),message:v(),data:xe().optional()})}).strict();var Ns=i(t=>Lc.safeParse(t).success,"isJSONRPCErrorResponse");var yr=Se([Em,xm,qc,Lc]),Cj=Se([qc,Lc]),Ur=qe.strict(),tb=_t.extend({requestId:Ds.optional(),reason:v().optional()}),js=vt.extend({method:M("notifications/cancelled"),params:tb}),rb=T({src:v(),mimeType:v().optional(),sizes:$(v()).optional(),theme:at(["light","dark"]).optional()}),si=T({icons:$(rb).optional()}),Vn=T({name:v(),title:v().optional()}),Rm=Vn.extend({...Vn.shape,...si.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),nb=rc(T({applyDefaults:fe().optional()}),he(v(),xe())),ob=nc(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,rc(T({form:nb.optional(),url:Oe.optional()}),he(v(),xe()).optional())),ib=Te({list:Oe.optional(),cancel:Oe.optional(),requests:Te({sampling:Te({createMessage:Oe.optional()}).optional(),elicitation:Te({create:Oe.optional()}).optional()}).optional()}),sb=Te({list:Oe.optional(),cancel:Oe.optional(),requests:Te({tools:Te({call:Oe.optional()}).optional()}).optional()}),ab=T({experimental:he(v(),Oe).optional(),sampling:T({context:Oe.optional(),tools:Oe.optional()}).optional(),elicitation:ob.optional(),roots:T({listChanged:fe().optional()}).optional(),tasks:ib.optional(),extensions:he(v(),Oe).optional()}),cb=dt.extend({protocolVersion:v(),capabilities:ab,clientInfo:Rm}),Im=je.extend({method:M("initialize"),params:cb}),Cm=i(t=>Im.safeParse(t).success,"isInitializeRequest"),lb=T({experimental:he(v(),Oe).optional(),logging:Oe.optional(),completions:Oe.optional(),prompts:T({listChanged:fe().optional()}).optional(),resources:T({subscribe:fe().optional(),listChanged:fe().optional()}).optional(),tools:T({listChanged:fe().optional()}).optional(),tasks:sb.optional(),extensions:he(v(),Oe).optional()}),Uc=qe.extend({protocolVersion:v(),capabilities:lb,serverInfo:Rm,instructions:v().optional()}),$m=vt.extend({method:M("notifications/initialized"),params:_t.optional()}),qs=i(t=>$m.safeParse(t).success,"isInitializedNotification"),Ls=je.extend({method:M("ping"),params:dt.optional()}),db=T({progress:ce(),total:ke(ce()),message:ke(v())}),ub=T({..._t.shape,...db.shape,progressToken:wm}),Us=vt.extend({method:M("notifications/progress"),params:ub}),pb=dt.extend({cursor:bm.optional()}),ai=je.extend({params:pb.optional()}),ci=qe.extend({nextCursor:bm.optional()}),fb=at(["working","input_required","completed","failed","cancelled"]),li=T({taskId:v(),status:fb,ttl:Se([ce(),dp()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:ke(ce()),statusMessage:ke(v())}),Vr=qe.extend({task:li}),mb=_t.merge(li),di=vt.extend({method:M("notifications/tasks/status"),params:mb}),Vs=je.extend({method:M("tasks/get"),params:dt.extend({taskId:v()})}),Fs=qe.merge(li),Hs=je.extend({method:M("tasks/result"),params:dt.extend({taskId:v()})}),$j=qe.loose(),Zs=ai.extend({method:M("tasks/list")}),Ks=ci.extend({tasks:$(li)}),Gs=je.extend({method:M("tasks/cancel"),params:dt.extend({taskId:v()})}),Tm=qe.merge(li),Om=T({uri:v(),mimeType:ke(v()),_meta:he(v(),xe()).optional()}),Am=Om.extend({text:v()}),Vc=v().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mm=Om.extend({blob:Vc}),ui=at(["user","assistant"]),Hn=T({audience:$(ui).optional(),priority:ce().min(0).max(1).optional(),lastModified:cp.datetime({offset:!0}).optional()}),zm=T({...Vn.shape,...si.shape,uri:v(),description:ke(v()),mimeType:ke(v()),size:ke(ce()),annotations:Hn.optional(),_meta:ke(Te({}))}),hb=T({...Vn.shape,...si.shape,uriTemplate:v(),description:ke(v()),mimeType:ke(v()),annotations:Hn.optional(),_meta:ke(Te({}))}),gb=ai.extend({method:M("resources/list")}),Fc=ci.extend({resources:$(zm)}),yb=ai.extend({method:M("resources/templates/list")}),Hc=ci.extend({resourceTemplates:$(hb)}),Zc=dt.extend({uri:v()}),_b=Zc,vb=je.extend({method:M("resources/read"),params:_b}),Kc=qe.extend({contents:$(Se([Am,Mm]))}),Gc=vt.extend({method:M("notifications/resources/list_changed"),params:_t.optional()}),Sb=Zc,wb=je.extend({method:M("resources/subscribe"),params:Sb}),bb=Zc,kb=je.extend({method:M("resources/unsubscribe"),params:bb}),Eb=_t.extend({uri:v()}),xb=vt.extend({method:M("notifications/resources/updated"),params:Eb}),Pb=T({name:v(),description:ke(v()),required:ke(fe())}),Rb=T({...Vn.shape,...si.shape,description:ke(v()),arguments:ke($(Pb)),_meta:ke(Te({}))}),Ib=ai.extend({method:M("prompts/list")}),Wc=ci.extend({prompts:$(Rb)}),Cb=dt.extend({name:v(),arguments:he(v(),v()).optional()}),$b=je.extend({method:M("prompts/get"),params:Cb}),Bc=T({type:M("text"),text:v(),annotations:Hn.optional(),_meta:he(v(),xe()).optional()}),Jc=T({type:M("image"),data:Vc,mimeType:v(),annotations:Hn.optional(),_meta:he(v(),xe()).optional()}),Yc=T({type:M("audio"),data:Vc,mimeType:v(),annotations:Hn.optional(),_meta:he(v(),xe()).optional()}),Tb=T({type:M("tool_use"),name:v(),id:v(),input:he(v(),xe()),_meta:he(v(),xe()).optional()}),Ob=T({type:M("resource"),resource:Se([Am,Mm]),annotations:Hn.optional(),_meta:he(v(),xe()).optional()}),Ab=zm.extend({type:M("resource_link")}),Xc=Se([Bc,Jc,Yc,Ab,Ob]),Mb=T({role:ui,content:Xc}),Qc=qe.extend({description:v().optional(),messages:$(Mb)}),el=vt.extend({method:M("notifications/prompts/list_changed"),params:_t.optional()}),zb=T({title:v().optional(),readOnlyHint:fe().optional(),destructiveHint:fe().optional(),idempotentHint:fe().optional(),openWorldHint:fe().optional()}),Db=T({taskSupport:at(["required","optional","forbidden"]).optional()}),Ws=T({...Vn.shape,...si.shape,description:v().optional(),inputSchema:T({type:M("object"),properties:he(v(),Oe).optional(),required:$(v()).optional()}).catchall(xe()),outputSchema:T({type:M("object"),properties:he(v(),Oe).optional(),required:$(v()).optional()}).catchall(xe()).optional(),annotations:zb.optional(),execution:Db.optional(),_meta:he(v(),xe()).optional()}),Nb=ai.extend({method:M("tools/list")}),pi=ci.extend({tools:$(Ws)}),_r=qe.extend({content:$(Xc).default([]),structuredContent:he(v(),xe()).optional(),isError:fe().optional()}),Tj=_r.or(qe.extend({toolResult:xe()})),jb=oi.extend({name:v(),arguments:he(v(),xe()).optional()}),qb=je.extend({method:M("tools/call"),params:jb}),fi=vt.extend({method:M("notifications/tools/list_changed"),params:_t.optional()}),Dm=T({autoRefresh:fe().default(!0),debounceMs:ce().int().nonnegative().default(300)}),Nm=at(["debug","info","notice","warning","error","critical","alert","emergency"]),Lb=dt.extend({level:Nm}),Ub=je.extend({method:M("logging/setLevel"),params:Lb}),Vb=_t.extend({level:Nm,logger:v().optional(),data:xe()}),tl=vt.extend({method:M("notifications/message"),params:Vb}),Fb=T({name:v().optional()}),Hb=T({hints:$(Fb).optional(),costPriority:ce().min(0).max(1).optional(),speedPriority:ce().min(0).max(1).optional(),intelligencePriority:ce().min(0).max(1).optional()}),Zb=T({mode:at(["auto","required","none"]).optional()}),Kb=T({type:M("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:$(Xc).default([]),structuredContent:T({}).loose().optional(),isError:fe().optional(),_meta:he(v(),xe()).optional()}),Gb=tc("type",[Bc,Jc,Yc]),Ms=tc("type",[Bc,Jc,Yc,Tb,Kb]),Wb=T({role:ui,content:Se([Ms,$(Ms)]),_meta:he(v(),xe()).optional()}),Bb=oi.extend({messages:$(Wb),modelPreferences:Hb.optional(),systemPrompt:v().optional(),includeContext:at(["none","thisServer","allServers"]).optional(),temperature:ce().optional(),maxTokens:ce().int(),stopSequences:$(v()).optional(),metadata:Oe.optional(),tools:$(Ws).optional(),toolChoice:Zb.optional()}),rl=je.extend({method:M("sampling/createMessage"),params:Bb}),nl=qe.extend({model:v(),stopReason:ke(at(["endTurn","stopSequence","maxTokens"]).or(v())),role:ui,content:Gb}),ol=qe.extend({model:v(),stopReason:ke(at(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:ui,content:Se([Ms,$(Ms)])}),Jb=T({type:M("boolean"),title:v().optional(),description:v().optional(),default:fe().optional()}),Yb=T({type:M("string"),title:v().optional(),description:v().optional(),minLength:ce().optional(),maxLength:ce().optional(),format:at(["email","uri","date","date-time"]).optional(),default:v().optional()}),Xb=T({type:at(["number","integer"]),title:v().optional(),description:v().optional(),minimum:ce().optional(),maximum:ce().optional(),default:ce().optional()}),Qb=T({type:M("string"),title:v().optional(),description:v().optional(),enum:$(v()),default:v().optional()}),ek=T({type:M("string"),title:v().optional(),description:v().optional(),oneOf:$(T({const:v(),title:v()})),default:v().optional()}),tk=T({type:M("string"),title:v().optional(),description:v().optional(),enum:$(v()),enumNames:$(v()).optional(),default:v().optional()}),rk=Se([Qb,ek]),nk=T({type:M("array"),title:v().optional(),description:v().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:T({type:M("string"),enum:$(v())}),default:$(v()).optional()}),ok=T({type:M("array"),title:v().optional(),description:v().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:T({anyOf:$(T({const:v(),title:v()}))}),default:$(v()).optional()}),ik=Se([nk,ok]),sk=Se([tk,rk,ik]),ak=Se([sk,Jb,Yb,Xb]),ck=oi.extend({mode:M("form").optional(),message:v(),requestedSchema:T({type:M("object"),properties:he(v(),ak),required:$(v()).optional()})}),lk=oi.extend({mode:M("url"),message:v(),elicitationId:v(),url:v().url()}),dk=Se([ck,lk]),il=je.extend({method:M("elicitation/create"),params:dk}),uk=_t.extend({elicitationId:v()}),pk=vt.extend({method:M("notifications/elicitation/complete"),params:uk}),sl=qe.extend({action:at(["accept","decline","cancel"]),content:nc(t=>t===null?void 0:t,he(v(),Se([v(),ce(),fe(),$(v())])).optional())}),fk=T({type:M("ref/resource"),uri:v()});var mk=T({type:M("ref/prompt"),name:v()}),hk=dt.extend({ref:Se([mk,fk]),argument:T({name:v(),value:v()}),context:T({arguments:he(v(),v()).optional()}).optional()}),gk=je.extend({method:M("completion/complete"),params:hk});var al=qe.extend({completion:Te({values:$(v()).max(100),total:ke(ce().int()),hasMore:ke(fe())})}),yk=T({uri:v().startsWith("file://"),name:v().optional(),_meta:he(v(),xe()).optional()}),cl=je.extend({method:M("roots/list"),params:dt.optional()}),_k=qe.extend({roots:$(yk)}),vk=vt.extend({method:M("notifications/roots/list_changed"),params:_t.optional()}),Oj=Se([Ls,Im,gk,Ub,$b,Ib,gb,yb,vb,wb,kb,qb,Nb,Vs,Hs,Zs,Gs]),Aj=Se([js,Us,$m,vk,di]),Mj=Se([Ur,nl,ol,sl,_k,Fs,Ks,Vr]),zj=Se([Ls,rl,il,cl,Vs,Hs,Zs,Gs]),Dj=Se([js,Us,tl,xb,Gc,fi,el,di,pk]),Nj=Se([Ur,Uc,al,Qc,Wc,Fc,Hc,Kc,_r,pi,Fs,Ks,Vr]),N=class t extends Error{static{i(this,"McpError")}constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===q.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Nc(o.elicitations,r)}return new t(e,r,n)}},Nc=class extends N{static{i(this,"UrlElicitationRequiredError")}constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(q.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};var Zn={};H(Zn,{ClientInfo:()=>Lm,Entry:()=>Um,McpAuth:()=>Zn,Service:()=>Fr,Tokens:()=>qm,node:()=>Ek,use:()=>bk});import Sk from"path";var qm=f.Struct({accessToken:f.mutableKey(f.String),refreshToken:f.mutableKey(f.optional(f.String)),expiresAt:f.mutableKey(f.optional(f.Number)),scope:f.mutableKey(f.optional(f.String))}),Lm=f.Struct({clientId:f.mutableKey(f.String),clientSecret:f.mutableKey(f.optional(f.String)),clientIdIssuedAt:f.mutableKey(f.optional(f.Number)),clientSecretExpiresAt:f.mutableKey(f.optional(f.Number))}),Um=f.Struct({tokens:f.mutableKey(f.optional(qm)),clientInfo:f.mutableKey(f.optional(Lm)),codeVerifier:f.mutableKey(f.optional(f.String)),oauthState:f.mutableKey(f.optional(f.String)),serverUrl:f.mutableKey(f.optional(f.String))}),wk=f.decodeUnknownOption(f.Record(f.String,Um)),ll=Sk.join(se.Path.globalData,"mcp-auth.json"),jm=`mcp-auth:${ll}`,Fr=class extends te.Service()("@opencode/McpAuth"){static{i(this,"Service")}},bk=ys(Fr),kk=V.effect(Fr,a.gen(function*(){let t=yield*ae.Service,e=yield*mn.Service,r=a.fn("McpAuth.read")(function*(){return yield*t.readJson(ll).pipe(a.map(x=>pt.getOrElse(wk(x),()=>({}))),a.catch(()=>a.succeed({})))}),n=a.fn("McpAuth.all")(function*(){return yield*r().pipe(e.withLock(jm),a.orDie)}),o=a.fn("McpAuth.mutate")(function*(x){yield*a.gen(function*(){let w=x(yield*r());w&&(yield*t.writeJson(ll,w,384).pipe(a.orDie))}).pipe(e.withLock(jm),a.orDie)}),s=a.fn("McpAuth.get")(function*(x){return(yield*n())[x]}),c=a.fn("McpAuth.getForUrl")(function*(x,w){let P=yield*s(x);if(P&&P.serverUrl&&P.serverUrl===w)return P}),l=a.fn("McpAuth.set")(function*(x,w,P){yield*o(I=>({...I,[x]:P?{...w,serverUrl:P}:w}))}),d=a.fn("McpAuth.remove")(function*(x){yield*o(w=>{let P={...w};return delete P[x],P})}),u=i((x,w)=>a.fn(`McpAuth.${w}`)(function*(P,I,L){yield*o(F=>{let Be=F[P]??{};return Be[x]=I,L&&(Be.serverUrl=L),{...F,[P]:Be}})}),"updateField"),p=i((x,w)=>a.fn(`McpAuth.${w}`)(function*(P){yield*o(I=>{let L=I[P];if(L)return delete L[x],{...I,[P]:L}})}),"clearField"),m=u("tokens","updateTokens"),g=u("clientInfo","updateClientInfo"),y=u("codeVerifier","updateCodeVerifier"),h=u("oauthState","updateOAuthState"),_=p("codeVerifier","clearCodeVerifier"),S=p("oauthState","clearOAuthState"),E=a.fn("McpAuth.getOAuthState")(function*(x){return(yield*s(x))?.oauthState});return Fr.of({all:n,get:s,getForUrl:c,set:l,remove:d,updateTokens:m,updateClientInfo:g,updateCodeVerifier:y,clearCodeVerifier:_,updateOAuthState:h,getOAuthState:E,clearOAuthState:S})})),Ek=ft.make({service:Fr,layer:kk,deps:[ae.node,mn.node]});var ut={};H(ut,{McpCatalog:()=>ut,callMeta:()=>Ly,convertTool:()=>qI,defs:()=>jI,fetch:()=>LI,paginate:()=>Zi,prompts:()=>VI,resourceTemplates:()=>HI,resources:()=>FI,sanitize:()=>Hi,toolName:()=>UI});function Kn(t){return!!t._zod}i(Kn,"isZ4Schema");function Rt(t,e){return Kn(t)?Ss(t,e):t.safeParse(e)}i(Rt,"safeParse");function Bs(t){if(!t)return;let e;if(Kn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}i(Bs,"getObjectShape");function Zm(t){if(Kn(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}i(Zm,"getLiteralValue");function vr(t){return t==="completed"||t==="failed"||t==="cancelled"}i(vr,"isTerminal");var $V=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ul(t){let r=Bs(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Zm(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}i(ul,"getMethodLiteral");function pl(t,e){let r=Rt(t,e);if(!r.success)throw r.error;return r.data}i(pl,"parseWithCompat");var Fk=6e4,Js=class{static{i(this,"Protocol")}constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(js,r=>{this._oncancel(r)}),this.setNotificationHandler(Us,r=>{this._onprogress(r)}),this.setRequestHandler(Ls,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Vs,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new N(q.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Hs,async(r,n)=>{let o=i(async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(l.type==="response"||l.type==="error"){let d=l.message,u=d.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),l.type==="response")p(d);else{let m=d,g=new N(m.error.code,m.error.message,m.error.data);p(g)}else{let m=l.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${u}`))}continue}await this._transport?.send(l.message,{relatedRequestId:n.requestId})}}let c=await this._taskStore.getTask(s,n.sessionId);if(!c)throw new N(q.InvalidParams,`Task not found: ${s}`);if(!vr(c.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(vr(c.status)){let l=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...l,_meta:{...l._meta,[gr]:{taskId:s}}}}return await o()},"handleTaskResult");return await o()}),this.setRequestHandler(Zs,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new N(q.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Gs,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new N(q.InvalidParams,`Task not found: ${r.params.taskId}`);if(vr(o.status))throw new N(q.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new N(q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof N?o:new N(q.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),N.fromError(q.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,c)=>{o?.(s,c),Lr(s)||Ns(s)?this._onresponse(s):ii(s)?this._onrequest(s,c):Pm(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=N.fromError(q.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[gr]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:q.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):o?.send(p).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}let c=new AbortController;this._requestHandlerAbortControllers.set(e.id,c);let l=km(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:c.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:i(async p=>{if(c.signal.aborted)return;let m={relatedRequestId:e.id};s&&(m.relatedTask={taskId:s}),await this.notification(p,m)},"sendNotification"),sendRequest:i(async(p,m,g)=>{if(c.signal.aborted)throw new N(q.ConnectionClosed,"Request was cancelled");let y={...g,relatedRequestId:e.id};s&&!y.relatedTask&&(y.relatedTask={taskId:s});let h=y.relatedTask?.taskId??s;return h&&d&&await d.updateTaskStatus(h,"input_required"),await this.request(p,m,y)},"sendRequest"),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:d,taskRequestedTtl:l?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{l&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async p=>{if(c.signal.aborted)return;let m={result:p,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:m,timestamp:Date.now()},o?.sessionId):await o?.send(m)},async p=>{if(c.signal.aborted)return;let m={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:q.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:m,timestamp:Date.now()},o?.sessionId):await o?.send(m)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===c&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let c=this._responseHandlers.get(o),l=this._timeoutInfo.get(o);if(l&&c&&l.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(d){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),c(d);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Lr(e))n(e);else{let c=new N(e.error.code,e.error.message,e.error.data);n(c)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Lr(e)&&e.result&&typeof e.result=="object"){let c=e.result;if(c.task&&typeof c.task=="object"){let l=c.task;typeof l.taskId=="string"&&(s=!0,this._taskProgressTokens.set(l.taskId,r))}}if(s||this._progressHandlers.delete(r),Lr(e))o(e);else{let c=N.fromError(e.error.code,e.error.message,e.error.data);o(c)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(c){yield{type:"error",error:c instanceof N?c:new N(q.InternalError,String(c))}}return}let s;try{let c=await this.request(e,Vr,n);if(c.task)s=c.task.taskId,yield{type:"taskCreated",task:c.task};else throw new N(q.InternalError,"Task creation did not return a task");for(;;){let l=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:l},vr(l.status)){l.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:l.status==="failed"?yield{type:"error",error:new N(q.InternalError,`Task ${s} failed`)}:l.status==="cancelled"&&(yield{type:"error",error:new N(q.InternalError,`Task ${s} was cancelled`)});return}if(l.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let d=l.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,d)),n?.signal?.throwIfAborted()}}catch(c){yield{type:"error",error:c instanceof N?c:new N(q.InternalError,String(c))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:c,task:l,relatedTask:d}=n??{};return new Promise((u,p)=>{let m=i(x=>{p(x)},"earlyReject");if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),l&&this.assertTaskCapability(e.method)}catch(x){m(x);return}n?.signal?.throwIfAborted();let g=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),y.params={...e.params,_meta:{...e.params?._meta||{},progressToken:g}}),l&&(y.params={...y.params,task:l}),d&&(y.params={...y.params,_meta:{...y.params?._meta||{},[gr]:d}});let h=i(x=>{this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(x)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:c}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let w=x instanceof N?x:new N(q.RequestTimeout,String(x));p(w)},"cancel");this._responseHandlers.set(g,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return p(x);try{let w=Rt(r,x.result);w.success?u(w.data):p(w.error)}catch(w){p(w)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let _=n?.timeout??Fk,S=i(()=>h(N.fromError(q.RequestTimeout,"Request timed out",{timeout:_})),"timeoutHandler");this._setupTimeout(g,_,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let E=d?.taskId;if(E){let x=i(w=>{let P=this._responseHandlers.get(g);P?P(w):this._onerror(new Error(`Response handler missing for side-channeled request ${g}`))},"responseResolver");this._requestResolvers.set(g,x),this._enqueueTaskMessage(E,{type:"request",message:y,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(g),p(w)})}else this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:c,isRequestActive:i(()=>this._responseHandlers.has(g),"isRequestActive")}).catch(x=>{this._cleanupTimeout(g),p(x)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Fs,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ks,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Tm,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let l={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[gr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:l,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let l={...e,jsonrpc:"2.0"};r?.relatedTask&&(l={...l,params:{...l.params,_meta:{...l.params?._meta||{},[gr]:r.relatedTask}}}),this._transport?.send(l,r).catch(d=>this._onerror(d))});return}let c={...e,jsonrpc:"2.0"};r?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[gr]:r.relatedTask}}}),await this._transport.send(c,r)}setRequestHandler(e,r){let n=ul(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let c=pl(e,o);return Promise.resolve(r(c,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=ul(e);this._notificationHandlers.set(n,o=>{let s=pl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&ii(o.message)){let s=o.message.id,c=this._requestResolvers.get(s);c?(c(new N(q.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new N(q.InvalidRequest,"Request cancelled"));return}let c=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(c),s(new N(q.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:i(async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},"createTask"),getTask:i(async o=>{let s=await n.getTask(o,r);if(!s)throw new N(q.InvalidParams,"Failed to retrieve task: Task not found");return s},"getTask"),storeTaskResult:i(async(o,s,c)=>{await n.storeTaskResult(o,s,c,r);let l=await n.getTask(o,r);if(l){let d=di.parse({method:"notifications/tasks/status",params:l});await this.notification(d),vr(l.status)&&this._cleanupTaskProgressHandler(o)}},"storeTaskResult"),getTaskResult:i(o=>n.getTaskResult(o,r),"getTaskResult"),updateTaskStatus:i(async(o,s,c)=>{let l=await n.getTask(o,r);if(!l)throw new N(q.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(vr(l.status))throw new N(q.InvalidParams,`Cannot update task "${o}" from terminal status "${l.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,c,r);let d=await n.getTask(o,r);if(d){let u=di.parse({method:"notifications/tasks/status",params:d});await this.notification(u),vr(d.status)&&this._cleanupTaskProgressHandler(o)}},"updateTaskStatus"),listTasks:i(o=>n.listTasks(o,r),"listTasks")}}};function Gm(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}i(Gm,"isPlainObject");function Wm(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let c=r[o];Gm(c)&&Gm(s)?r[o]={...c,...s}:r[o]=s}return r}i(Wm,"mergeCapabilities");var My=Ka(Yd(),1),zy=Ka(Ay(),1);function MI(){let t=new My.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,zy.default)(t),t}i(MI,"createDefaultAjvInstance");var Oa=class{static{i(this,"AjvJsonSchemaValidator")}constructor(e){this._ajv=e??MI()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Aa=class{static{i(this,"ExperimentalClientTasks")}constructor(e){this._client=e}async*callToolStream(e,r=_r,n){let o=this._client,s={...n,task:n?.task??(o.isToolTask(e.name)?{}:void 0)},c=o.requestStream({method:"tools/call",params:e},r,s),l=o.getToolOutputValidator(e.name);for await(let d of c){if(d.type==="result"&&l){let u=d.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new N(q.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let p=l(u.structuredContent);if(!p.valid){yield{type:"error",error:new N(q.InvalidParams,`Structured content does not match the tool's output schema: ${p.errorMessage}`)};return}}catch(p){if(p instanceof N){yield{type:"error",error:p};return}yield{type:"error",error:new N(q.InvalidParams,`Failed to validate structured content: ${p instanceof Error?p.message:String(p)}`)};return}}yield d}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function Dy(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}i(Dy,"assertToolsCallTaskCapability");function Ny(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}i(Ny,"assertClientRequestTaskCapability");function Ma(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let o of Object.keys(n)){let s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Ma(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Ma(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Ma(r,e)}}i(Ma,"applyElicitationDefaults");function zI(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}i(zI,"getSupportedElicitationModes");var za=class extends Js{static{i(this,"Client")}constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Oa,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",fi,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",el,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Gc,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Aa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Wm(this._capabilities,e)}setRequestHandler(e,r){let o=Bs(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Kn(o)){let l=o;s=l._zod?.def?.value??l.value}else{let l=o;s=l._def?.value??l.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");let c=s;if(c==="elicitation/create"){let l=i(async(d,u)=>{let p=Rt(il,d);if(!p.success){let x=p.error instanceof Error?p.error.message:String(p.error);throw new N(q.InvalidParams,`Invalid elicitation request: ${x}`)}let{params:m}=p.data;m.mode=m.mode??"form";let{supportsFormMode:g,supportsUrlMode:y}=zI(this._capabilities.elicitation);if(m.mode==="form"&&!g)throw new N(q.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!y)throw new N(q.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(d,u));if(m.task){let x=Rt(Vr,h);if(!x.success){let w=x.error instanceof Error?x.error.message:String(x.error);throw new N(q.InvalidParams,`Invalid task creation result: ${w}`)}return x.data}let _=Rt(sl,h);if(!_.success){let x=_.error instanceof Error?_.error.message:String(_.error);throw new N(q.InvalidParams,`Invalid elicitation result: ${x}`)}let S=_.data,E=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&S.action==="accept"&&S.content&&E&&this._capabilities.elicitation?.form?.applyDefaults)try{Ma(E,S.content)}catch{}return S},"wrappedHandler");return super.setRequestHandler(e,l)}if(c==="sampling/createMessage"){let l=i(async(d,u)=>{let p=Rt(rl,d);if(!p.success){let S=p.error instanceof Error?p.error.message:String(p.error);throw new N(q.InvalidParams,`Invalid sampling request: ${S}`)}let{params:m}=p.data,g=await Promise.resolve(r(d,u));if(m.task){let S=Rt(Vr,g);if(!S.success){let E=S.error instanceof Error?S.error.message:String(S.error);throw new N(q.InvalidParams,`Invalid task creation result: ${E}`)}return S.data}let h=m.tools||m.toolChoice?ol:nl,_=Rt(h,g);if(!_.success){let S=_.error instanceof Error?_.error.message:String(_.error);throw new N(q.InvalidParams,`Invalid sampling result: ${S}`)}return _.data},"wrappedHandler");return super.setRequestHandler(e,l)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.onsessionexpired=async()=>{await this._initialize(e)},e.sessionId===void 0)try{await this._initialize(e,r)}catch(n){throw this.close(),n}}async _initialize(e,r){let n=await this.request({method:"initialize",params:{protocolVersion:Fn,capabilities:this._capabilities,clientInfo:this._clientInfo}},Uc,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Sm.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){Dy(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&Ny(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Ur,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},al,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Ur,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Qc,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Wc,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Fc,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Hc,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Kc,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Ur,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Ur,r)}async callTool(e,r=_r,n){if(this.isToolTaskRequired(e.name))throw new N(q.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:e},r,n),s=this.getToolOutputValidator(e.name);if(s){if(!o.structuredContent&&!o.isError)throw new N(q.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let c=s(o.structuredContent);if(!c.valid)throw new N(q.InvalidParams,`Structured content does not match the tool's output schema: ${c.errorMessage}`)}catch(c){throw c instanceof N?c:new N(q.InvalidParams,`Failed to validate structured content: ${c instanceof Error?c.message:String(c)}`)}}return o}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e,r=!0){r&&(this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear());for(let n of e){if(n.outputSchema){let s=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,s)}let o=n.execution?.taskSupport;(o==="required"||o==="optional")&&this._cachedKnownTaskTools.add(n.name),o==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},pi,r);return this.cacheToolMetadata(n.tools,e?.cursor===void 0),n}_setupListChangedHandler(e,r,n,o){let s=Dm.safeParse(n);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:c,debounceMs:l}=s.data,{onChanged:d}=n,u=i(async()=>{if(!c){d(null,null);return}try{let m=await o();d(null,m)}catch(m){let g=m instanceof Error?m:new Error(String(m));d(g,null)}},"refresh"),p=i(()=>{if(l){let m=this._listChangedDebounceTimers.get(e);m&&clearTimeout(m);let g=setTimeout(u,l);this._listChangedDebounceTimers.set(e,g)}else u()},"handler");this.setNotificationHandler(r,p)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var jy="alchemylab/fieldTags";function T3(t,e,r,n){if(!r)return{description:t,schema:e};let o=new Set(n),s=structuredClone(e),c=s.properties?.operation?.enum,l=c?.filter(m=>o.has(m))??[],d=!!c&&l.length>0;d&&(s.properties.operation.enum=l);for(let[m,g]of Object.entries(r)){if(g.some(S=>o.has(S)))continue;let y=m.split("."),h=s;for(let S of y.slice(0,-1))h=h?.properties?.[S],h?.type==="array"&&(h=h.items);let _=y[y.length-1];!h?.properties||!(_ in h.properties)||(delete h.properties[_],Array.isArray(h.required)&&(h.required=h.required.filter(S=>S!==_)))}let u=new Set(d?c.filter(m=>!o.has(m)):[]);return{description:t.split(`
872
+ `).filter(m=>{let g=/^\s*(?:•|•)\s+(.+?)\s+-\s/.exec(m);return g?!g[1].split("/").map(h=>h.trim()).every(h=>u.has(h)):!0}).join(`
873
+ `),schema:s}}i(T3,"scopeTool");var DI=3e4,qy=1e3,NI=pi.extend({tools:Ws.omit({outputSchema:!0}).array()});async function Zi(t,e){let r=[],n=new Set,o;for(let s=0;s<qy;s++){let c=await t(o);if(r.push(...e(c)),c.nextCursor===void 0)return r;if(n.has(c.nextCursor))throw new Error(`MCP list returned duplicate cursor: ${c.nextCursor}`);n.add(c.nextCursor),o=c.nextCursor}throw new Error(`MCP list exceeded ${qy} pages`)}i(Zi,"paginate");function jI(t,e){return ZI(t,e??DI).pipe(a.catch(()=>a.void))}i(jI,"defs");function Ly(t){let e=t?.callContext,r={};return e?.sessionId&&(r.sessionId=e.sessionId),e?.messageId&&(r.messageId=e.messageId),Object.keys(r).length>0?r:void 0}i(Ly,"callMeta");function qI(t,e,r){let n={...t.inputSchema,type:"object",properties:t.inputSchema.properties??{},additionalProperties:!1},o=bp({description:t.description??"",inputSchema:wp(n),execute:i(async(c,l)=>{let d={};for(let[g,y]of Object.entries(c||{}))y!==null&&(d[g]=y);let u=await e.callTool({name:t.name,arguments:d,_meta:Ly(l)},_r,{resetTimeoutOnProgress:!0,signal:l.abortSignal,timeout:r,onprogress:i(()=>{},"onprogress")});if(u.isError)throw new Error(u.content.flatMap(g=>g.type==="text"?[g.text]:[]).filter(g=>g.trim()).join(`
874
+
875
+ `)||"MCP tool returned an error");let p=u._meta?.alchemy,m=u.content.length>0||u.structuredContent===void 0||u.structuredContent===null?u:{...u,content:[{type:"text",text:JSON.stringify(u.structuredContent)}]};return p?{...m,metadata:p}:m},"execute")}),s=t._meta?.[jy];return s&&typeof s=="object"&&Object.assign(o,{fieldTags:s,jsonInputSchema:n}),o}i(qI,"convertTool");function LI(t,e,r,n,o){return a.tryPromise({try:i(()=>r(e),"try"),catch:i(s=>s,"catch")}).pipe(a.tapError(s=>a.logWarning(`failed to get ${n}`,{clientName:t,error:s instanceof Error?s.message:String(s)})),a.map(s=>{let c=Hi(t),l=t.replaceAll("%","%25").replaceAll(":","%3A");return Object.fromEntries(s.map(d=>[o?l+":"+o(d):c+":"+Hi(d.name),{...d,client:t}]))}),a.orElseSucceed(()=>{}))}i(LI,"fetch");var Hi=i(t=>t.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitize"),UI=i((t,e)=>Hi(t)+"_"+Hi(e),"toolName");function VI(t,e){return t.getServerCapabilities()?.prompts?Zi(r=>t.listPrompts(r===void 0?void 0:{cursor:r},{timeout:e}),r=>r.prompts):Promise.resolve([])}i(VI,"prompts");function FI(t,e){return t.getServerCapabilities()?.resources?Zi(r=>t.listResources(r===void 0?void 0:{cursor:r},{timeout:e}),r=>r.resources):Promise.resolve([])}i(FI,"resources");function HI(t,e){return t.getServerCapabilities()?.resources?Zi(r=>t.listResourceTemplates(r===void 0?void 0:{cursor:r},{timeout:e}),r=>r.resourceTemplates):Promise.resolve([])}i(HI,"resourceTemplates");function ZI(t,e){return a.tryPromise({try:i(()=>Zi(async r=>{let n=r===void 0?void 0:{cursor:r};try{return await t.listTools(n,{timeout:e})}catch(o){if(!(o instanceof Error)||!KI(o))throw o;return t.request({method:"tools/list",params:n},NI,{timeout:e})}},r=>r.tools),"try"),catch:i(r=>r instanceof Error?r:new Error(String(r)),"catch")})}i(ZI,"listTools");function KI(t){return/can't resolve reference|resolves to more than one schema|outputSchema|schema.*reference|reference.*schema/i.test(t.message)}i(KI,"isOutputSchemaValidationError");var Ru={};H(Ru,{BrowserOpenFailed:()=>k_,Failed:()=>WC,MCP:()=>Ru,NotFoundError:()=>Za,Resource:()=>KC,Service:()=>dn,Status:()=>e$,ToolManifestEntry:()=>GC,ToolsChanged:()=>Pu,node:()=>n$,use:()=>t$});import FC from"node:path";import{pathToFileURL as HC}from"node:url";function uo(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}i(uo,"normalizeHeaders");function Da(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...uo(e.headers),...uo(n.headers)}:e.headers};return t(r,o)}:t}i(Da,"createFetchWithInit");var iu;iu=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function GI(t){return(await iu).getRandomValues(new Uint8Array(t))}i(GI,"getRandomValues");async function WI(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await GI(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}i(WI,"random");async function BI(t){return await WI(t)}i(BI,"generateVerifier");async function JI(t){let e=await(await iu).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}i(JI,"generateChallenge");async function su(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await BI(t),r=await JI(e);return{code_verifier:e,code_challenge:r}}i(su,"pkceChallenge");var Fe=lp().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:fp.custom,message:"URL must be parseable",fatal:!0}),ec}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Vy=Te({resource:v().url(),authorization_servers:$(Fe).optional(),jwks_uri:v().url().optional(),scopes_supported:$(v()).optional(),bearer_methods_supported:$(v()).optional(),resource_signing_alg_values_supported:$(v()).optional(),resource_name:v().optional(),resource_documentation:v().optional(),resource_policy_uri:v().url().optional(),resource_tos_uri:v().url().optional(),tls_client_certificate_bound_access_tokens:fe().optional(),authorization_details_types_supported:$(v()).optional(),dpop_signing_alg_values_supported:$(v()).optional(),dpop_bound_access_tokens_required:fe().optional()}),au=Te({issuer:v(),authorization_endpoint:Fe,token_endpoint:Fe,registration_endpoint:Fe.optional(),scopes_supported:$(v()).optional(),response_types_supported:$(v()),response_modes_supported:$(v()).optional(),grant_types_supported:$(v()).optional(),token_endpoint_auth_methods_supported:$(v()).optional(),token_endpoint_auth_signing_alg_values_supported:$(v()).optional(),service_documentation:Fe.optional(),revocation_endpoint:Fe.optional(),revocation_endpoint_auth_methods_supported:$(v()).optional(),revocation_endpoint_auth_signing_alg_values_supported:$(v()).optional(),introspection_endpoint:v().optional(),introspection_endpoint_auth_methods_supported:$(v()).optional(),introspection_endpoint_auth_signing_alg_values_supported:$(v()).optional(),code_challenge_methods_supported:$(v()).optional(),client_id_metadata_document_supported:fe().optional()}),YI=Te({issuer:v(),authorization_endpoint:Fe,token_endpoint:Fe,userinfo_endpoint:Fe.optional(),jwks_uri:Fe,registration_endpoint:Fe.optional(),scopes_supported:$(v()).optional(),response_types_supported:$(v()),response_modes_supported:$(v()).optional(),grant_types_supported:$(v()).optional(),acr_values_supported:$(v()).optional(),subject_types_supported:$(v()),id_token_signing_alg_values_supported:$(v()),id_token_encryption_alg_values_supported:$(v()).optional(),id_token_encryption_enc_values_supported:$(v()).optional(),userinfo_signing_alg_values_supported:$(v()).optional(),userinfo_encryption_alg_values_supported:$(v()).optional(),userinfo_encryption_enc_values_supported:$(v()).optional(),request_object_signing_alg_values_supported:$(v()).optional(),request_object_encryption_alg_values_supported:$(v()).optional(),request_object_encryption_enc_values_supported:$(v()).optional(),token_endpoint_auth_methods_supported:$(v()).optional(),token_endpoint_auth_signing_alg_values_supported:$(v()).optional(),display_values_supported:$(v()).optional(),claim_types_supported:$(v()).optional(),claims_supported:$(v()).optional(),service_documentation:v().optional(),claims_locales_supported:$(v()).optional(),ui_locales_supported:$(v()).optional(),claims_parameter_supported:fe().optional(),request_parameter_supported:fe().optional(),request_uri_parameter_supported:fe().optional(),require_request_uri_registration:fe().optional(),op_policy_uri:Fe.optional(),op_tos_uri:Fe.optional(),client_id_metadata_document_supported:fe().optional()}),Fy=T({...YI.shape,...au.pick({code_challenge_methods_supported:!0}).shape}),Hy=T({access_token:v(),id_token:v().optional(),token_type:v(),expires_in:mp.number().optional(),scope:v().optional(),refresh_token:v().optional()}).strip(),Zy=T({error:v(),error_description:v().optional(),error_uri:v().optional()}),Uy=Fe.optional().or(M("").transform(()=>{})),XI=T({redirect_uris:$(Fe),token_endpoint_auth_method:v().optional(),grant_types:$(v()).optional(),response_types:$(v()).optional(),client_name:v().optional(),client_uri:Fe.optional(),logo_uri:Uy,scope:v().optional(),contacts:$(v()).optional(),tos_uri:Uy,policy_uri:v().optional(),jwks_uri:Fe.optional(),jwks:up().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional()}).strip(),QI=T({client_id:v(),client_secret:v().optional(),client_id_issued_at:ce().optional(),client_secret_expires_at:ce().optional()}).strip(),Ky=XI.merge(QI),Z3=T({error:v(),error_description:v().optional()}).strip(),K3=T({token:v(),token_type_hint:v().optional()}).strip();function Gy(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}i(Gy,"resourceUrlFromServerUrl");function Wy({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}i(Wy,"checkResourceAllowed");var Re=class extends Error{static{i(this,"OAuthError")}constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Ki=class extends Re{static{i(this,"InvalidRequestError")}};Ki.errorCode="invalid_request";var en=class extends Re{static{i(this,"InvalidClientError")}};en.errorCode="invalid_client";var tn=class extends Re{static{i(this,"InvalidGrantError")}};tn.errorCode="invalid_grant";var rn=class extends Re{static{i(this,"UnauthorizedClientError")}};rn.errorCode="unauthorized_client";var Gi=class extends Re{static{i(this,"UnsupportedGrantTypeError")}};Gi.errorCode="unsupported_grant_type";var Wi=class extends Re{static{i(this,"InvalidScopeError")}};Wi.errorCode="invalid_scope";var Bi=class extends Re{static{i(this,"AccessDeniedError")}};Bi.errorCode="access_denied";var ar=class extends Re{static{i(this,"ServerError")}};ar.errorCode="server_error";var Ji=class extends Re{static{i(this,"TemporarilyUnavailableError")}};Ji.errorCode="temporarily_unavailable";var Yi=class extends Re{static{i(this,"UnsupportedResponseTypeError")}};Yi.errorCode="unsupported_response_type";var Xi=class extends Re{static{i(this,"UnsupportedTokenTypeError")}};Xi.errorCode="unsupported_token_type";var Qi=class extends Re{static{i(this,"InvalidTokenError")}};Qi.errorCode="invalid_token";var es=class extends Re{static{i(this,"MethodNotAllowedError")}};es.errorCode="method_not_allowed";var ts=class extends Re{static{i(this,"TooManyRequestsError")}};ts.errorCode="too_many_requests";var nn=class extends Re{static{i(this,"InvalidClientMetadataError")}};nn.errorCode="invalid_client_metadata";var rs=class extends Re{static{i(this,"InsufficientScopeError")}};rs.errorCode="insufficient_scope";var ns=class extends Re{static{i(this,"InvalidTargetError")}};ns.errorCode="invalid_target";var By={[Ki.errorCode]:Ki,[en.errorCode]:en,[tn.errorCode]:tn,[rn.errorCode]:rn,[Gi.errorCode]:Gi,[Wi.errorCode]:Wi,[Bi.errorCode]:Bi,[ar.errorCode]:ar,[Ji.errorCode]:Ji,[Yi.errorCode]:Yi,[Xi.errorCode]:Xi,[Qi.errorCode]:Qi,[es.errorCode]:es,[ts.errorCode]:ts,[nn.errorCode]:nn,[rs.errorCode]:rs,[ns.errorCode]:ns};var ze=class extends Error{static{i(this,"UnauthorizedError")}constructor(e){super(e??"Unauthorized")}};function eC(t){return["client_secret_basic","client_secret_post","none"].includes(t)}i(eC,"isClientAuthMethod");var cu="code",lu="S256";function tC(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&eC(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}i(tC,"selectClientAuthMethod");function rC(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":nC(o,s,r);return;case"client_secret_post":oC(o,s,n);return;case"none":iC(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}i(rC,"applyClientAuthentication");function nC(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}i(nC,"applyBasicAuth");function oC(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}i(oC,"applyPostAuth");function iC(t,e){e.set("client_id",t)}i(iC,"applyPublicAuth");async function Yy(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=Zy.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:c}=n,l=By[o]||ar;return new l(s||"",c)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ar(o)}}i(Yy,"parseErrorResponse");async function cr(t,e){try{return await du(t,e)}catch(r){if(r instanceof en||r instanceof rn)return await t.invalidateCredentials?.("all"),await du(t,e);if(r instanceof tn)return await t.invalidateCredentials?.("tokens"),await du(t,e);throw r}}i(cr,"auth");function sC({requestedScope:t,resourceMetadata:e,authServerMetadata:r,clientMetadata:n}){let o=t||e?.scopes_supported?.join(" ")||n.scope;return o&&r?.scopes_supported?.includes("offline_access")&&!o.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token")&&(o=`${o} offline_access`),o}i(sC,"determineScope");async function du(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let c=await t.discoveryState?.(),l,d,u,p=o;if(!p&&c?.resourceMetadataUrl&&(p=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(d=c.authorizationServerUrl,l=c.resourceMetadata,u=c.authorizationServerMetadata??await Qy(d,{fetchFn:s}),!l)try{l=await Xy(e,{resourceMetadataUrl:p},s)}catch{}(u!==c.authorizationServerMetadata||l!==c.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:p?.toString(),resourceMetadata:l,authorizationServerMetadata:u})}else{let w=await fC(e,{resourceMetadataUrl:p,fetchFn:s});d=w.authorizationServerUrl,u=w.authorizationServerMetadata,l=w.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:p?.toString(),resourceMetadata:l,authorizationServerMetadata:u})}let m=await cC(e,t,l),g=sC({requestedScope:n,resourceMetadata:l,authServerMetadata:u,clientMetadata:t.clientMetadata}),y=await Promise.resolve(t.clientInformation());if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let w=u?.client_id_metadata_document_supported===!0,P=t.clientMetadataUrl;if(P&&!aC(P))throw new nn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${P}`);if(w&&P)y={client_id:P},await t.saveClientInformation?.(y);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let L=await _C(d,{metadata:u,clientMetadata:t.clientMetadata,scope:g,fetchFn:s});await t.saveClientInformation(L),y=L}}let h=!t.redirectUrl;if(r!==void 0||h){let w=await yC(t,d,{metadata:u,resource:m,authorizationCode:r,fetchFn:s});return await t.saveTokens(w),"AUTHORIZED"}let _=await t.tokens();if(_?.refresh_token)try{let w=await gC(d,{metadata:u,clientInformation:y,refreshToken:_.refresh_token,resource:m,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Re)||w instanceof ar))throw w}let S=t.state?await t.state():void 0,{authorizationUrl:E,codeVerifier:x}=await mC(d,{metadata:u,clientInformation:y,state:S,redirectUrl:t.redirectUrl,scope:g,resource:m});return await t.saveCodeVerifier(x),await t.redirectToAuthorization(E),"REDIRECT"}i(du,"authInternal");function aC(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}i(aC,"isHttpsUrl");async function cC(t,e,r){let n=Gy(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!Wy({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}i(cC,"selectResourceURL");function po(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=uu(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let c=uu(t,"scope")||void 0,l=uu(t,"error")||void 0;return{resourceMetadataUrl:s,scope:c,error:l}}i(po,"extractWWWAuthenticateParams");function uu(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}i(uu,"extractFieldFromWwwAuth");async function Xy(t,e,r=fetch){let n=await uC(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Vy.parse(await n.json())}i(Xy,"discoverOAuthProtectedResourceMetadata");async function pu(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?pu(t,void 0,r):void 0;throw n}}i(pu,"fetchWithCorsRetry");function lC(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}i(lC,"buildWellKnownPath");async function Jy(t,e,r=fetch){return await pu(t,{"MCP-Protocol-Version":e},r)}i(Jy,"tryMetadataDiscovery");function dC(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}i(dC,"shouldAttemptFallback");async function uC(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??Fn,c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{let d=lC(e,o.pathname);c=new URL(d,n?.metadataServerUrl??o),c.search=o.search}let l=await Jy(c,s,r);if(!n?.metadataUrl&&dC(l,o.pathname)){let d=new URL(`/.well-known/${e}`,o);l=await Jy(d,s,r)}return l}i(uC,"discoverMetadataWithFallback");function pC(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let o=e.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,e.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}i(pC,"buildDiscoveryUrls");async function Qy(t,{fetchFn:e=fetch,protocolVersion:r=Fn}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=pC(t);for(let{url:s,type:c}of o){let l=await pu(s,n,e);if(l){if(!l.ok){if(await l.body?.cancel(),l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return c==="oauth"?au.parse(await l.json()):Fy.parse(await l.json())}}}i(Qy,"discoverAuthorizationServerMetadata");async function fC(t,e){let r,n;try{r=await Xy(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",t)));let o=await Qy(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}i(fC,"discoverOAuthServerInfo");async function mC(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:c}){let l;if(e){if(l=new URL(e.authorization_endpoint),!e.response_types_supported.includes(cu))throw new Error(`Incompatible auth server: does not support response type ${cu}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(lu))throw new Error(`Incompatible auth server: does not support code challenge method ${lu}`)}else l=new URL("/authorize",t);let d=await su(),u=d.code_verifier,p=d.code_challenge;return l.searchParams.set("response_type",cu),l.searchParams.set("client_id",r.client_id),l.searchParams.set("code_challenge",p),l.searchParams.set("code_challenge_method",lu),l.searchParams.set("redirect_uri",String(n)),s&&l.searchParams.set("state",s),o&&l.searchParams.set("scope",o),o?.split(" ").includes("offline_access")&&l.searchParams.append("prompt","consent"),c&&l.searchParams.set("resource",c.href),{authorizationUrl:l,codeVerifier:u}}i(mC,"startAuthorization");function hC(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}i(hC,"prepareAuthorizationCodeRequest");async function e_(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:c}){let l=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(d,r,l,e);else if(n){let p=e?.token_endpoint_auth_methods_supported??[],m=tC(n,p);rC(m,n,d,r)}let u=await(c??fetch)(l,{method:"POST",headers:d,body:r});if(!u.ok)throw await Yy(u);return Hy.parse(await u.json())}i(e_,"executeTokenRequest");async function gC(t,{metadata:e,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:c}){let l=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),d=await e_(t,{metadata:e,tokenRequestParams:l,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:c});return{refresh_token:n,...d}}i(gC,"refreshAuthorization");async function yC(t,e,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){let c=t.clientMetadata.scope,l;if(t.prepareTokenRequest&&(l=await t.prepareTokenRequest(c)),!l){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let u=await t.codeVerifier();l=hC(o,u,t.redirectUrl)}let d=await t.clientInformation();return e_(e,{metadata:r,tokenRequestParams:l,clientInformation:d??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}i(yC,"fetchToken");async function _C(t,{metadata:e,clientMetadata:r,scope:n,fetchFn:o}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);let c=await(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!c.ok)throw await Yy(c);return Ky.parse(await c.json())}i(_C,"registerClient");var vC={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ir=class extends Error{static{i(this,"StreamableHTTPError")}constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},os=class{static{i(this,"StreamableHTTPClientTransport")}constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Da(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??vC}async _authThenStart(){if(!this._authProvider)throw new ze("No auth provider");let e;try{e=await cr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new ze;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=uo(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Ir(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),o)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r,c,l=!1,d=!1;i(async()=>{try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new gp({onRetry:i(y=>{this._serverRetryMs=y},"onRetry")})).getReader();for(;;){let{value:y,done:h}=await p.read();if(h)break;if(y.id&&(c=y.id,l=!0,o?.(y.id)),!!y.data&&(!y.event||y.event==="message"))try{let _=yr.parse(JSON.parse(y.data));(Lr(_)||Ns(_))&&(d=!0,s!==void 0&&(_.id=s)),this.onmessage?.(_)}catch(_){this.onerror?.(_)}}(n||l)&&!d&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:c,onresumptiontoken:o,replayMessageId:s},0)}catch(p){if(this.onerror?.(new Error(`SSE stream disconnected: ${p}`)),(n||l)&&!d&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:c,onresumptiontoken:o,replayMessageId:s},0)}catch(y){this.onerror?.(new Error(`Failed to reconnect: ${y instanceof Error?y.message:String(y)}`))}}},"processStream")()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new ze("No auth provider");if(await cr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ze("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){return this._send(e,r,!1)}async _recoverSession(e){if(this._sessionRecovery)return await this._sessionRecovery,!0;if(this._sessionId!==e)return!0;this._sessionId=void 0,this._sessionRecovery=Promise.resolve().then(()=>this.onsessionexpired?.());try{await this._sessionRecovery}catch(r){throw this._sessionId=void 0,await this.close(),r}finally{this._sessionRecovery=void 0}return!0}async _send(e,r,n){try{if(this._sessionRecovery&&!Cm(e)&&!qs(e)&&(await this._sessionRecovery,r?.isRequestActive?.()===!1))throw new Error("Request is no longer active");let{resumptionToken:o,onresumptiontoken:s}=r||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:ii(e)?e.id:void 0}).catch(h=>this.onerror?.(h));return}let c=await this._commonHeaders(),l=c.get("mcp-session-id")??void 0;c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:this._abortController?.signal},u=await(this._fetch??fetch)(this._url,d),p=u.headers.get("mcp-session-id");if(p&&(l===void 0||this._sessionId===l)&&(this._sessionId=p),!u.ok){let h=await u.text().catch(()=>null);if(u.status===404&&l&&!n&&!qs(e)){let _=await this._recoverSession(l);if(r?.isRequestActive?.()===!1)throw new Error("Request is no longer active");if(_)return this._send(e,r,!0)}if(u.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ir(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:_,scope:S}=po(u);if(this._resourceMetadataUrl=_,this._scope=S,await cr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ze;return this._hasCompletedAuthFlow=!0,this._send(e,r,n)}if(u.status===403&&this._authProvider){let{resourceMetadataUrl:_,scope:S,error:E}=po(u);if(E==="insufficient_scope"){let x=u.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===x)throw new Ir(403,"Server returned 403 after trying upscoping");if(S&&(this._scope=S),_&&(this._resourceMetadataUrl=_),this._lastUpscopingHeader=x??void 0,await cr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ze;return this._send(e,r,n)}}throw new Ir(u.status,`Error POSTing to endpoint: ${h}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,u.status===202){await u.body?.cancel(),qs(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(h=>this.onerror?.(h));return}let g=(Array.isArray(e)?e:[e]).filter(h=>"method"in h&&"id"in h&&h.id!==void 0).length>0,y=u.headers.get("content-type");if(g)if(y?.includes("text/event-stream"))this._handleSseStream(u.body,{onresumptiontoken:s},!1);else if(y?.includes("application/json")){let h=await u.json(),_=Array.isArray(h)?h.map(S=>yr.parse(S)):[yr.parse(h)];for(let S of _)this.onmessage?.(S)}else throw await u.body?.cancel(),new Ir(-1,`Unexpected content type: ${y}`);else await u.body?.cancel()}catch(o){throw this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Ir(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var ja=class extends Event{static{i(this,"ErrorEvent")}constructor(e,r){var n,o;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(t_(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(t_(this),r)}};function SC(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}i(SC,"syntaxError");function fu(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(fu).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${fu(t.cause)}`:t.message:`${t}`}i(fu,"flattenError");function t_(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}i(t_,"inspectableError");var n_=i(t=>{throw TypeError(t)},"__typeError"),wu=i((t,e,r)=>e.has(t)||n_("Cannot "+r),"__accessCheck"),ee=i((t,e,r)=>(wu(t,e,"read from private field"),r?r.call(t):e.get(t)),"__privateGet"),Ae=i((t,e,r)=>e.has(t)?n_("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),"__privateAdd"),we=i((t,e,r,n)=>(wu(t,e,"write to private field"),e.set(t,r),r),"__privateSet"),lr=i((t,e,r)=>(wu(t,e,"access private method"),r),"__privateMethod"),it,on,fo,Na,qa,as,go,cs,Cr,mo,yo,ho,is,At,mu,hu,gu,r_,yu,_u,ss,vu,Su,sn=class extends EventTarget{static{i(this,"EventSource")}constructor(e,r){var n,o;super(),Ae(this,At),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ae(this,it),Ae(this,on),Ae(this,fo),Ae(this,Na),Ae(this,qa),Ae(this,as),Ae(this,go),Ae(this,cs,null),Ae(this,Cr),Ae(this,mo),Ae(this,yo,null),Ae(this,ho,null),Ae(this,is,null),Ae(this,hu,async s=>{var c;ee(this,mo).reset();let{body:l,redirected:d,status:u,headers:p}=s;if(u===204){lr(this,At,ss).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(d?we(this,fo,new URL(s.url)):we(this,fo,void 0),u!==200){lr(this,At,ss).call(this,`Non-200 status code (${u})`,u);return}if(!(p.get("content-type")||"").startsWith("text/event-stream")){lr(this,At,ss).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(ee(this,it)===this.CLOSED)return;we(this,it,this.OPEN);let m=new Event("open");if((c=ee(this,is))==null||c.call(this,m),this.dispatchEvent(m),typeof l!="object"||!l||!("getReader"in l)){lr(this,At,ss).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let g=new TextDecoder,y=l.getReader(),h=!0;do{let{done:_,value:S}=await y.read();S&&ee(this,mo).feed(g.decode(S,{stream:!_})),_&&(h=!1,ee(this,mo).reset(),lr(this,At,vu).call(this))}while(h)}),Ae(this,gu,s=>{we(this,Cr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&lr(this,At,vu).call(this,fu(s))}),Ae(this,yu,s=>{typeof s.id=="string"&&we(this,cs,s.id);let c=new MessageEvent(s.event||"message",{data:s.data,origin:ee(this,fo)?ee(this,fo).origin:ee(this,on).origin,lastEventId:s.id||""});ee(this,ho)&&(!s.event||s.event==="message")&&ee(this,ho).call(this,c),this.dispatchEvent(c)}),Ae(this,_u,s=>{we(this,as,s)}),Ae(this,Su,()=>{we(this,go,void 0),ee(this,it)===this.CONNECTING&&lr(this,At,mu).call(this)});try{if(e instanceof URL)we(this,on,e);else if(typeof e=="string")we(this,on,new URL(e,wC()));else throw new Error("Invalid URL")}catch{throw SC("An invalid or illegal string was specified")}we(this,mo,hp({onEvent:ee(this,yu),onRetry:ee(this,_u)})),we(this,it,this.CONNECTING),we(this,as,3e3),we(this,qa,(n=r?.fetch)!=null?n:globalThis.fetch),we(this,Na,(o=r?.withCredentials)!=null?o:!1),lr(this,At,mu).call(this)}get readyState(){return ee(this,it)}get url(){return ee(this,on).href}get withCredentials(){return ee(this,Na)}get onerror(){return ee(this,yo)}set onerror(e){we(this,yo,e)}get onmessage(){return ee(this,ho)}set onmessage(e){we(this,ho,e)}get onopen(){return ee(this,is)}set onopen(e){we(this,is,e)}addEventListener(e,r,n){let o=r;super.addEventListener(e,o,n)}removeEventListener(e,r,n){let o=r;super.removeEventListener(e,o,n)}close(){ee(this,go)&&clearTimeout(ee(this,go)),ee(this,it)!==this.CLOSED&&(ee(this,Cr)&&ee(this,Cr).abort(),we(this,it,this.CLOSED),we(this,Cr,void 0))}};it=new WeakMap,on=new WeakMap,fo=new WeakMap,Na=new WeakMap,qa=new WeakMap,as=new WeakMap,go=new WeakMap,cs=new WeakMap,Cr=new WeakMap,mo=new WeakMap,yo=new WeakMap,ho=new WeakMap,is=new WeakMap,At=new WeakSet,mu=i(function(){we(this,it,this.CONNECTING),we(this,Cr,new AbortController),ee(this,qa)(ee(this,on),lr(this,At,r_).call(this)).then(ee(this,hu)).catch(ee(this,gu))},"connect_fn"),hu=new WeakMap,gu=new WeakMap,r_=i(function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...ee(this,cs)?{"Last-Event-ID":ee(this,cs)}:void 0},cache:"no-store",signal:(t=ee(this,Cr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},"getRequestOptions_fn"),yu=new WeakMap,_u=new WeakMap,ss=i(function(t,e){var r;ee(this,it)!==this.CLOSED&&we(this,it,this.CLOSED);let n=new ja("error",{code:e,message:t});(r=ee(this,yo))==null||r.call(this,n),this.dispatchEvent(n)},"failConnection_fn"),vu=i(function(t,e){var r;if(ee(this,it)===this.CLOSED)return;we(this,it,this.CONNECTING);let n=new ja("error",{code:e,message:t});(r=ee(this,yo))==null||r.call(this,n),this.dispatchEvent(n),we(this,go,setTimeout(ee(this,Su),ee(this,as)))},"scheduleReconnect_fn"),Su=new WeakMap,sn.CONNECTING=0,sn.OPEN=1,sn.CLOSED=2;function wC(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}i(wC,"getBaseURL");var bu=class extends Error{static{i(this,"SseError")}constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},La=class{static{i(this,"SSEClientTransport")}constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Da(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new ze("No auth provider");let e;try{e=await cr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new ze;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=uo(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new sn(this._url.href,{...this._eventSourceInit,fetch:i(async(o,s)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let l=await e(o,{...s,headers:c});if(l.status===401&&l.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:u}=po(l);this._resourceMetadataUrl=d,this._scope=u}return l},"fetch")}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}let s=new bu(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(c){n(c),this.onerror?.(c),this.close();return}r()}),this._eventSource.onmessage=o=>{let s=o,c;try{c=yr.parse(JSON.parse(s.data))}catch(l){this.onerror?.(l);return}this.onmessage?.(c)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new ze("No auth provider");if(await cr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ze("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){let s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:c,scope:l}=po(o);if(this._resourceMetadataUrl=c,this._scope=l,await cr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ze;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var i_=Ka(O_(),1);import ku from"node:process";import{PassThrough as kC}from"node:stream";var Ua=class{static{i(this,"ReadBuffer")}append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
876
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),bC(r)}clear(){this._buffer=void 0}};function bC(t){return yr.parse(JSON.parse(t))}i(bC,"deserializeMessage");function o_(t){return JSON.stringify(t)+`
877
+ `}i(o_,"serializeMessage");var EC=ku.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function xC(){let t={};for(let e of EC){let r=ku.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}i(xC,"getDefaultEnvironment");var ls=class{static{i(this,"StdioClientTransport")}constructor(e){this._readBuffer=new Ua,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new kC)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,i_.default)(this._serverParams.command,this._serverParams.args??[],{env:{...xC(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:ku.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=o_(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function s_(t,e,r){let n;return Promise.race([t.finally(()=>{clearTimeout(n)}),new Promise((o,s)=>{n=setTimeout(()=>{s(new Error(r??`Operation timed out after ${e}ms`))},e)})])}i(s_,"withTimeout");var _o=19876,$r="/mcp/oauth/callback",ds=class{constructor(e,r,n,o,s){this.mcpName=e;this.serverUrl=r;this.config=n;this.callbacks=o;this.auth=s}mcpName;serverUrl;config;callbacks;auth;static{i(this,"McpOAuthProvider")}get redirectUrl(){return this.config.redirectUri?this.config.redirectUri:`http://127.0.0.1:${this.config.callbackPort??_o}${$r}`}get clientMetadata(){return{redirect_uris:[this.redirectUrl],client_name:"OpenCode",client_uri:"https://opencode.ai",grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:this.config.clientSecret?"client_secret_post":"none",...this.config.scope?{scope:this.config.scope}:{}}}async clientInformation(){if(this.config.clientId)return{client_id:this.config.clientId,client_secret:this.config.clientSecret};let e=await a.runPromise(this.auth.getForUrl(this.mcpName,this.serverUrl));if(e?.clientInfo)return e.clientInfo.clientSecretExpiresAt&&e.clientInfo.clientSecretExpiresAt<Date.now()/1e3?void 0:{client_id:e.clientInfo.clientId,client_secret:e.clientInfo.clientSecret}}async saveClientInformation(e){await a.runPromise(this.auth.updateClientInfo(this.mcpName,{clientId:e.client_id,clientSecret:e.client_secret,clientIdIssuedAt:e.client_id_issued_at,clientSecretExpiresAt:e.client_secret_expires_at},this.serverUrl))}async tokens(){let e=await a.runPromise(this.auth.getForUrl(this.mcpName,this.serverUrl));if(e?.tokens)return{access_token:e.tokens.accessToken,token_type:"Bearer",refresh_token:e.tokens.refreshToken,expires_in:e.tokens.expiresAt?Math.max(0,Math.floor(e.tokens.expiresAt-Date.now()/1e3)):void 0,scope:e.tokens.scope}}async saveTokens(e){await a.runPromise(this.auth.updateTokens(this.mcpName,{accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:e.expires_in?Date.now()/1e3+e.expires_in:void 0,scope:e.scope},this.serverUrl))}async redirectToAuthorization(e){if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`MCP server "${this.serverUrl}" returned a ${e.protocol} authorization URL; only http and https are supported`);await this.callbacks.onRedirect(e)}async saveCodeVerifier(e){await a.runPromise(this.auth.updateCodeVerifier(this.mcpName,e))}async codeVerifier(){let e=await a.runPromise(this.auth.get(this.mcpName));if(!e?.codeVerifier)throw new Error(`No code verifier saved for MCP server: ${this.mcpName}`);return e.codeVerifier}async saveState(e){await a.runPromise(this.auth.updateOAuthState(this.mcpName,e))}async state(){let e=await a.runPromise(this.auth.get(this.mcpName));if(e?.oauthState)return e.oauthState;let r=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(n=>n.toString(16).padStart(2,"0")).join("");return await a.runPromise(this.auth.updateOAuthState(this.mcpName,r)),r}async invalidateCredentials(e){let r=await a.runPromise(this.auth.get(this.mcpName));if(r)switch(e){case"all":await a.runPromise(this.auth.remove(this.mcpName));break;case"client":delete r.clientInfo,await a.runPromise(this.auth.set(this.mcpName,r));break;case"tokens":delete r.tokens,await a.runPromise(this.auth.set(this.mcpName,r));break}}},Va=class extends ds{static{i(this,"McpOAuthPendingProvider")}pendingClientInfo;pendingTokens;async clientInformation(){return this.config.clientId?{client_id:this.config.clientId,client_secret:this.config.clientSecret}:this.pendingClientInfo}async saveClientInformation(e){this.pendingClientInfo=e}async tokens(){return this.pendingTokens}async saveTokens(e){this.pendingTokens=e}async invalidateCredentials(e){(e==="all"||e==="client")&&(this.pendingClientInfo=void 0),(e==="all"||e==="tokens")&&(this.pendingTokens=void 0)}async commit(){this.pendingTokens&&await a.runPromise(this.auth.set(this.mcpName,{tokens:{accessToken:this.pendingTokens.access_token,refreshToken:this.pendingTokens.refresh_token,expiresAt:this.pendingTokens.expires_in?Date.now()/1e3+this.pendingTokens.expires_in:void 0,scope:this.pendingTokens.scope},clientInfo:this.pendingClientInfo&&!this.config.clientId?{clientId:this.pendingClientInfo.client_id,clientSecret:this.pendingClientInfo.client_secret,clientIdIssuedAt:this.pendingClientInfo.client_id_issued_at,clientSecretExpiresAt:this.pendingClientInfo.client_secret_expires_at}:void 0},this.serverUrl))}};function a_(t){if(!t)return{port:_o,path:$r};try{let e=new URL(t),r=e.port?parseInt(e.port,10):e.protocol==="https:"?443:80,n=e.pathname||$r;return{port:r,path:n}}catch{return{port:_o,path:$r}}}i(a_,"parseRedirectUri");var cn={};H(cn,{McpOAuthCallback:()=>cn,cancelPending:()=>AC,ensureRunning:()=>TC,isPortInUse:()=>l_,isRunning:()=>MC,stop:()=>d_,waitForCallback:()=>OC});import{createConnection as PC}from"net";import{createServer as RC}from"http";var IC="127.0.0.1",Fa=_o,Eu=$r,Et,st=new Map,an=new Map,CC=300*1e3;function c_(t){for(let[e,r]of an)if(r===t){an.delete(e);break}}i(c_,"cleanupStateIndex");function Ha(){st.size>0||!Et||(Et.close(),Et=void 0)}i(Ha,"stopIfIdle");function $C(t,e){let r=new URL(t.url||"/",`http://localhost:${Fa}`);if(r.pathname!==Eu){e.writeHead(404),e.end("Not found");return}let n=r.searchParams.get("code"),o=r.searchParams.get("state"),s=r.searchParams.get("error"),c=r.searchParams.get("error_description");if(!o){let d="Missing required state parameter - potential CSRF attack";e.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),e.end(lt.error(d,{provider:"MCP"}));return}if(s){let d=c||s;if(st.has(o)){let u=st.get(o);clearTimeout(u.timeout),st.delete(o),c_(o),u.reject(new Error(d))}e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(lt.error(d,{provider:"MCP"})),Ha();return}if(!n){e.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),e.end(lt.error("No authorization code provided",{provider:"MCP"}));return}if(!st.has(o)){let d="Invalid or expired state parameter - potential CSRF attack";e.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),e.end(lt.error(d,{provider:"MCP"}));return}let l=st.get(o);clearTimeout(l.timeout),st.delete(o),c_(o),l.resolve(n),e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(lt.success({provider:"MCP"})),Ha()}i($C,"handleRequest");async function TC(t){let{port:e,path:r}=a_(t);Et&&(Fa!==e||Eu!==r)&&await d_(),!(Et||await l_(e))&&(Fa=e,Eu=r,Et=RC($C),await new Promise((o,s)=>{Et.listen(Fa,IC,()=>{o()}),Et.on("error",s)}))}i(TC,"ensureRunning");function OC(t,e){return e&&an.set(e,t),new Promise((r,n)=>{let o=setTimeout(()=>{st.has(t)&&(st.delete(t),e&&an.delete(e),n(new Error("OAuth callback timeout - authorization took too long")),Ha())},CC);st.set(t,{resolve:r,reject:n,timeout:o})})}i(OC,"waitForCallback");function AC(t){let r=an.get(t)??t,n=st.get(r);n&&(clearTimeout(n.timeout),st.delete(r),an.delete(t),n.reject(new Error("Authorization cancelled")),Ha())}i(AC,"cancelPending");async function l_(t=_o){return new Promise(e=>{let r=PC(t,"127.0.0.1");r.on("connect",()=>{r.destroy(),e(!0)}),r.on("error",()=>{e(!1)})})}i(l_,"isPortInUse");async function d_(){Et&&(await new Promise(t=>Et.close(()=>t())),Et=void 0);for(let[t,e]of st)clearTimeout(e.timeout),e.reject(new Error("OAuth callback server stopped"));st.clear(),an.clear()}i(d_,"stop");function MC(){return Et!==void 0}i(MC,"isRunning");var ln={};H(ln,{CommandExecute:()=>p_,Definitions:()=>DC,PromptAppend:()=>u_,SessionSelect:()=>m_,ToastShow:()=>f_,TuiEvent:()=>ln});var zC=5e3,u_=zt.define({type:"tui.prompt.append",schema:{text:f.String}}),p_=zt.define({type:"tui.command.execute",schema:{command:f.Union([f.Literals(["session.list","session.new","session.share","session.interrupt","session.compact","session.page.up","session.page.down","session.line.up","session.line.down","session.half.page.up","session.half.page.down","session.first","session.last","prompt.clear","prompt.submit","agent.cycle"]),f.String])}}),f_=zt.define({type:"tui.toast.show",schema:{title:Me(f.String),message:f.String,variant:f.Literals(["info","success","warning","error"]),duration:Du.pipe(f.withDecodingDefault(a.succeed(zC))).annotate({description:"Duration in milliseconds"})}}),m_=zt.define({type:"tui.session.select",schema:{sessionID:Uu.annotate({description:"Session ID to navigate to"})}}),DC=zt.inventory(u_,p_,f_,m_);var So={};H(So,{EffectBridge:()=>So,bind:()=>NC,fromPromise:()=>jC,make:()=>qC});function vo(t,e){return t!==void 0?Ro.restore(t,e):e()}i(vo,"restoreWorkspace");function h_(){let t=gs.getCurrent(),e=t?te.getReferenceUnsafe(t.context,zr):void 0,r=(t?te.getReferenceUnsafe(t.context,mr):void 0)??Ro.workspaceID;return{instance:e,workspace:r}}i(h_,"captureSync");var NC=i(t=>{let e=h_();return(...r)=>vo(e.workspace,()=>a.runSync(ws(a.sync(()=>t(...r)),e)))},"bind"),jC=i(t=>a.gen(function*(){let e=yield*mr;return yield*a.promise(()=>Promise.resolve(vo(e,()=>t())))}),"fromPromise");function qC(){return a.gen(function*(){let t=yield*a.context(),e=h_(),r=(yield*zr)??e.instance,n=(yield*mr)??e.workspace,o=i(s=>ws(s.pipe(a.provide(t)),{instance:r,workspace:n}),"wrap");return{promise:i(s=>vo(n,()=>a.runPromise(o(s))),"promise"),fork:i(s=>vo(n,()=>a.runFork(o(s))),"fork"),run:i(s=>a.callback(c=>{vo(n,()=>a.runPromiseExit(o(s)).then(l=>c(Wt.isSuccess(l)?a.succeed(l.value):a.failCause(l.cause))))}),"run"),bind:i(s=>(...c)=>vo(n,()=>a.runSync(o(a.sync(()=>s(...c))))),"bind")}})}i(qC,"make");var wo={};H(wo,{BrowserOpenFailed:()=>y_,Definitions:()=>LC,McpEvent:()=>wo,ToolsChanged:()=>g_});var g_=zt.define({type:"mcp.tools.changed",schema:{server:f.String}}),y_=zt.define({type:"mcp.browser.open.failed",schema:{mcpName:f.String,url:f.String}}),LC=zt.inventory(g_,y_);var ko={};H(ko,{McpBrowser:()=>ko,Service:()=>bo,node:()=>VC});function __(t){let e=URL.canParse(t)?new URL(t):void 0;return!e||e.protocol!=="http:"&&e.protocol!=="https:"?Promise.reject(new Error(`Only http and https links can be opened in the browser: ${t}`)):kp(e.href)}i(__,"openUrl");var bo=class extends te.Service()("@opencode/McpBrowser"){static{i(this,"Service")}},UC=V.succeed(bo,bo.of({open:a.fn("McpBrowser.open")(function*(t){let e=yield*a.tryPromise({try:i(()=>__(t),"try"),catch:i(r=>r instanceof Error?r:new Error(String(r)),"catch")});yield*a.callback(r=>{let n=setTimeout(()=>r(a.void),500);e.on("error",s=>{clearTimeout(n),r(a.fail(s))});let o=i(s=>{s===null||s===0||(clearTimeout(n),r(a.fail(new Error(`Browser open failed with exit code ${s}`))))},"onExit");e.on("exit",o),o(e.exitCode)})})})),VC=ft.make({service:bo,layer:UC,deps:[]});var v_=3e4,ZC={capabilities:{roots:{}}},KC=f.Struct({name:f.String,uri:f.String,description:f.optional(f.String),mimeType:f.optional(f.String),client:f.String}).annotate({identifier:"McpResource"}),GC=f.Struct({name:f.String,description:f.optional(f.String),readOnly:f.optional(f.Boolean)}).annotate({identifier:"MCPToolManifestEntry"}),Pu=wo.ToolsChanged,k_=wo.BrowserOpenFailed,WC=vs.create("MCPFailed",{name:f.String}),Za=class extends f.TaggedErrorClass()("MCP.NotFoundError",{name:f.String}){static{i(this,"NotFoundError")}};function S_(t){let e=new za({name:"opencode",version:ht},ZC);return e.setRequestHandler(cl,()=>Promise.resolve({roots:[{uri:HC(t).href}]})),e}i(S_,"createClient");var BC=f.Struct({status:f.Literal("connected")}).annotate({identifier:"MCPStatusConnected"}),JC=f.Struct({status:f.Literal("disabled")}).annotate({identifier:"MCPStatusDisabled"}),YC=f.Struct({status:f.Literal("failed"),error:f.String}).annotate({identifier:"MCPStatusFailed"}),XC=f.Struct({status:f.Literal("needs_auth")}).annotate({identifier:"MCPStatusNeedsAuth"}),QC=f.Struct({status:f.Literal("needs_client_registration"),error:f.String}).annotate({identifier:"MCPStatusNeedsClientRegistration"}),e$=f.Union([BC,JC,YC,XC,QC]).annotate({identifier:"MCPStatus",discriminator:"status"}),Eo=new Map;function us(t){return typeof t=="object"&&t!==null&&"type"in t}i(us,"isMcpConfigured");function w_(t){if(URL.canParse(t))return new URL(t)}i(w_,"remoteURL");var dn=class extends te.Service()("@opencode/MCP"){static{i(this,"Service")}},b_=new Map;function xu(t){let e=b_.get(t);return e||(e=new Map,b_.set(t,e)),e}i(xu,"runtimeFor");var t$=ys(dn),r$=V.effect(dn,a.gen(function*(){let t=yield*Au.ChildProcessSpawner,e=yield*Zn.Service,r=yield*Xt.Service,n=yield*ko.Service,o=a.fn("MCP.connectTransport")(function*(b,k){let R=yield*Q.directory;return yield*a.acquireUseRelease(a.succeed(b),C=>a.tryPromise({try:i(()=>{let A=S_(R);return s_(A.connect(C),k).then(()=>A)},"try"),catch:i(A=>A instanceof Error?A:new Error(String(A)),"catch")}),(C,A)=>Wt.isFailure(A)?a.tryPromise(()=>C.close()).pipe(a.ignore):a.void)}),s={status:{status:"disabled"}},c=a.fn("MCP.connectRemote")(function*(b,k){let R=k.oauth===!1,C=typeof k.oauth=="object"?k.oauth:void 0,A=w_(k.url);if(!A)return{client:void 0,status:{status:"failed",error:`Invalid MCP URL for "${b}"`}};let D;R||(D=new ds(b,k.url,{clientId:C?.clientId,clientSecret:C?.clientSecret,scope:C?.scope,callbackPort:C?.callbackPort,redirectUri:C?.redirectUri},{onRedirect:i(async()=>{},"onRedirect")},e));let j=[{name:"StreamableHTTP",transport:new os(A,{authProvider:D,requestInit:k.headers?{headers:k.headers}:void 0})},{name:"SSE",transport:new La(A,{authProvider:D,requestInit:k.headers?{headers:k.headers}:void 0})}],ne=k.timeout??v_,Z;for(let{name:Pt,transport:$e}of j){let $u=yield*o($e,ne).pipe(a.map(un=>({client:un,transportName:Pt})),a.catch(un=>{let hs=un instanceof Error?un:new Error(String(un));return un instanceof ze||D&&hs.message.includes("OAuth")?hs.message.includes("registration")||hs.message.includes("client_id")?(Z={status:"needs_client_registration",error:"Server does not support dynamic client registration. Please provide clientId in config."},r.publish(ln.ToastShow,{title:"MCP Authentication Required",message:`Server "${b}" requires a pre-registered client ID. Add clientId to your config.`,variant:"warning",duration:8e3}).pipe(a.ignore,a.as(void 0))):(Eo.set(b,{transport:$e}),Z={status:"needs_auth"},r.publish(ln.ToastShow,{title:"MCP Authentication Required",message:`Server "${b}" requires authentication. Run: opencode mcp auth ${b}`,variant:"warning",duration:8e3}).pipe(a.ignore,a.as(void 0))):(Z={status:"failed",error:hs.message},a.void)}));if($u)return{client:$u.client,status:{status:"connected"}};if(Z?.status==="needs_auth"||Z?.status==="needs_client_registration")break}return{client:void 0,status:Z??{status:"failed",error:"Unknown error"}}}),l=a.fn("MCP.connectLocal")(function*(b,k){let[R,...C]=k.command,A=yield*Q.directory,D=k.cwd?FC.resolve(A,k.cwd):A,j=new ls({stderr:"pipe",command:R,args:C,cwd:D,env:{...process.env,...R==="opencode"?{BUN_BE_BUN:"1"}:{},...k.environment}}),ne=k.timeout??v_;return yield*o(j,ne).pipe(a.map(Z=>({client:Z,status:{status:"connected"}})),a.catch(Z=>{let Pt=Z instanceof Error?Z.message:String(Z);return a.succeed({client:void 0,status:{status:"failed",error:Pt}})}))}),d=a.fn("MCP.create")(function*(b,k){if(k.enabled===!1)return s;let{client:R,status:C}=k.type==="remote"?yield*c(b,k):yield*l(b,k);return R?yield*a.gen(function*(){let A=R.getServerCapabilities()?.tools?yield*ut.defs(R,k.timeout):[];return A?{mcpClient:R,status:C,defs:A,instructions:R.getInstructions()?.trim()}:yield*a.fail(new Error("Failed to get tools"))}).pipe(a.catchCause(A=>a.tryPromise(()=>R.close()).pipe(a.ignore,a.andThen(a.failCause(A))))):(C.status!=="connected"&&C.status!=="disabled"&&(yield*a.logWarning("server unavailable",{key:b,type:k.type,status:C.status})),{status:C})},a.map(b=>b),a.catchCause(b=>{if(xo.hasInterruptsOnly(b))return a.interrupt;let k=xo.squash(b);return a.succeed({status:{status:"failed",error:k instanceof Error?k.message:String(k)}})})),u=yield*gn.Service,p=a.fnUntraced(function*(b){if(process.platform==="win32")return[];let k=[],R=[b];for(let C=0;C<R.length;C++){let A=R[C],D=yield*t.spawn(Mu.make("pgrep",["-P",String(A)],{stdin:"ignore"})),j=yield*ur.mkString(ur.decodeText(D.stdout));yield*D.exitCode;for(let ne of j.split(`
878
+ `)){let Z=parseInt(ne,10);!isNaN(Z)&&!k.includes(Z)&&(k.push(Z),R.push(Z))}}return k},a.scoped,a.catch(()=>a.succeed([])));function m(b,k,R,C,A){R.onclose=()=>{b.clients[k]===R&&(delete b.clients[k],delete b.defs[k],delete b.instructions[k],b.status[k]={status:"failed",error:"Connection closed"},C.fork(a.logWarning("MCP connection closed",{server:k}).pipe(a.andThen(r.publish(Pu,{server:k})),a.ignore)))},R.setNotificationHandler(tl,D=>C.promise(g(k,D.params))),R.getServerCapabilities()?.tools&&R.setNotificationHandler(fi,async()=>{if(b.clients[k]!==R||b.status[k]?.status!=="connected")return;let D=await C.promise(ut.defs(R,A));D&&(b.clients[k]!==R||b.status[k]?.status!=="connected"||(b.defs[k]=D,await C.promise(r.publish(Pu,{server:k}).pipe(a.ignore))))})}i(m,"watch");function g(b,k){let R={server:b,logger:k.logger,level:k.level,data:k.data};switch(k.level){case"debug":return a.logDebug("MCP server log",R);case"info":case"notice":return a.logInfo("MCP server log",R);case"warning":return a.logWarning("MCP server log",R);case"error":case"critical":case"alert":case"emergency":return a.logError("MCP server log",R)}}i(g,"serverLog");let y=yield*Q.make(a.fn("MCP.state")(function*(b){let k=yield*u.get(),R=yield*So.make(),C=Object.fromEntries([...xu(b.directory)].filter(([j])=>!(k.mcp??{})[j])),A={...C,...k.mcp??{}},D={config:{...C},status:{},clients:{},defs:{},instructions:{}};return yield*a.forEach(Object.entries(A),([j,ne])=>a.gen(function*(){if(!us(ne)){yield*a.logError("Ignoring MCP config entry without type",{key:j});return}if(ne.enabled===!1){D.status[j]={status:"disabled"};return}let Z=yield*d(j,ne);D.status[j]=Z.status,Z.mcpClient&&(D.clients[j]=Z.mcpClient,D.defs[j]=Z.defs,Z.instructions&&(D.instructions[j]=Z.instructions),m(D,j,Z.mcpClient,R,ne.timeout))}),{concurrency:"unbounded"}),yield*a.addFinalizer(()=>a.gen(function*(){let j=Object.values(D.clients);D.clients={},D.defs={},D.instructions={},yield*a.forEach(j,ne=>a.gen(function*(){let Z=ne.transport instanceof ls?ne.transport.pid:null;if(typeof Z=="number"){let Pt=yield*p(Z);for(let $e of Pt)try{process.kill($e,"SIGTERM")}catch{}}yield*a.tryPromise(()=>ne.close()).pipe(a.ignore)}),{concurrency:"unbounded"}),Eo.clear()})),D}));function h(b,k){let R=b.clients[k];return delete b.clients[k],delete b.defs[k],delete b.instructions[k],R?a.tryPromise(()=>R.close()).pipe(a.ignore):a.void}i(h,"closeClient");let _=a.fnUntraced(function*(b,k,R,C,A,D){let j=yield*So.make(),ne=b.clients[k];return b.status[k]={status:"connected"},b.clients[k]=R,b.defs[k]=C,A?b.instructions[k]=A:delete b.instructions[k],m(b,k,R,j,D),ne&&(yield*a.tryPromise(()=>ne.close()).pipe(a.ignore)),b.status[k]}),S=a.fn("MCP.status")(function*(){let b=yield*Q.get(y),R=(yield*u.get()).mcp??{},C={};for(let[A,D]of Object.entries(R))us(D)&&(C[A]=b.status[A]??{status:"disabled"});for(let A of Object.keys(b.config))C[A]=b.status[A]??{status:"disabled"};return C}),E=a.fn("MCP.clients")(function*(){return(yield*Q.get(y)).clients}),x=a.fn("MCP.instructions")(function*(){let b=yield*Q.get(y);return Object.entries(b.instructions).filter(([k])=>b.status[k]?.status==="connected").sort(([k],[R])=>k.localeCompare(R)).map(([k,R])=>({name:k,instructions:R,tools:(b.defs[k]??[]).map(C=>ut.toolName(k,C.name))}))}),w=a.fn("MCP.createAndStore")(function*(b,k){let R=yield*Q.get(y),C=yield*d(b,k);return R.status[b]=C.status,C.mcpClient?yield*_(R,b,C.mcpClient,C.defs,C.instructions,k.timeout):(yield*h(R,b),delete R.clients[b],C.status)}),P=a.fn("MCP.add")(function*(b,k){let R=yield*Q.get(y);return R.config[b]=k,yield*w(b,k),xu(yield*Q.directory).set(b,k),{status:R.status}}),I=a.fn("MCP.connect")(function*(b){let k=yield*Or(b);yield*w(b,{...k,enabled:!0})}),L=a.fn("MCP.disconnect")(function*(b){yield*Or(b);let k=yield*Q.get(y);yield*h(k,b),delete k.clients[b],k.status[b]={status:"disabled"},xu(yield*Q.directory).delete(b)});function F(b,k,R,C){let A=R&&us(R)?R.timeout:void 0;return b.config[k]?.timeout??A??C}i(F,"requestTimeout");let Be=a.fn("MCP.tools")(function*(){let b={},k=yield*Q.get(y),R=yield*u.get(),C=R.mcp??{},A=R.experimental?.mcp_timeout;for(let[D,j]of Object.entries(k.clients)){if(k.status[D]?.status!=="connected")continue;let ne=C[D],Z=k.defs[D];if(!Z){yield*a.logWarning("missing cached tools for connected server",{clientName:D});continue}let Pt=F(k,D,ne,A);for(let $e of Z)b[ut.toolName(D,$e.name)]={def:$e,client:j,timeout:Pt}}return b}),Gt=a.fn("MCP.toolManifest")(function*(){let b=yield*Q.get(y),k={};for(let R of Object.keys(b.clients)){if(b.status[R]?.status!=="connected")continue;let C=b.defs[R];C&&(k[R]=C.map(A=>({name:A.name,...A.description?{description:A.description}:{},...typeof A.annotations?.readOnlyHint=="boolean"?{readOnly:A.annotations.readOnlyHint}:{}})))}return k});function xt(b,k,R,C,A){return a.gen(function*(){let D=yield*u.get();return yield*a.forEach(Object.entries(b.clients).filter(([j])=>b.status[j]?.status==="connected"&&(!A||j===A)),([j,ne])=>ut.fetch(j,ne,Z=>k(Z,F(b,j,D.mcp?.[j],D.experimental?.mcp_timeout)),R,C).pipe(a.map(Z=>Object.entries(Z??{}))),{concurrency:"unbounded"}).pipe(a.map(j=>Object.fromEntries(j.flat())))})}i(xt,"collectFromConnected");let Tr=a.fn("MCP.prompts")(function*(){return yield*xt(yield*Q.get(y),ut.prompts,"prompts")}),ps=a.fn("MCP.resources")(function*(b){return yield*xt(yield*Q.get(y),ut.resources,"resources",k=>k.uri,b)}),fs=a.fn("MCP.resourceTemplates")(function*(b){return yield*xt(yield*Q.get(y),ut.resourceTemplates,"resource templates",k=>k.uriTemplate,b)}),ms=a.fnUntraced(function*(b,k,R,C){let A=yield*Q.get(y),D=A.clients[b];if(!D){yield*a.logWarning(`client not found for ${R}`,{clientName:b});return}let j=yield*u.get();return yield*a.tryPromise({try:i(()=>k(D,F(A,b,j.mcp?.[b],j.experimental?.mcp_timeout)),"try"),catch:i(ne=>ne,"catch")}).pipe(a.tapError(ne=>a.logError(`failed to ${R}`,{clientName:b,...C,error:ne instanceof Error?ne.message:String(ne)})),a.orElseSucceed(()=>{}))}),E_=a.fn("MCP.getPrompt")(function*(b,k,R){return yield*ms(b,(C,A)=>C.getPrompt({name:k,arguments:R},{timeout:A}),"getPrompt",{promptName:k})}),x_=a.fn("MCP.readResource")(function*(b,k){return yield*ms(b,(R,C)=>R.readResource({uri:k},{timeout:C}),"readResource",{resourceUri:k})}),P_=a.fnUntraced(function*(b){let k=yield*Q.get(y);if(k.config[b])return k.config[b];let C=(yield*u.get()).mcp?.[b];if(!(!C||!us(C)))return C}),Or=a.fnUntraced(function*(b){let k=yield*P_(b);return k||(yield*new Za({name:b}))}),Iu=a.fn("MCP.startAuth")(function*(b){let k=yield*Or(b);if(k.type!=="remote")throw new Error(`MCP server ${b} is not a remote server`);if(k.oauth===!1)throw new Error(`MCP server ${b} has OAuth explicitly disabled`);let R=w_(k.url);if(!R)throw new Error(`Invalid MCP URL for "${b}"`);let C=typeof k.oauth=="object"?k.oauth:void 0,A=C?.redirectUri??(C?.callbackPort?`http://127.0.0.1:${C.callbackPort}${$r}`:void 0);yield*a.promise(()=>cn.ensureRunning(A));let D=Array.from(crypto.getRandomValues(new Uint8Array(32))).map($e=>$e.toString(16).padStart(2,"0")).join("");yield*e.updateOAuthState(b,D);let j,ne=new Va(b,k.url,{clientId:C?.clientId,clientSecret:C?.clientSecret,scope:C?.scope,redirectUri:A},{onRedirect:i(async $e=>{j=$e},"onRedirect")},e),Z=new os(R,{authProvider:ne,requestInit:k.headers?{headers:k.headers}:void 0}),Pt=yield*Q.directory;return yield*a.tryPromise({try:i(()=>{let $e=S_(Pt);return $e.connect(Z).then(async()=>(await ne.commit(),{authorizationUrl:"",oauthState:D,client:$e}))},"try"),catch:i($e=>$e,"catch")}).pipe(a.catch($e=>$e instanceof ze&&j?(Eo.set(b,{transport:Z,provider:ne}),a.succeed({authorizationUrl:j.toString(),oauthState:D})):a.die($e)))}),R_=a.fn("MCP.authenticate")(function*(b,k){let R=yield*Iu(b);if(!R.authorizationUrl){let j="client"in R?R.client:void 0,ne=yield*Or(b).pipe(a.tapError(()=>a.tryPromise(()=>j?.close()??Promise.resolve()).pipe(a.ignore))),Z=j?j.getServerCapabilities()?.tools?yield*ut.defs(j,ne.timeout):[]:void 0;if(!j||!Z)return yield*a.tryPromise(()=>j?.close()??Promise.resolve()).pipe(a.ignore),{status:"failed",error:"Failed to get tools"};let Pt=yield*Q.get(y);return yield*e.clearOAuthState(b),yield*_(Pt,b,j,Z,j.getInstructions()?.trim(),ne.timeout)}let C=cn.waitForCallback(R.oauthState,b);k?.(R.authorizationUrl),yield*n.open(R.authorizationUrl).pipe(a.catch(()=>r.publish(k_,{mcpName:b,url:R.authorizationUrl}).pipe(a.ignore)));let A=yield*a.promise(()=>C);if((yield*e.getOAuthState(b))!==R.oauthState)throw yield*e.clearOAuthState(b),new Error("OAuth state mismatch - potential CSRF attack");return yield*e.clearOAuthState(b),yield*Cu(b,A)}),Cu=a.fn("MCP.finishAuth")(function*(b,k){yield*Or(b);let R=Eo.get(b);if(!R)throw new Error(`No pending OAuth flow for MCP server: ${b}`);let C=yield*a.tryPromise({try:i(()=>R.transport.finishAuth(k),"try"),catch:i(D=>D,"catch")}).pipe(a.match({onFailure:i(D=>D instanceof Error?D.message:String(D),"onFailure"),onSuccess:i(()=>{},"onSuccess")}));if(C)return{status:"failed",error:`OAuth completion failed: ${C}`};yield*a.promise(()=>R.provider?.commit()??Promise.resolve()),yield*e.clearCodeVerifier(b),Eo.delete(b);let A=yield*Or(b);return yield*w(b,{...A,enabled:!0})}),I_=a.fn("MCP.removeAuth")(function*(b){yield*e.remove(b),cn.cancelPending(b),Eo.delete(b)}),C_=a.fn("MCP.supportsOAuth")(function*(b){let k=yield*Or(b);return k.type==="remote"&&k.oauth!==!1}),$_=a.fn("MCP.hasStoredTokens")(function*(b){return!!(yield*e.get(b))?.tokens}),T_=a.fn("MCP.getAuthStatus")(function*(b){let R=((yield*Q.has(y))?(yield*Q.get(y)).config[b]:void 0)??(yield*u.get()).mcp?.[b];if(!R||!us(R)||R.type!=="remote")return"not_authenticated";let C=yield*e.getForUrl(b,R.url);return C?.tokens?C.tokens.expiresAt&&C.tokens.expiresAt<Date.now()/1e3?"expired":"authenticated":"not_authenticated"});return dn.of({status:S,clients:E,instructions:x,tools:Be,defs:Gt,prompts:Tr,resources:ps,resourceTemplates:fs,add:P,connect:I,disconnect:L,getPrompt:E_,readResource:x_,startAuth:Iu,authenticate:R_,finishAuth:Cu,removeAuth:I_,supportsOAuth:C_,hasStoredTokens:$_,getAuthStatus:T_})})),n$=ft.make({service:dn,layer:r$,deps:[Yu.node,Zn.node,Xt.node,gn.node,ko.node]});export{hr as a,To as b,gt as c,kn as d,xn as e,ct as f,zn as g,Qt as h,Ze as i,er as j,Ce as k,Lt as l,Io as m,jt as n,lt as o,Ac as p,yi as q,yl as r,B as s,oe as t,or as u,wt as v,Vl as w,Ii as x,la as y,Ci as z,ua as A,ig as B,hg as C,Sg as D,wa as E,gy as F,Yd as G,Iy as H,Ay as I,__ as J,C$ as K,So as L,ic as M,$o as N,Sn as O,Dc as P,_r as Q,s_ as R,Zn as S,ln as T,T3 as U,ut as V,wo as W,Ru as X};