alchemylab-opencode 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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-ND6UHXWL.js +18 -0
  43. package/dist/app-runtime-ZWWQ4JTM.js +18 -0
  44. package/dist/chunk-2MRHL4B2.js +18 -0
  45. package/dist/chunk-2XWBNI3L.js +1490 -0
  46. package/dist/chunk-4MBUHJHY.js +22 -0
  47. package/dist/chunk-6MAPFAXY.js +190 -0
  48. package/dist/chunk-7XX6TY62.js +259 -0
  49. package/dist/chunk-ANF3QA3Z.js +48 -0
  50. package/dist/chunk-AUB2TEYJ.js +55 -0
  51. package/dist/chunk-AZUMH3TO.js +18 -0
  52. package/dist/chunk-BQ4IEPN3.js +19 -0
  53. package/dist/chunk-CYRZU5QM.js +33 -0
  54. package/dist/chunk-DGJQZN2Q.js +18 -0
  55. package/dist/chunk-DO2UZ6NY.js +18 -0
  56. package/dist/chunk-DZ6G4VSD.js +19 -0
  57. package/dist/chunk-EK6FQQHY.js +20 -0
  58. package/dist/chunk-ELPXQ32J.js +90 -0
  59. package/dist/chunk-F5PY52BY.js +18 -0
  60. package/dist/chunk-FGLPSSRK.js +19 -0
  61. package/dist/chunk-FV7U6PVP.js +18 -0
  62. package/dist/chunk-FYYAOZPU.js +18 -0
  63. package/dist/chunk-GDWO6EXN.js +22 -0
  64. package/dist/chunk-GW3ZRKAI.js +20 -0
  65. package/dist/chunk-IQSFXWDQ.js +18 -0
  66. package/dist/chunk-IYUSBBGY.js +35 -0
  67. package/dist/chunk-JPOFLMNH.js +18 -0
  68. package/dist/{chunk-VURLSDCB.js → chunk-K5LKDIVU.js} +4 -0
  69. package/dist/chunk-KS4WLVK5.js +19 -0
  70. package/dist/chunk-L3CE2Y3L.js +55 -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-OCWGUTZJ.js +36 -0
  78. package/dist/chunk-OGDRUXMJ.js +18 -0
  79. package/dist/chunk-OGJKLJC7.js +29 -0
  80. package/dist/chunk-P5RLCJUV.js +18 -0
  81. package/dist/chunk-Q3WIUQXB.js +18 -0
  82. package/dist/{20260227213759_add_session_workspace_id-ROENWPKA.js → chunk-QCRIXKIC.js} +5 -1
  83. package/dist/chunk-QD24DLUD.js +18 -0
  84. package/dist/chunk-R2GWBJEP.js +18 -0
  85. package/dist/chunk-RIA6SDOY.js +780 -0
  86. package/dist/chunk-RPAXSOGH.js +18 -0
  87. package/dist/chunk-TK5R7QUN.js +18 -0
  88. package/dist/chunk-TNQWZFIZ.js +28 -0
  89. package/dist/chunk-UCLPBO4I.js +18 -0
  90. package/dist/chunk-V6FDDNGV.js +117 -0
  91. package/dist/chunk-V6HERYFV.js +18 -0
  92. package/dist/chunk-V7XKKJ7X.js +24 -0
  93. package/dist/chunk-VHDYUBBS.js +23 -0
  94. package/dist/chunk-VWLJXTZ5.js +18 -0
  95. package/dist/chunk-VXAPFOIL.js +22 -0
  96. package/dist/chunk-WKZYINC7.js +29 -0
  97. package/dist/chunk-WL33KE3H.js +920 -0
  98. package/dist/chunk-WPMP2ZFE.js +40 -0
  99. package/dist/chunk-WRTNIOI3.js +18 -0
  100. package/dist/chunk-WZ4237YY.js +19 -0
  101. package/dist/chunk-X5F46HR5.js +18 -0
  102. package/dist/chunk-XPS7TQZG.js +22 -0
  103. package/dist/chunk-XSKT4AXR.js +878 -0
  104. package/dist/chunk-YJPP6IQ3.js +23 -0
  105. package/dist/chunk-ZYQWFC55.js +22 -0
  106. package/dist/code-mode-H3HRSD24.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/dist-HXJTF22W.js +32 -0
  112. package/dist/dist-JFXI53ZF.js +22 -0
  113. package/dist/dist-KBYKWVT5.js +22 -0
  114. package/dist/dist-KGNO5AP7.js +35 -0
  115. package/dist/dist-KTNLTEHB.js +18 -0
  116. package/dist/dist-KZ5R5QM5.js +24 -0
  117. package/dist/{20260605042240_add_context_epoch_agent-W6IQYZXE.js → dist-LOXU6IEM.js} +5 -1
  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-WZJ3LNRG.js +28 -0
  129. package/dist/dist-XAFENVUS.js +22 -0
  130. package/dist/dist-XPFB35TX.js +32 -0
  131. package/dist/dist-es-43ZM44MP.js +18 -0
  132. package/dist/dist-es-CH2YKBKX.js +18 -0
  133. package/dist/{20260428004200_add_session_path-LGW75WYA.js → dist-es-DHCTZZ2E.js} +5 -1
  134. package/dist/dist-es-EVVG3KDV.js +26 -0
  135. package/dist/dist-es-HRCONNGK.js +18 -0
  136. package/dist/dist-es-L2GU465G.js +18 -0
  137. package/dist/dist-es-RGEIM2BP.js +18 -0
  138. package/dist/dist-es-RZ25XEH6.js +18 -0
  139. package/dist/dist-es-SITTNOGV.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-7VH6D2QJ.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-GSWEOYZ5.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-XRUYBM7W.js +21 -0
  163. package/dist/session-4BXV4JJH.js +18 -0
  164. package/dist/signin-DKBWDEYP.js +18 -0
  165. package/dist/src-JODD73WX.js +18 -0
  166. package/dist/src-QJHT5SCV.js +18 -0
  167. package/dist/src-SMM4U63G.js +18 -0
  168. package/dist/src-WDYKISPD.js +20 -0
  169. package/dist/sso-oidc-S3P64MCY.js +18 -0
  170. package/dist/sts-RG44NMOQ.js +18 -0
  171. package/dist/token-2V62AM3G.js +18 -0
  172. package/dist/token-util-VXONHEUD.js +18 -0
  173. package/dist/unified-W3ZKZ4HG.js +18 -0
  174. package/dist/worktree-B2LROS2B.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,21 @@
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{A as Hm,B as Pm,C as ha,D as ye,E as bm,F as Es,G as Sa,a as am,b as Xe,c as hm,d as Nc,e as $t,f as vo,g as Sm,h as Xr,i as ma,j as la,k as Eo,l as Am,m as Im,n as fa,o as Ao,p as wm,q as Rm,r as Jr,s as Io,t as Cm,u as _c,v as ya,w as ga,x as Vt,y as km,z as at}from"./chunk-2XWBNI3L.js";import{D as qm,F as wo,G as Oe,H as zt,a as Gu,c as om,d as oa,e as Pt,f as yo,g as Ke,h as sm,i as he,j as Yr,k as sa,p as Oc,r as im,s as Ss,t as Ne,v as ym,z as Dm}from"./chunk-WL33KE3H.js";import{a as xm,b as Zr,f as it,g as It,h as Tm,w as fr}from"./chunk-6MAPFAXY.js";import{L as ho,N as Cn,O as gm,P as So,S as vm,T as ie,W as Em,X as qe,b as Bu,c as Fu,d as qc,e as hs,f as fo,g as Xu,h as ta,i as Ju,j as Zu,k as ra,m as nm,n as na}from"./chunk-XSKT4AXR.js";import"./chunk-GW3ZRKAI.js";import{R as X,g as pa,h as lm,i as fm,j as Y,k as Kr,l as Uc,p as da,q as ua}from"./chunk-L3CE2Y3L.js";import{$ as lo,B as Yu,Ba as pe,C as gs,Ca as Lc,Da as Ue,Ea as um,Ia as go,X as Ku,_ as mo,_a as At,a as wn,aa as Et,b as Ru,c as Ge,d as K,da as em,e as Wu,ea as tm,f as $u,g as Vu,h as Vr,ha as rm,i as zu,j as Qu,ja as cm,jb as lr,k as ea,ka as pm,kb as Wt,la as ia,lb as mm,mb as vs,r as zr,t as bc,ta as dm,u as Qr,v as ys,va as Gt,wa as aa,xa as ca,ya as Mc}from"./chunk-RIA6SDOY.js";import"./chunk-QD24DLUD.js";import"./chunk-WZ4237YY.js";import"./chunk-V6FDDNGV.js";import"./chunk-QCRIXKIC.js";import"./chunk-P5RLCJUV.js";import"./chunk-LIXP4TPL.js";import"./chunk-M6E6KNLV.js";import{d as xh}from"./chunk-NDI67DRG.js";import"./chunk-WKZYINC7.js";import"./chunk-Q3WIUQXB.js";import"./chunk-WPMP2ZFE.js";import"./chunk-K5LKDIVU.js";import"./chunk-TK5R7QUN.js";import{b as Rn,d as Zi,f as $r}from"./chunk-R2GWBJEP.js";import{$ as Su,$a as bu,A as nu,Aa as st,B as ji,Ba as Pc,C as Gi,Ca as Ye,D as ou,Da as Qi,E as Rc,Ea as ds,F as su,G as iu,H as q,I as Qe,J as Cc,Ja as be,K as au,L as Le,La as kt,M as xc,Ma as us,N as pu,Na as Cu,O as du,P as kc,Pa as Yi,Q as Wi,R as uu,Ra as xu,S as mu,Sa as ku,Sb as Ou,Sc as Gr,T as lu,Ta as Hu,Tc as Uu,U as fu,Ub as po,V as le,Vb as Mu,Vc as uo,W as yu,Wc as Ht,X as gu,Xa as Pu,Y as Br,Ya as Tu,Z as $i,_ as hu,aa as vu,ba as Eu,bd as Fe,ca as Ee,cd as ce,de as Tc,ed as Dn,fe as Ji,ga as Au,ge as fe,ha as zi,ia as Fr,j as ru,je as _u,ke as je,la as In,lb as ms,le as fs,m as ur,ma as Ie,mb as Ki,mc as Lu,n as ao,na as vt,nb as qu,oa as we,pc as mr,q as _i,qa as Du,qb as jr,rb as Xi,sb as ls,sd as Nu,we as ju,x as Bi,xa as z,xe as Wr,y as Fi,z as Be}from"./chunk-7XX6TY62.js";import"./chunk-LSC4RT5V.js";import"./chunk-V7XKKJ7X.js";import"./chunk-FV7U6PVP.js";import"./chunk-UCLPBO4I.js";import"./chunk-V6HERYFV.js";import"./chunk-DO2UZ6NY.js";import"./chunk-AZUMH3TO.js";import{d as jt,h as cu,p as Vi,u as Iu,v as wu}from"./chunk-VWLJXTZ5.js";import{$f as Nd,$i as Oi,Bc as xt,Bd as Ei,Be as lc,Bf as s,Bh as Ci,Ca as yi,Cf as ns,Ch as is,Ci as Kd,Df as Pd,Dh as $d,Di as Xd,Ee as Hd,Ef as Ur,Eh as Vd,Ei as Jd,Ej as co,Ff as Td,Fg as Ae,Gd as re,Gf as oo,Gi as bi,Hc as Id,Hf as dr,Ia as Ed,Ih as zd,Ii as as,Jh as xi,Kd as Dd,Kf as yc,Ki as cs,Lc as vi,Lf as bd,Lh as ki,Li as Ic,Md as es,Mi as vn,Nd as no,Oa as Te,Oh as Nr,Oi as Zd,P as fi,Pa as gi,Pd as dc,Pf as gc,Pi as qi,Qf as qd,Ra as Mr,Rf as Od,Rh as Hi,S as yd,Sa as Lr,Sd as uc,Sf as Md,Sh as Pi,Si as _r,Ta as hi,Tc as P,Td as pr,Tf as Ld,Uf as Ii,Ui as wc,Va as Xo,Vf as Ud,Vi as En,Wa as ac,Wf as wi,Xd as Rd,Xf as hc,Ya as cc,Yf as Sc,Yi as eu,Z as gd,Za as Ct,Zd as ts,Zf as so,_ as hd,_a as Jo,_f as vc,a as qr,aa as Ce,ab as Ad,ae as Ai,ag as _d,bb as oe,bg as Sn,bi as se,bj as tu,c as hn,cg as Ec,cj as Dc,dc as cr,dg as os,dj as Mi,eg as Bd,eh as ss,f as ld,fa as Sd,fj as nt,ge as Cd,gh as jd,h as fd,he as Bt,hj as Li,ih as Di,ij as Ui,ja as sc,jd as _t,jh as Ri,kd as wd,kj as ps,lc as ro,lj as ot,me as xd,mh as io,nb as Si,nd as pc,nj as An,of as fc,oj as Ni,pg as Fd,pj as o,qa as vd,qj as Hc,r as St,rc as Zo,rg as Ac,rh as Gd,ta as Or,ti as ze,ue as mc,ui as Ti,wh as Ft,wi as Qd,ye as rs,yh as Wd,yi as Yd,za as ic,ze as kd}from"./chunk-ELPXQ32J.js";import{a as i,b as gn,d as ve,e as me,g as oc}from"./chunk-2MRHL4B2.js";var Ca=ve(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});tp.default=Iv;var al=/[A-Z]/g;function cl(t){return t.toLowerCase()}i(cl,"toLowerCase");function Iv(t,e){let r=t.replace(al,cl),n=e.replace(al,cl);return r===n}i(Iv,"dnsEqual")});var rp=ve(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.DnsTxt=void 0;var xa=class{static{i(this,"DnsTxt")}constructor(e={}){this.binary=e?e.binary:!1}encode(e={}){return Object.entries(e).map(([r,n])=>{let a=`${r}=${n}`;return Buffer.from(a)})}decode(e){var r={};try{let a=e.toString().split(/=(.+)/),c=a[0],p=a[1];r[c]=p}catch{}return r}decodeAll(e){return e.filter(r=>r.length>1).map(r=>this.decode(r)).reduce((r,n)=>{var a=r;let[c]=Object.keys(n),[p]=Object.values(n);return a[c]=p,a},{})}};Ws.DnsTxt=xa;Ws.default=xa});var np=ve(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.toType=Co.toString=void 0;var pl=i(t=>"_"+t,"Prefix"),wv=i(t=>["name","protocol","subtype"].includes(t),"AllowedProp"),Dv=i(t=>{let e={name:t.name,protocol:t.protocol,subtype:t.subtype};return Object.entries(e).filter(([n,a])=>wv(n)&&a!==void 0).reduce((n,[a,c])=>(typeof c==="object"?c.map(p=>n.push(pl(p))):n.push(pl(c)),n),[]).join(".")},"toString");Co.toString=Dv;var Rv=i(t=>{let e=t.split("."),r;for(let n in e)e[n][0]==="_"&&(e[n]=e[n].slice(1));return e.includes("sub")&&(r=e.shift(),e.shift()),{name:e.shift(),protocol:e.shift()||null,subtype:r}},"toType");Co.toType=Rv});var op=ve(Mn=>{"use strict";var ul=Mn&&Mn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.Service=void 0;var dl=ul(gn("os")),Cv=ul(rp()),xv=gn("events"),kv=np(),ka=".local",Ha=class extends xv.EventEmitter{static{i(this,"Service")}constructor(e){if(super(),this.probe=!0,this.published=!1,this.activated=!1,this.destroyed=!1,this.txtService=new Cv.default,!e.name)throw new Error("ServiceConfig requires `name` property to be set");if(!e.type)throw new Error("ServiceConfig requires `type` property to be set");if(!e.port)throw new Error("ServiceConfig requires `port` property to be set");this.name=e.name.split(".").join("-"),this.protocol=e.protocol||"tcp",this.type=(0,kv.toString)({name:e.type,protocol:this.protocol}),this.port=e.port,this.host=e.host||dl.default.hostname(),this.fqdn=`${this.name}.${this.type}${ka}`,this.txt=e.txt,this.subtypes=e.subtypes,this.disableIPv6=!!e.disableIPv6}records(){var e=[this.RecordPTR(this),this.RecordSRV(this),this.RecordTXT(this)];for(let n of this.subtypes||[])e.push(this.RecordSubtypePTR(this,n));let r=Object.values(dl.default.networkInterfaces());for(let n of r){let a=n;for(let c of a)if(!(c.internal||c.mac==="00:00:00:00:00:00"))switch(c.family){case"IPv4":e.push(this.RecordA(this,c.address));break;case"IPv6":if(this.disableIPv6)break;e.push(this.RecordAAAA(this,c.address));break}}return e}RecordPTR(e){return{name:`${e.type}${ka}`,type:"PTR",ttl:28800,data:e.fqdn}}RecordSubtypePTR(e,r){return{name:`_${r}._sub.${e.type}${ka}`,type:"PTR",ttl:28800,data:`${e.name}.${e.type}${ka}`}}RecordSRV(e){return{name:e.fqdn,type:"SRV",ttl:120,data:{port:e.port,target:e.host}}}RecordTXT(e){return{name:e.fqdn,type:"TXT",ttl:4500,data:this.txtService.encode(e.txt)}}RecordA(e,r){return{name:e.host,type:"A",ttl:120,data:r}}RecordAAAA(e,r){return{name:e.host,type:"AAAA",ttl:120,data:r}}};Mn.Service=Ha;Mn.default=Ha});var ll=ve(Ln=>{"use strict";var ml=Ln&&Ln.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ln,"__esModule",{value:!0});Ln.Registry=void 0;var Hv=ml(Ca()),sp=ml(op()),Pv=3600*1e3,Tv=3,bv=i(function(){},"noop"),Pa=class{static{i(this,"Registry")}constructor(e){this.services=[],this.server=e}publish(e){function r(c,p,f){c.activated||(c.activated=!0,p.services.push(c),c instanceof sp.default&&(f?.probe?p.probe(p.server.mdns,c,l=>{if(l){c.stop!==void 0&&c.stop(),console.log(new Error("Service name is already in use on the network"));return}p.announce(p.server,c)}):p.announce(p.server,c)))}i(r,"start");function n(c,p,f){if(f||(f=bv),!c.activated||!(c instanceof sp.default))return process.nextTick(f);p.teardown(p.server,c,f);let l=p.services.indexOf(c);l!==-1&&p.services.splice(l,1)}i(n,"stop");let a=new sp.default(e);return a.start=r.bind(null,a,this),a.stop=n.bind(null,a,this),a.start({probe:e.probe!==!1}),a}unpublishAll(e){this.teardown(this.server,this.services,e),this.services=[]}destroy(){this.services.map(e=>e.destroyed=!0)}probe(e,r,n){var a=!1,c=0,p;let f=i(()=>{!r.activated||r.destroyed||e.query(r.fqdn,"ANY",function(){a=!0,p=setTimeout(++c<3?f:y,250),p.unref()})},"send"),l=i(g=>{a&&(g.answers.some(m)||g.additionals.some(m))&&y(!0)},"onresponse"),m=i(g=>(0,Hv.default)(g.name,r.fqdn),"matchRR"),y=i(g=>{e.removeListener("response",l),clearTimeout(p),n(!!g)},"done");e.on("response",l),setTimeout(f,Math.random()*250)}announce(e,r){var n=1e3,a=r.records();e.register(a);let c=i(()=>{!r.activated||r.destroyed||e.mdns.respond(a,function(){r.published||(r.activated=!0,r.published=!0,r.emit("up")),n=n*Tv,n<Pv&&!r.destroyed&&setTimeout(c,n).unref()})},"broadcast");c()}teardown(e,r,n){Array.isArray(r)||(r=[r]),r=r.filter(c=>c.activated);var a=r.flatMap(function(c){c.activated=!1;var p=c.records();return p.forEach(f=>{f.ttl=0}),p});if(a.length===0)return n&&process.nextTick(n);e.unregister(a),e.mdns.respond(a,function(){r.forEach(function(c){c.published=!1}),typeof n=="function"&&n.apply(null,arguments)})}};Ln.Registry=Pa;Ln.default=Pa});var fl=ve(ip=>{"use strict";ip.toString=function(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t};ip.toType=function(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}});var yl=ve(ap=>{"use strict";ap.toString=function(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t};ap.toRcode=function(t){switch(t.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var gl=ve(cp=>{"use strict";cp.toString=function(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t};cp.toOpcode=function(t){switch(t.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var hl=ve(pp=>{"use strict";pp.toString=function(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t};pp.toClass=function(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var Sl=ve(dp=>{"use strict";dp.toString=function(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`};dp.toCode=function(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var Al=ve((El,up)=>{var vl=(function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=g,t.encode=y,t.familyOf=m,t.name=void 0,t.sizeOf=l,t.v6=t.v4=void 0;let e=/^(\d{1,3}\.){3,3}\d{1,3}$/,r=4,n=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,a=16,c={name:"v4",size:r,isFormat:i(E=>e.test(E),"isFormat"),encode(E,v,h){h=~~h,v=v||new Uint8Array(h+r);let w=E.length,C=0;for(let R=0;R<w;){let b=E.charCodeAt(R++);b===46?(v[h++]=C,C=0):C=C*10+(b-48)}return v[h]=C,v},decode(E,v){return v=~~v,`${E[v++]}.${E[v++]}.${E[v++]}.${E[v]}`}};t.v4=c;let p={name:"v6",size:a,isFormat:i(E=>E.length>0&&n.test(E),"isFormat"),encode(E,v,h){h=~~h;let w=h+a,C=-1,R=0,b=0,O=!0,Z=!1;v=v||new Uint8Array(h+a);for(let Se=0;Se<E.length;Se++){let Re=E.charCodeAt(Se);Re===58?(O?C!==-1?(h<w&&(v[h]=0),h<w-1&&(v[h+1]=0),h+=2):h<w&&(C=h):(Z===!0?(h<w&&(v[h]=b),h++):(h<w&&(v[h]=R>>8),h<w-1&&(v[h+1]=R&255),h+=2),R=0,b=0),O=!0,Z=!1):Re===46?(h<w&&(v[h]=b),h++,b=0,R=0,O=!1,Z=!0):(O=!1,Re>=97?Re-=87:Re>=65?Re-=55:(Re-=48,b=b*10+Re),R=(R<<4)+Re)}if(O===!1)Z===!0?(h<w&&(v[h]=b),h++):(h<w&&(v[h]=R>>8),h<w-1&&(v[h+1]=R&255),h+=2);else if(C===0)h<w&&(v[h]=0),h<w-1&&(v[h+1]=0),h+=2;else if(C!==-1){h+=2;for(let Se=Math.min(h-1,w-1);Se>=C+2;Se--)v[Se]=v[Se-2];v[C]=0,v[C+1]=0,C=h}if(C!==h&&C!==-1)for(h>w-2&&(h=w-2);w>C;)v[--w]=h<w&&h>C?v[--h]:0;else for(;h<w;)v[h++]=0;return v},decode(E,v){v=~~v;let h="";for(let w=0;w<a;w+=2)w!==0&&(h+=":"),h+=(E[v+w]<<8|E[v+w+1]).toString(16);return h.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};t.v6=p;let f="ip";t.name=f;function l(E){if(c.isFormat(E))return c.size;if(p.isFormat(E))return p.size;throw Error(`Invalid ip address: ${E}`)}i(l,"sizeOf");function m(E){return l(E)===c.size?1:2}i(m,"familyOf");function y(E,v,h){h=~~h;let w=l(E);return typeof v=="function"&&(v=v(h+w)),w===c.size?c.encode(E,v,h):p.encode(E,v,h)}i(y,"encode");function g(E,v,h){if(v=~~v,h=h||E.length-v,h===c.size)return c.decode(E,v,h);if(h===p.size)return p.decode(E,v,h);throw Error(`Invalid buffer size needs to be ${c.size} for v4 or ${p.size} for v6.`)}return i(g,"decode"),"default"in t?t.default:t})({});typeof define=="function"&&define.amd?define([],function(){return vl}):typeof up=="object"&&typeof El=="object"&&(up.exports=vl)});var Dl=ve(M=>{"use strict";var L=gn("buffer").Buffer,Rr=fl(),qv=yl(),Ov=gl(),ba=hl(),mp=Sl(),Un=Al(),Mv=0,Il=32768,lp=32768,Lv=~lp,wl=32768,Uv=~wl,T=M.name={};T.encode=function(t,e,r,{mail:n=!1}={}){e||(e=L.alloc(T.encodingLength(t))),r||(r=0);let a=r,c=t.replace(/^\.|\.$/gm,"");if(c.length){let p=[];if(n){let f="";c.split(".").forEach(l=>{l.endsWith("\\")?f+=(f.length?".":"")+l.slice(0,-1):p.length===0&&f.length?p.push(f+"."+l):p.push(l)})}else p=c.split(".");for(let f=0;f<p.length;f++){let l=e.write(p[f],r+1);e[r]=l,r+=l+1}}return e[r++]=0,T.encode.bytes=r-a,e};T.encode.bytes=0;T.decode=function(t,e,{mail:r=!1}={}){e||(e=0);let n=[],a=e,c=0,p=0,f=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let l=t[e++];if(p+=f?0:1,l===0)break;if((l&192)===0){if(e+l>t.length)throw new Error("Cannot decode name (buffer overflow)");if(c+=l+1,c>254)throw new Error("Cannot decode name (name too long)");let m=t.toString("utf-8",e,e+l);r&&(m=m.replace(/\./g,"\\.")),n.push(m),e+=l,p+=f?0:l}else if((l&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let m=t.readUInt16BE(e-1)-49152;if(m>=a)throw new Error("Cannot decode name (bad pointer)");e=m,a=m,p+=f?0:1,f=!0}else throw new Error("Cannot decode name (bad label)")}return T.decode.bytes=p,n.length===0?".":n.join(".")};T.decode.bytes=0;T.encodingLength=function(t){return t==="."||t===".."?1:L.byteLength(t.replace(/^\.|\.$/gm,""))+2};var G={};G.encode=function(t,e,r){e||(e=L.alloc(G.encodingLength(t))),r||(r=0);let n=e.write(t,r+1);return e[r]=n,G.encode.bytes=n+1,e};G.encode.bytes=0;G.decode=function(t,e){e||(e=0);let r=t[e],n=t.toString("utf-8",e+1,e+1+r);return G.decode.bytes=r+1,n};G.decode.bytes=0;G.encodingLength=function(t){return L.byteLength(t)+1};var qt={};qt.encode=function(t,e,r){e||(e=qt.encodingLength(t)),r||(r=0);let n=(t.flags||0)&32767,a=t.type==="response"?Il:Mv;return e.writeUInt16BE(t.id||0,r),e.writeUInt16BE(n|a,r+2),e.writeUInt16BE(t.questions.length,r+4),e.writeUInt16BE(t.answers.length,r+6),e.writeUInt16BE(t.authorities.length,r+8),e.writeUInt16BE(t.additionals.length,r+10),e};qt.encode.bytes=12;qt.decode=function(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=t.readUInt16BE(e+2);return{id:t.readUInt16BE(e),type:r&Il?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:Ov.toString(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:qv.toString(r&15),questions:new Array(t.readUInt16BE(e+4)),answers:new Array(t.readUInt16BE(e+6)),authorities:new Array(t.readUInt16BE(e+8)),additionals:new Array(t.readUInt16BE(e+10))}};qt.decode.bytes=12;qt.encodingLength=function(){return 12};var gr=M.unknown={};gr.encode=function(t,e,r){return e||(e=L.alloc(gr.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.length,r),t.copy(e,r+2),gr.encode.bytes=t.length+2,e};gr.encode.bytes=0;gr.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=t.slice(e+2,e+2+r);return gr.decode.bytes=r+2,n};gr.decode.bytes=0;gr.encodingLength=function(t){return t.length+2};var hr=M.ns={};hr.encode=function(t,e,r){return e||(e=L.alloc(hr.encodingLength(t))),r||(r=0),T.encode(t,e,r+2),e.writeUInt16BE(T.encode.bytes,r),hr.encode.bytes=T.encode.bytes+2,e};hr.encode.bytes=0;hr.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=T.decode(t,e+2);return hr.decode.bytes=r+2,n};hr.decode.bytes=0;hr.encodingLength=function(t){return T.encodingLength(t)+2};var Sr=M.soa={};Sr.encode=function(t,e,r){e||(e=L.alloc(Sr.encodingLength(t))),r||(r=0);let n=r;return r+=2,T.encode(t.mname,e,r),r+=T.encode.bytes,T.encode(t.rname,e,r,{mail:!0}),r+=T.encode.bytes,e.writeUInt32BE(t.serial||0,r),r+=4,e.writeUInt32BE(t.refresh||0,r),r+=4,e.writeUInt32BE(t.retry||0,r),r+=4,e.writeUInt32BE(t.expire||0,r),r+=4,e.writeUInt32BE(t.minimum||0,r),r+=4,e.writeUInt16BE(r-n-2,n),Sr.encode.bytes=r-n,e};Sr.encode.bytes=0;Sr.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=T.decode(t,e),e+=T.decode.bytes,n.rname=T.decode(t,e,{mail:!0}),e+=T.decode.bytes,n.serial=t.readUInt32BE(e),e+=4,n.refresh=t.readUInt32BE(e),e+=4,n.retry=t.readUInt32BE(e),e+=4,n.expire=t.readUInt32BE(e),e+=4,n.minimum=t.readUInt32BE(e),e+=4,Sr.decode.bytes=e-r,n};Sr.decode.bytes=0;Sr.encodingLength=function(t){return 22+T.encodingLength(t.mname)+T.encodingLength(t.rname)};var vr=M.txt={};vr.encode=function(t,e,r){Array.isArray(t)||(t=[t]);for(let a=0;a<t.length;a++)if(typeof t[a]=="string"&&(t[a]=L.from(t[a])),!L.isBuffer(t[a]))throw new Error("Must be a Buffer");e||(e=L.alloc(vr.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(a){e[r++]=a.length,a.copy(e,r,0,a.length),r+=a.length}),e.writeUInt16BE(r-n-2,n),vr.encode.bytes=r-n,e};vr.encode.bytes=0;vr.decode=function(t,e){e||(e=0);let r=e,n=t.readUInt16BE(e);e+=2;let a=[];for(;n>0;){let c=t[e++];if(--n,n<c)throw new Error("Buffer overflow");a.push(t.slice(e,e+c)),e+=c,n-=c}return vr.decode.bytes=e-r,a};vr.decode.bytes=0;vr.encodingLength=function(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=L.byteLength(r)+1:e+=r.length+1}),e};var Er=M.null={};Er.encode=function(t,e,r){e||(e=L.alloc(Er.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=L.from(t)),t||(t=L.alloc(0));let n=r;r+=2;let a=t.length;return t.copy(e,r,0,a),r+=a,e.writeUInt16BE(r-n-2,n),Er.encode.bytes=r-n,e};Er.encode.bytes=0;Er.decode=function(t,e){e||(e=0);let r=e,n=t.readUInt16BE(e);e+=2;let a=t.slice(e,e+n);return e+=n,Er.decode.bytes=e-r,a};Er.decode.bytes=0;Er.encodingLength=function(t){return t?(L.isBuffer(t)?t.length:L.byteLength(t))+2:2};var Ar=M.hinfo={};Ar.encode=function(t,e,r){e||(e=L.alloc(Ar.encodingLength(t))),r||(r=0);let n=r;return r+=2,G.encode(t.cpu,e,r),r+=G.encode.bytes,G.encode(t.os,e,r),r+=G.encode.bytes,e.writeUInt16BE(r-n-2,n),Ar.encode.bytes=r-n,e};Ar.encode.bytes=0;Ar.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=G.decode(t,e),e+=G.decode.bytes,n.os=G.decode(t,e),e+=G.decode.bytes,Ar.decode.bytes=e-r,n};Ar.decode.bytes=0;Ar.encodingLength=function(t){return G.encodingLength(t.cpu)+G.encodingLength(t.os)+2};var Tt=M.ptr={},Nv=M.cname=Tt,_v=M.dname=Tt;Tt.encode=function(t,e,r){return e||(e=L.alloc(Tt.encodingLength(t))),r||(r=0),T.encode(t,e,r+2),e.writeUInt16BE(T.encode.bytes,r),Tt.encode.bytes=T.encode.bytes+2,e};Tt.encode.bytes=0;Tt.decode=function(t,e){e||(e=0);let r=T.decode(t,e+2);return Tt.decode.bytes=T.decode.bytes+2,r};Tt.decode.bytes=0;Tt.encodingLength=function(t){return T.encodingLength(t)+2};var Ir=M.srv={};Ir.encode=function(t,e,r){e||(e=L.alloc(Ir.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.priority||0,r+2),e.writeUInt16BE(t.weight||0,r+4),e.writeUInt16BE(t.port||0,r+6),T.encode(t.target,e,r+8);let n=T.encode.bytes+6;return e.writeUInt16BE(n,r),Ir.encode.bytes=n+2,e};Ir.encode.bytes=0;Ir.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n={};return n.priority=t.readUInt16BE(e+2),n.weight=t.readUInt16BE(e+4),n.port=t.readUInt16BE(e+6),n.target=T.decode(t,e+8),Ir.decode.bytes=r+2,n};Ir.decode.bytes=0;Ir.encodingLength=function(t){return 8+T.encodingLength(t.target)};var pt=M.caa={};pt.ISSUER_CRITICAL=128;pt.encode=function(t,e,r){let n=pt.encodingLength(t);return e||(e=L.alloc(pt.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=pt.ISSUER_CRITICAL),e.writeUInt16BE(n-2,r),r+=2,e.writeUInt8(t.flags||0,r),r+=1,G.encode(t.tag,e,r),r+=G.encode.bytes,e.write(t.value,r),r+=L.byteLength(t.value),pt.encode.bytes=n,e};pt.encode.bytes=0;pt.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e);e+=2;let n=e,a={};return a.flags=t.readUInt8(e),e+=1,a.tag=G.decode(t,e),e+=G.decode.bytes,a.value=t.toString("utf-8",e,n+r),a.issuerCritical=!!(a.flags&pt.ISSUER_CRITICAL),pt.decode.bytes=r+2,a};pt.decode.bytes=0;pt.encodingLength=function(t){return G.encodingLength(t.tag)+G.encodingLength(t.value)+2};var on=M.mx={};on.encode=function(t,e,r){e||(e=L.alloc(on.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,T.encode(t.exchange,e,r),r+=T.encode.bytes,e.writeUInt16BE(r-n-2,n),on.encode.bytes=r-n,e};on.encode.bytes=0;on.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=t.readUInt16BE(e),e+=2,n.exchange=T.decode(t,e),e+=T.decode.bytes,on.decode.bytes=e-r,n};on.encodingLength=function(t){return 4+T.encodingLength(t.exchange)};var wr=M.a={};wr.encode=function(t,e,r){return e||(e=L.alloc(wr.encodingLength(t))),r||(r=0),e.writeUInt16BE(4,r),r+=2,Un.v4.encode(t,e,r),wr.encode.bytes=6,e};wr.encode.bytes=0;wr.decode=function(t,e){e||(e=0),e+=2;let r=Un.v4.decode(t,e);return wr.decode.bytes=6,r};wr.decode.bytes=0;wr.encodingLength=function(){return 6};var Dr=M.aaaa={};Dr.encode=function(t,e,r){return e||(e=L.alloc(Dr.encodingLength(t))),r||(r=0),e.writeUInt16BE(16,r),r+=2,Un.v6.encode(t,e,r),Dr.encode.bytes=18,e};Dr.encode.bytes=0;Dr.decode=function(t,e){e||(e=0),e+=2;let r=Un.v6.decode(t,e);return Dr.decode.bytes=18,r};Dr.decode.bytes=0;Dr.encodingLength=function(){return 18};var et=M.option={};et.encode=function(t,e,r){e||(e=L.alloc(et.encodingLength(t))),r||(r=0);let n=r,a=mp.toCode(t.code);if(e.writeUInt16BE(a,r),r+=2,t.data)e.writeUInt16BE(t.data.length,r),r+=2,t.data.copy(e,r),r+=t.data.length;else switch(a){case 8:let c=t.sourcePrefixLength||0,p=t.family||Un.familyOf(t.ip),f=Un.encode(t.ip,L.alloc),l=Math.ceil(c/8);e.writeUInt16BE(l+4,r),r+=2,e.writeUInt16BE(p,r),r+=2,e.writeUInt8(c,r++),e.writeUInt8(t.scopePrefixLength||0,r++),f.copy(e,r,0,l),r+=l;break;case 11:t.timeout?(e.writeUInt16BE(2,r),r+=2,e.writeUInt16BE(t.timeout,r),r+=2):(e.writeUInt16BE(0,r),r+=2);break;case 12:let m=t.length||0;e.writeUInt16BE(m,r),r+=2,e.fill(0,r,r+m),r+=m;break;case 14:let y=t.tags.length*2;e.writeUInt16BE(y,r),r+=2;for(let g of t.tags)e.writeUInt16BE(g,r),r+=2;break;default:throw new Error(`Unknown roption code: ${t.code}`)}return et.encode.bytes=r-n,e};et.encode.bytes=0;et.decode=function(t,e){e||(e=0);let r={};r.code=t.readUInt16BE(e),r.type=mp.toString(r.code),e+=2;let n=t.readUInt16BE(e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=t.readUInt16BE(e),e+=2,r.sourcePrefixLength=t.readUInt8(e++),r.scopePrefixLength=t.readUInt8(e++);let a=L.alloc(r.family===1?4:16);t.copy(a,0,e,e+n-4),r.ip=Un.decode(a);break;case 11:n>0&&(r.timeout=t.readUInt16BE(e),e+=2);break;case 14:r.tags=[];for(let c=0;c<n;c+=2)r.tags.push(t.readUInt16BE(e)),e+=2}return et.decode.bytes=n+4,r};et.decode.bytes=0;et.encodingLength=function(t){if(t.data)return t.data.length+4;switch(mp.toCode(t.code)){case 8:let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8;case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)};var ut=M.opt={};ut.encode=function(t,e,r){e||(e=L.alloc(ut.encodingLength(t))),r||(r=0);let n=r,a=xo(t,et);return e.writeUInt16BE(a,r),r=$s(t,et,e,r+2),ut.encode.bytes=r-n,e};ut.encode.bytes=0;ut.decode=function(t,e){e||(e=0);let r=e,n=[],a=t.readUInt16BE(e);e+=2;let c=0;for(;a>0;)n[c++]=et.decode(t,e),e+=et.decode.bytes,a-=et.decode.bytes;return ut.decode.bytes=e-r,n};ut.decode.bytes=0;ut.encodingLength=function(t){return 2+xo(t||[],et)};var We=M.dnskey={};We.PROTOCOL_DNSSEC=3;We.ZONE_KEY=128;We.SECURE_ENTRYPOINT=32768;We.encode=function(t,e,r){e||(e=L.alloc(We.encodingLength(t))),r||(r=0);let n=r,a=t.key;if(!L.isBuffer(a))throw new Error("Key must be a Buffer");return r+=2,e.writeUInt16BE(t.flags,r),r+=2,e.writeUInt8(We.PROTOCOL_DNSSEC,r),r+=1,e.writeUInt8(t.algorithm,r),r+=1,a.copy(e,r,0,a.length),r+=a.length,We.encode.bytes=r-n,e.writeUInt16BE(We.encode.bytes-2,n),e};We.encode.bytes=0;We.decode=function(t,e){e||(e=0);let r=e;var n={},a=t.readUInt16BE(e);if(e+=2,n.flags=t.readUInt16BE(e),e+=2,t.readUInt8(e)!==We.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t.readUInt8(e),e+=1,n.key=t.slice(e,r+a+2),e+=n.key.length,We.decode.bytes=e-r,n};We.decode.bytes=0;We.encodingLength=function(t){return 6+L.byteLength(t.key)};var Yt=M.rrsig={};Yt.encode=function(t,e,r){e||(e=L.alloc(Yt.encodingLength(t))),r||(r=0);let n=r,a=t.signature;if(!L.isBuffer(a))throw new Error("Signature must be a Buffer");return r+=2,e.writeUInt16BE(Rr.toType(t.typeCovered),r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.labels,r),r+=1,e.writeUInt32BE(t.originalTTL,r),r+=4,e.writeUInt32BE(t.expiration,r),r+=4,e.writeUInt32BE(t.inception,r),r+=4,e.writeUInt16BE(t.keyTag,r),r+=2,T.encode(t.signersName,e,r),r+=T.encode.bytes,a.copy(e,r,0,a.length),r+=a.length,Yt.encode.bytes=r-n,e.writeUInt16BE(Yt.encode.bytes-2,n),e};Yt.encode.bytes=0;Yt.decode=function(t,e){e||(e=0);let r=e;var n={},a=t.readUInt16BE(e);return e+=2,n.typeCovered=Rr.toString(t.readUInt16BE(e)),e+=2,n.algorithm=t.readUInt8(e),e+=1,n.labels=t.readUInt8(e),e+=1,n.originalTTL=t.readUInt32BE(e),e+=4,n.expiration=t.readUInt32BE(e),e+=4,n.inception=t.readUInt32BE(e),e+=4,n.keyTag=t.readUInt16BE(e),e+=2,n.signersName=T.decode(t,e),e+=T.decode.bytes,n.signature=t.slice(e,r+a+2),e+=n.signature.length,Yt.decode.bytes=e-r,n};Yt.decode.bytes=0;Yt.encodingLength=function(t){return 20+T.encodingLength(t.signersName)+L.byteLength(t.signature)};var Kt=M.rp={};Kt.encode=function(t,e,r){e||(e=L.alloc(Kt.encodingLength(t))),r||(r=0);let n=r;return r+=2,T.encode(t.mbox||".",e,r,{mail:!0}),r+=T.encode.bytes,T.encode(t.txt||".",e,r),r+=T.encode.bytes,Kt.encode.bytes=r-n,e.writeUInt16BE(Kt.encode.bytes-2,n),e};Kt.encode.bytes=0;Kt.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=T.decode(t,e,{mail:!0})||".",e+=T.decode.bytes,n.txt=T.decode(t,e)||".",e+=T.decode.bytes,Kt.decode.bytes=e-r,n};Kt.decode.bytes=0;Kt.encodingLength=function(t){return 2+T.encodingLength(t.mbox||".")+T.encodingLength(t.txt||".")};var He={};He.encode=function(t,e,r){e||(e=L.alloc(He.encodingLength(t))),r||(r=0);let n=r;for(var a=[],c=0;c<t.length;c++){var p=Rr.toType(t[c]);a[p>>8]===void 0&&(a[p>>8]=[]),a[p>>8][p>>3&31]|=1<<7-(p&7)}for(c=0;c<a.length;c++)if(a[c]!==void 0){var f=L.from(a[c]);e.writeUInt8(c,r),r+=1,e.writeUInt8(f.length,r),r+=1,f.copy(e,r),r+=f.length}return He.encode.bytes=r-n,e};He.encode.bytes=0;He.decode=function(t,e,r){e||(e=0);let n=e;for(var a=[];e-n<r;){var c=t.readUInt8(e);e+=1;var p=t.readUInt8(e);e+=1;for(var f=0;f<p;f++)for(var l=t.readUInt8(e+f),m=0;m<8;m++)if(l&1<<7-m){var y=Rr.toString(c<<8|f<<3|m);a.push(y)}e+=p}return He.decode.bytes=e-n,a};He.decode.bytes=0;He.encodingLength=function(t){for(var e=[],r=0;r<t.length;r++){var n=Rr.toType(t[r]);e[n>>8]=Math.max(e[n>>8]||0,n&255)}var a=0;for(r=0;r<e.length;r++)e[r]!==void 0&&(a+=2+Math.ceil((e[r]+1)/8));return a};var Xt=M.nsec={};Xt.encode=function(t,e,r){e||(e=L.alloc(Xt.encodingLength(t))),r||(r=0);let n=r;return r+=2,T.encode(t.nextDomain,e,r),r+=T.encode.bytes,He.encode(t.rrtypes,e,r),r+=He.encode.bytes,Xt.encode.bytes=r-n,e.writeUInt16BE(Xt.encode.bytes-2,n),e};Xt.encode.bytes=0;Xt.decode=function(t,e){e||(e=0);let r=e;var n={},a=t.readUInt16BE(e);return e+=2,n.nextDomain=T.decode(t,e),e+=T.decode.bytes,n.rrtypes=He.decode(t,e,a-(e-r)),e+=He.decode.bytes,Xt.decode.bytes=e-r,n};Xt.decode.bytes=0;Xt.encodingLength=function(t){return 2+T.encodingLength(t.nextDomain)+He.encodingLength(t.rrtypes)};var Jt=M.nsec3={};Jt.encode=function(t,e,r){e||(e=L.alloc(Jt.encodingLength(t))),r||(r=0);let n=r,a=t.salt;if(!L.isBuffer(a))throw new Error("salt must be a Buffer");let c=t.nextDomain;if(!L.isBuffer(c))throw new Error("nextDomain must be a Buffer");return r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.flags,r),r+=1,e.writeUInt16BE(t.iterations,r),r+=2,e.writeUInt8(a.length,r),r+=1,a.copy(e,r,0,a.length),r+=a.length,e.writeUInt8(c.length,r),r+=1,c.copy(e,r,0,c.length),r+=c.length,He.encode(t.rrtypes,e,r),r+=He.encode.bytes,Jt.encode.bytes=r-n,e.writeUInt16BE(Jt.encode.bytes-2,n),e};Jt.encode.bytes=0;Jt.decode=function(t,e){e||(e=0);let r=e;var n={},a=t.readUInt16BE(e);e+=2,n.algorithm=t.readUInt8(e),e+=1,n.flags=t.readUInt8(e),e+=1,n.iterations=t.readUInt16BE(e),e+=2;let c=t.readUInt8(e);e+=1,n.salt=t.slice(e,e+c),e+=c;let p=t.readUInt8(e);return e+=1,n.nextDomain=t.slice(e,e+p),e+=p,n.rrtypes=He.decode(t,e,a-(e-r)),e+=He.decode.bytes,Jt.decode.bytes=e-r,n};Jt.decode.bytes=0;Jt.encodingLength=function(t){return 8+t.salt.length+t.nextDomain.length+He.encodingLength(t.rrtypes)};var Zt=M.ds={};Zt.encode=function(t,e,r){e||(e=L.alloc(Zt.encodingLength(t))),r||(r=0);let n=r,a=t.digest;if(!L.isBuffer(a))throw new Error("Digest must be a Buffer");return r+=2,e.writeUInt16BE(t.keyTag,r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.digestType,r),r+=1,a.copy(e,r,0,a.length),r+=a.length,Zt.encode.bytes=r-n,e.writeUInt16BE(Zt.encode.bytes-2,n),e};Zt.encode.bytes=0;Zt.decode=function(t,e){e||(e=0);let r=e;var n={},a=t.readUInt16BE(e);return e+=2,n.keyTag=t.readUInt16BE(e),e+=2,n.algorithm=t.readUInt8(e),e+=1,n.digestType=t.readUInt8(e),e+=1,n.digest=t.slice(e,r+a+2),e+=n.digest.length,Zt.decode.bytes=e-r,n};Zt.decode.bytes=0;Zt.encodingLength=function(t){return 6+L.byteLength(t.digest)};var dt=M.sshfp={};dt.getFingerprintLengthForHashType=i(function(e){switch(e){case 1:return 20;case 2:return 32}},"getFingerprintLengthForHashType");dt.encode=i(function(e,r,n){r||(r=L.alloc(dt.encodingLength(e))),n||(n=0);let a=n;n+=2,r[n]=e.algorithm,n+=1,r[n]=e.hash,n+=1;let c=L.from(e.fingerprint.toUpperCase(),"hex");if(c.length!==dt.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return c.copy(r,n),n+=c.byteLength,dt.encode.bytes=n-a,r.writeUInt16BE(dt.encode.bytes-2,a),r},"encode");dt.encode.bytes=0;dt.decode=i(function(e,r){r||(r=0);let n=r,a={};r+=2,a.algorithm=e[r],r+=1,a.hash=e[r],r+=1;let c=dt.getFingerprintLengthForHashType(a.hash);return a.fingerprint=e.slice(r,r+c).toString("hex").toUpperCase(),r+=c,dt.decode.bytes=r-n,a},"decode");dt.decode.bytes=0;dt.encodingLength=function(t){return 4+L.from(t.fingerprint,"hex").byteLength};var er=M.naptr={};er.encode=function(t,e,r){e||(e=L.alloc(er.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.order||0,r),r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,G.encode(t.flags,e,r),r+=G.encode.bytes,G.encode(t.services,e,r),r+=G.encode.bytes,G.encode(t.regexp,e,r),r+=G.encode.bytes,T.encode(t.replacement,e,r),r+=T.encode.bytes,er.encode.bytes=r-n,e.writeUInt16BE(er.encode.bytes-2,n),e};er.encode.bytes=0;er.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.order=t.readUInt16BE(e),e+=2,n.preference=t.readUInt16BE(e),e+=2,n.flags=G.decode(t,e),e+=G.decode.bytes,n.services=G.decode(t,e),e+=G.decode.bytes,n.regexp=G.decode(t,e),e+=G.decode.bytes,n.replacement=T.decode(t,e),e+=T.decode.bytes,er.decode.bytes=e-r,n};er.decode.bytes=0;er.encodingLength=function(t){return G.encodingLength(t.flags)+G.encodingLength(t.services)+G.encodingLength(t.regexp)+T.encodingLength(t.replacement)+6};var tr=M.tlsa={};tr.encode=function(t,e,r){e||(e=L.alloc(tr.encodingLength(t))),r||(r=0);let n=r,a=t.certificate;if(!L.isBuffer(a))throw new Error("Certificate must be a Buffer");return r+=2,e.writeUInt8(t.usage,r),r+=1,e.writeUInt8(t.selector,r),r+=1,e.writeUInt8(t.matchingType,r),r+=1,a.copy(e,r,0,a.length),r+=a.length,tr.encode.bytes=r-n,e.writeUInt16BE(tr.encode.bytes-2,n),e};tr.encode.bytes=0;tr.decode=function(t,e){e||(e=0);let r=e,n={},a=t.readUInt16BE(e);return e+=2,n.usage=t.readUInt8(e),e+=1,n.selector=t.readUInt8(e),e+=1,n.matchingType=t.readUInt8(e),e+=1,n.certificate=t.slice(e,r+a+2),e+=n.certificate.length,tr.decode.bytes=e-r,n};tr.decode.bytes=0;tr.encodingLength=function(t){return 5+L.byteLength(t.certificate)};var fp=M.record=function(t){switch(t.toUpperCase()){case"A":return wr;case"PTR":return Tt;case"CNAME":return Nv;case"DNAME":return _v;case"TXT":return vr;case"NULL":return Er;case"AAAA":return Dr;case"SRV":return Ir;case"HINFO":return Ar;case"CAA":return pt;case"NS":return hr;case"SOA":return Sr;case"MX":return on;case"OPT":return ut;case"DNSKEY":return We;case"RRSIG":return Yt;case"RP":return Kt;case"NSEC":return Xt;case"NSEC3":return Jt;case"SSHFP":return dt;case"DS":return Zt;case"NAPTR":return er;case"TLSA":return tr}return gr},Me=M.answer={};Me.encode=function(t,e,r){e||(e=L.alloc(Me.encodingLength(t))),r||(r=0);let n=r;if(T.encode(t.name,e,r),r+=T.encode.bytes,e.writeUInt16BE(Rr.toType(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(t.udpPayloadSize||4096,r+2),e.writeUInt8(t.extendedRcode||0,r+4),e.writeUInt8(t.ednsVersion||0,r+5),e.writeUInt16BE(t.flags||0,r+6),r+=8,ut.encode(t.options||[],e,r),r+=ut.encode.bytes}else{let a=ba.toClass(t.class===void 0?"IN":t.class);t.flush&&(a|=lp),e.writeUInt16BE(a,r+2),e.writeUInt32BE(t.ttl||0,r+4),r+=8;let c=fp(t.type);c.encode(t.data,e,r),r+=c.encode.bytes}return Me.encode.bytes=r-n,e};Me.encode.bytes=0;Me.decode=function(t,e){e||(e=0);let r={},n=e;if(r.name=T.decode(t,e),e+=T.decode.bytes,r.type=Rr.toString(t.readUInt16BE(e)),r.type==="OPT")r.udpPayloadSize=t.readUInt16BE(e+2),r.extendedRcode=t.readUInt8(e+4),r.ednsVersion=t.readUInt8(e+5),r.flags=t.readUInt16BE(e+6),r.flag_do=(r.flags>>15&1)===1,r.options=ut.decode(t,e+8),e+=8+ut.decode.bytes;else{let a=t.readUInt16BE(e+2);r.ttl=t.readUInt32BE(e+4),r.class=ba.toString(a&Lv),r.flush=!!(a&lp);let c=fp(r.type);r.data=c.decode(t,e+8),e+=8+c.decode.bytes}return Me.decode.bytes=e-n,r};Me.decode.bytes=0;Me.encodingLength=function(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return T.encodingLength(t.name)+8+fp(t.type).encodingLength(e)};var bt=M.question={};bt.encode=function(t,e,r){e||(e=L.alloc(bt.encodingLength(t))),r||(r=0);let n=r;return T.encode(t.name,e,r),r+=T.encode.bytes,e.writeUInt16BE(Rr.toType(t.type),r),r+=2,e.writeUInt16BE(ba.toClass(t.class===void 0?"IN":t.class),r),r+=2,bt.encode.bytes=r-n,t};bt.encode.bytes=0;bt.decode=function(t,e){e||(e=0);let r=e,n={};return n.name=T.decode(t,e),e+=T.decode.bytes,n.type=Rr.toString(t.readUInt16BE(e)),e+=2,n.class=ba.toString(t.readUInt16BE(e)),e+=2,n.class&wl&&(n.class&=Uv),bt.decode.bytes=e-r,n};bt.decode.bytes=0;bt.encodingLength=function(t){return T.encodingLength(t.name)+4};M.AUTHORITATIVE_ANSWER=1024;M.TRUNCATED_RESPONSE=512;M.RECURSION_DESIRED=256;M.RECURSION_AVAILABLE=128;M.AUTHENTIC_DATA=32;M.CHECKING_DISABLED=16;M.DNSSEC_OK=32768;M.encode=function(t,e,r){let n=!e;n&&(e=L.alloc(M.encodingLength(t))),r||(r=0);let a=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),qt.encode(t,e,r),r+=qt.encode.bytes,r=$s(t.questions,bt,e,r),r=$s(t.answers,Me,e,r),r=$s(t.authorities,Me,e,r),r=$s(t.additionals,Me,e,r),M.encode.bytes=r-a,n&&M.encode.bytes!==e.length?e.slice(0,M.encode.bytes):e};M.encode.bytes=0;M.decode=function(t,e){e||(e=0);let r=e,n=qt.decode(t,e);return e+=qt.decode.bytes,e=Ta(n.questions,bt,t,e),e=Ta(n.answers,Me,t,e),e=Ta(n.authorities,Me,t,e),e=Ta(n.additionals,Me,t,e),M.decode.bytes=e-r,n};M.decode.bytes=0;M.encodingLength=function(t){return qt.encodingLength(t)+xo(t.questions||[],bt)+xo(t.answers||[],Me)+xo(t.authorities||[],Me)+xo(t.additionals||[],Me)};M.streamEncode=function(t){let e=M.encode(t),r=L.alloc(2);r.writeUInt16BE(e.byteLength);let n=L.concat([r,e]);return M.streamEncode.bytes=n.byteLength,n};M.streamEncode.bytes=0;M.streamDecode=function(t){let e=t.readUInt16BE(0);if(t.byteLength<e+2)return null;let r=M.decode(t.slice(2));return M.streamDecode.bytes=M.decode.bytes,r};M.streamDecode.bytes=0;function xo(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}i(xo,"encodingLengthList");function $s(t,e,r,n){for(let a=0;a<t.length;a++)e.encode(t[a],r,n),n+=e.encode.bytes;return n}i($s,"encodeList");function Ta(t,e,r,n){for(let a=0;a<t.length;a++)t[a]=e.decode(r,n),n+=e.decode.bytes;return n}i(Ta,"decodeList")});var xl=ve((CC,Cl)=>{"use strict";var Rl=$v;process.nextTick(Wv,42);Cl.exports=Bv;function Bv(t){var e=n;return r;function r(a){e(a||jv)}function n(a){var c=[a];e=p,t(f);function p(l){c.push(l)}i(p,"wait");function f(l){var m=arguments;for(e=Fv(l)?n:y;c.length;)y(c.shift());function y(g){Rl(Gv,g,m)}i(y,"finished")}i(f,"done")}}i(Bv,"thunky");function Fv(t){return Object.prototype.toString.call(t)==="[object Error]"}i(Fv,"isError");function jv(){}i(jv,"noop");function Gv(t,e){t.apply(null,e)}i(Gv,"apply");function Wv(t){t===42&&(Rl=process.nextTick)}i(Wv,"upgrade");function $v(t,e,r){process.nextTick(function(){t(e,r)})}i($v,"nextTickArgs")});var Pl=ve((kC,Hl)=>{var yp=Dl(),Vv=gn("dgram"),zv=xl(),Qv=gn("events"),hp=gn("os"),gp=i(function(){},"noop");Hl.exports=function(t){t||(t={});var e=new Qv.EventEmitter,r=typeof t.port=="number"?t.port:5353,n=t.type||"udp4",a=t.ip||t.host||(n==="udp4"?"224.0.0.251":null),c={address:a,port:r},p={},f=!1,l=null;if(n==="udp6"&&(!a||!t.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var m=t.socket||Vv.createSocket({type:n,reuseAddr:t.reuseAddr!==!1,toString:i(function(){return n},"toString")});m.on("error",function(g){g.code==="EACCES"||g.code==="EADDRINUSE"?e.emit("error",g):e.emit("warning",g)}),m.on("message",function(g,E){try{g=yp.decode(g)}catch(v){e.emit("warning",v);return}e.emit("packet",g,E),g.type==="query"&&e.emit("query",g,E),g.type==="response"&&e.emit("response",g,E)}),m.on("listening",function(){r||(r=c.port=m.address().port),t.multicast!==!1&&(e.update(),l=setInterval(e.update,5e3),m.setMulticastTTL(t.ttl||255),m.setMulticastLoopback(t.loopback!==!1))});var y=zv(function(g){if(!r||t.bind===!1)return g(null);m.once("error",g),m.bind(r,t.bind||t.interface,function(){m.removeListener("error",g),g(null)})});return y(function(g){if(g)return e.emit("error",g);e.emit("ready")}),e.send=function(g,E,v){if(typeof E=="function")return e.send(g,null,E);v||(v=gp),E?!E.host&&!E.address&&(E.address=c.address):E=c,y(h);function h(w){if(f)return v();if(w)return v(w);var C=yp.encode(g);m.send(C,0,C.length,E.port,E.address||E.host,v)}i(h,"onbind")},e.response=e.respond=function(g,E,v){Array.isArray(g)&&(g={answers:g}),g.type="response",g.flags=(g.flags||0)|yp.AUTHORITATIVE_ANSWER,e.send(g,E,v)},e.query=function(g,E,v,h){if(typeof E=="function")return e.query(g,null,null,E);if(typeof E=="object"&&E&&E.port)return e.query(g,null,E,v);if(typeof v=="function")return e.query(g,E,null,v);h||(h=gp),typeof g=="string"&&(g=[{name:g,type:E||"ANY"}]),Array.isArray(g)&&(g={type:"query",questions:g}),g.type="query",e.send(g,v,h)},e.destroy=function(g){if(g||(g=gp),f)return process.nextTick(g);f=!0,clearInterval(l);for(var E in p)try{m.dropMembership(a,E)}catch{}p={},m.close(g)},e.update=function(){for(var g=t.interface?[].concat(t.interface):Kv(),E=!1,v=0;v<g.length;v++){var h=g[v];if(!p[h])try{m.addMembership(a,h),p[h]=!0,E=!0}catch(w){e.emit("warning",w)}}if(E){if(m.setMulticastInterface)try{m.setMulticastInterface(t.interface||Yv())}catch(w){e.emit("warning",w)}e.emit("networkInterface")}},e};function Yv(){for(var t=hp.networkInterfaces(),e=Object.keys(t),r=0;r<e.length;r++)for(var n=t[e[r]],a=0;a<n.length;a++){var c=n[a];if(kl(c.family)&&!c.internal)return hp.platform()==="darwin"&&e[r]==="en0"?c.address:"0.0.0.0"}return"127.0.0.1"}i(Yv,"defaultInterface");function Kv(){for(var t=hp.networkInterfaces(),e=Object.keys(t),r=[],n=0;n<e.length;n++)for(var a=t[e[n]],c=0;c<a.length;c++){var p=a[c];if(kl(p.family)){r.push(p.address);break}}return r}i(Kv,"allInterfaces");function kl(t){return t===4||t==="IPv4"}i(kl,"isIPv4")});var bl=ve((PC,Tl)=>{"use strict";Tl.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,a,c;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!t(e[a],r[a]))return!1;return!0}if(e instanceof Map&&r instanceof Map){if(e.size!==r.size)return!1;for(a of e.entries())if(!r.has(a[0]))return!1;for(a of e.entries())if(!t(a[1],r.get(a[0])))return!1;return!0}if(e instanceof Set&&r instanceof Set){if(e.size!==r.size)return!1;for(a of e.entries())if(!r.has(a[0]))return!1;return!0}if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(r)){if(n=e.length,n!=r.length)return!1;for(a=n;a--!==0;)if(e[a]!==r[a])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(c=Object.keys(e),n=c.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,c[a]))return!1;for(a=n;a--!==0;){var p=c[a];if(!t(e[p],r[p]))return!1}return!0}return e!==e&&r!==r},"equal")});var ql=ve(Nn=>{"use strict";var Sp=Nn&&Nn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nn,"__esModule",{value:!0});Nn.Server=void 0;var Xv=Sp(Pl()),Jv=Sp(bl()),Zv=Sp(Ca()),qa=class{static{i(this,"Server")}constructor(e,r){this.registry={},this.mdns=(0,Xv.default)(e),this.mdns.setMaxListeners(0),this.mdns.on("query",this.respondToQuery.bind(this)),this.errorCallback=r??function(n){throw n}}register(e){let r=i(n=>{var a=this.registry[n.type];if(!a)a=this.registry[n.type]=[];else if(a.some(this.isDuplicateRecord(n)))return;a.push(n)},"shouldRegister");Array.isArray(e)?e.forEach(r):r(e)}unregister(e){let r=i(n=>{let a=n.type;a in this.registry&&(this.registry[a]=this.registry[a].filter(c=>c.name!==n.name))},"shouldUnregister");Array.isArray(e)?e.forEach(r):r(e)}respondToQuery(e){let r=this;e.questions.forEach(n=>{var a=n.type,c=n.name,p=a==="ANY"?Object.keys(r.registry).map(r.recordsFor.bind(r,c)).flat(1):r.recordsFor(c,a);if(p.length!==0){var f=[];a!=="ANY"&&(p.forEach(l=>{l.type==="PTR"&&(f=f.concat(r.recordsFor(l.data,"SRV")).concat(r.recordsFor(l.data,"TXT")))}),f.filter(function(l){return l.type==="SRV"}).map(function(l){return l.data.target}).filter(this.unique()).forEach(function(l){f=f.concat(r.recordsFor(l,"A")).concat(r.recordsFor(l,"AAAA"))})),r.mdns.respond({answers:p,additionals:f},l=>{l&&this.errorCallback(l)})}})}recordsFor(e,r){return r in this.registry?this.registry[r].filter(n=>{var a=~e.indexOf(".")?n.name:n.name.split(".")[0];return(0,Zv.default)(a,e)}):[]}isDuplicateRecord(e){return r=>e.type===r.type&&e.name===r.name&&(0,Jv.default)(e.data,r.data)}unique(){var e=[];return r=>~e.indexOf(r)?!1:(e.push(r),!0)}};Nn.Server=qa;Nn.default=qa});var Ol=ve(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});vp.default=(t,e)=>{if(e===void 0)return!0;let r=t.txt,n=Object.entries(e).map(([a,c])=>{let p=r[a];return!(p===void 0||c!=p)});return n.length==0?!0:!n.includes(!1)}});var Ml=ve(Ep=>{"use strict";Object.defineProperty(Ep,"__esModule",{value:!0});Ep.default=t=>Object.keys(t).filter(e=>!e.includes("binary")).reduce((e,r)=>Object.assign(e,{[r]:t[r]}),{})});var Ll=ve(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});Ap.default=eE;function eE(t,e){if(t===void 0||e===void 0)return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!=n.length)return!1;for(let a of r)if(t[a]!=e[a])return!1;return!0}i(eE,"equalTxt")});var _l=ve(_n=>{"use strict";var Vs=_n&&_n.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_n,"__esModule",{value:!0});_n.Browser=void 0;var tE=Vs(rp()),sn=Vs(Ca()),rE=gn("events"),Ip=np(),Ul=Vs(Ol()),nE=Vs(Ml()),oE=Vs(Ll()),Nl=".local",sE="_services._dns-sd._udp"+Nl,Oa=class t extends rE.EventEmitter{static{i(this,"Browser")}constructor(e,r,n){if(super(),this.onresponse=void 0,this.serviceMap={},this.wildcard=!1,this._services=[],typeof r=="function")return new t(e,null,r);this.mdns=e,this.txt=new tE.default(r!==null&&r.txt!=null?r.txt:void 0),r===null||r.type===void 0?(this.name=sE,this.wildcard=!0):(this.name=(0,Ip.toString)({name:r.type,protocol:r.protocol||"tcp"})+Nl,r.name&&(this.name=r.name+"."+this.name),this.wildcard=!1),r!=null&&r.txt!==void 0&&(this.txtQuery=(0,nE.default)(r.txt)),n&&this.on("up",n),this.start()}start(){if(!(this.onresponse||this.name===void 0)){var e=this,r={};this.wildcard||(r[this.name]=!0),this.onresponse=(n,a)=>{e.wildcard&&n.answers.forEach(c=>{c.type!=="PTR"||c.name!==e.name||c.name in r||(r[c.data]=!0,e.mdns.query(c.data,"PTR"))}),Object.keys(r).forEach(function(c){e.goodbyes(c,n).forEach(e.removeService.bind(e));var p=e.buildServicesFor(c,n,e.txt,a);p.length!==0&&p.forEach(f=>{if(e.serviceMap[f.fqdn]){e.updateService(f);return}e.addService(f)})})},this.mdns.on("response",this.onresponse),this.update()}}stop(){this.onresponse&&(this.mdns.removeListener("response",this.onresponse),this.onresponse=void 0)}update(){this.mdns.query(this.name,"PTR")}get services(){return this._services}addService(e){(0,Ul.default)(e,this.txtQuery)!==!1&&(this._services.push(e),this.serviceMap[e.fqdn]=!0,this.emit("up",e))}updateService(e){var r;if(!(0,oE.default)(e.txt,((r=this._services.find(n=>(0,sn.default)(n.fqdn,e.fqdn)))===null||r===void 0?void 0:r.txt)||{})){if(!(0,Ul.default)(e,this.txtQuery)){this.removeService(e.fqdn);return}this._services=this._services.map(function(n){return(0,sn.default)(n.fqdn,e.fqdn)?e:n}),this.emit("txt-update",e)}}removeService(e){var r,n;this._services.some(function(a,c){if((0,sn.default)(a.fqdn,e))return r=a,n=c,!0}),!(!r||n===void 0)&&(this._services.splice(n,1),delete this.serviceMap[e],this.emit("down",r))}goodbyes(e,r){return r.answers.concat(r.additionals).filter(n=>n.type==="PTR"&&n.ttl===0&&(0,sn.default)(n.name,e)).map(n=>n.data)}buildServicesFor(e,r,n,a){var c=r.answers.concat(r.additionals).filter(p=>p.ttl>0);return c.filter(p=>p.type==="PTR"&&(0,sn.default)(p.name,e)).map(p=>{let f={addresses:[],subtypes:[]};if(c.filter(l=>l.type==="PTR"&&(0,sn.default)(l.data,p.data)&&l.name.includes("._sub")).forEach(l=>{let m=(0,Ip.toType)(l.name);f.subtypes.push(m.subtype)}),c.filter(l=>(l.type==="SRV"||l.type==="TXT")&&(0,sn.default)(l.name,p.data)).forEach(l=>{if(l.type==="SRV"){var m=l.name.split("."),y=m[0],g=(0,Ip.toType)(m.slice(1,-1).join("."));f.name=y,f.fqdn=l.name,f.host=l.data.target,f.referer=a,f.port=l.data.port,f.type=g.name,f.protocol=g.protocol}else l.type==="TXT"&&(f.rawTxt=l.data,f.txt=this.txt.decodeAll(l.data))}),!!f.name)return c.filter(l=>(l.type==="A"||l.type==="AAAA")&&(0,sn.default)(l.name,f.host)).forEach(l=>f.addresses.push(l.data)),f}).filter(p=>!!p)}};_n.Browser=Oa;_n.default=Oa});var Bl=ve(Ot=>{"use strict";var La=Ot&&Ot.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ot,"__esModule",{value:!0});Ot.Browser=Ot.Service=Ot.Bonjour=void 0;var iE=La(ll()),aE=La(ql()),wp=La(_l());Ot.Browser=wp.default;var cE=La(op());Ot.Service=cE.default;var Ma=class{static{i(this,"Bonjour")}constructor(e={},r){this.server=new aE.default(e,r),this.registry=new iE.default(this.server)}publish(e){return this.registry.publish(e)}unpublishAll(e){return this.registry.unpublishAll(e)}find(e=null,r){return new wp.default(this.server.mdns,e,r)}findOne(e=null,r=1e4,n){let a=new wp.default(this.server.mdns,e);var c;return a.once("up",p=>{c!==void 0&&clearTimeout(c),a.stop(),n&&n(p)}),c=setTimeout(()=>{a.stop(),n&&n(null)},r),a}destroy(e){this.registry.destroy(),this.server.mdns.destroy(e)}};Ot.Bonjour=Ma;Ot.default=Ma});var yg=ve((e1,tc)=>{function pg(t){return Array.isArray(t)?t:[t]}i(pg,"makeArray");var Qw=void 0,Xp="",ag=" ",Kp="\\",Yw=/^\s+$/,Kw=/(?:[^\\]|^)\\$/,Xw=/^\\!/,Jw=/^\\#/,Zw=/\r?\n/g,eD=/^\.{0,2}\/|^\.{1,2}$/,tD=/\/$/,Qo="/",dg="node-ignore";typeof Symbol<"u"&&(dg=Symbol.for("node-ignore"));var ug=dg,Yo=i((t,e,r)=>(Object.defineProperty(t,e,{value:r}),r),"define"),rD=/([0-z])-([0-z])/g,mg=i(()=>!1,"RETURN_FALSE"),nD=i(t=>t.replace(rD,(e,r,n)=>r.charCodeAt(0)<=n.charCodeAt(0)?e:Xp),"sanitizeRange"),oD=i(t=>{let{length:e}=t;return t.slice(0,e-e%2)},"cleanRangeBackSlash"),sD=[[/^\uFEFF/,()=>Xp],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,r)=>e+(r.indexOf("\\")===0?ag:Xp)],[/(\\+?)\s/g,(t,e)=>{let{length:r}=e;return e.slice(0,r-r%2)+ag}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,i(function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"},"startingReplacer")],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,r)=>e+6<r.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,r)=>{let n=r.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Kp],[/\\\\/g,()=>Kp],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,r,n,a)=>e===Kp?`\\[${r}${oD(n)}${a}`:a==="]"&&n.length%2===0?`[${nD(r)}${n}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],iD=/(^|\\\/)?\\\*$/,ui="regex",Za="checkRegex",cg="_",aD={[ui](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Za](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},cD=i(t=>sD.reduce((e,[r,n])=>e.replace(r,n.bind(t)),t),"makeRegexPrefix"),ec=i(t=>typeof t=="string","isString"),pD=i(t=>t&&ec(t)&&!Yw.test(t)&&!Kw.test(t)&&t.indexOf("#")!==0,"checkPattern"),dD=i(t=>t.split(Zw).filter(Boolean),"splitPattern"),Jp=class{static{i(this,"IgnoreRule")}constructor(e,r,n,a,c,p){this.pattern=e,this.mark=r,this.negative=c,Yo(this,"body",n),Yo(this,"ignoreCase",a),Yo(this,"regexPrefix",p)}get regex(){let e=cg+ui;return this[e]?this[e]:this._make(ui,e)}get checkRegex(){let e=cg+Za;return this[e]?this[e]:this._make(Za,e)}_make(e,r){let n=this.regexPrefix.replace(iD,aD[e]),a=this.ignoreCase?new RegExp(n,"i"):new RegExp(n);return Yo(this,r,a)}},uD=i(({pattern:t,mark:e},r)=>{let n=!1,a=t;a.indexOf("!")===0&&(n=!0,a=a.substr(1)),a=a.replace(Xw,"!").replace(Jw,"#");let c=cD(a);return new Jp(t,e,a,r,n,c)},"createRule"),Zp=class{static{i(this,"RuleManager")}constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[ug]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(ec(e)&&(e={pattern:e}),pD(e.pattern)){let r=uD(e,this._ignoreCase);this._added=!0,this._rules.push(r)}}add(e){return this._added=!1,pg(ec(e)?dD(e):e).forEach(this._add,this),this._added}test(e,r,n){let a=!1,c=!1,p;this._rules.forEach(l=>{let{negative:m}=l;c===m&&a!==c||m&&!a&&!c&&!r||!l[n].test(e)||(a=!m,c=m,p=m?Qw:l)});let f={ignored:a,unignored:c};return p&&(f.rule=p),f}},mD=i((t,e)=>{throw new e(t)},"throwError"),Tr=i((t,e,r)=>ec(t)?t?Tr.isNotRelative(t)?r(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:r("path must not be empty",TypeError):r(`path must be a string, but got \`${e}\``,TypeError),"checkPath"),lg=i(t=>eD.test(t),"isNotRelative");Tr.isNotRelative=lg;Tr.convert=t=>t;var ed=class{static{i(this,"Ignore")}constructor({ignorecase:e=!0,ignoreCase:r=e,allowRelativePaths:n=!1}={}){Yo(this,ug,!0),this._rules=new Zp(r),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,r,n,a){let c=e&&Tr.convert(e);return Tr(c,e,this._strictPathCheck?mD:mg),this._t(c,r,n,a)}checkIgnore(e){if(!tD.test(e))return this.test(e);let r=e.split(Qo).filter(Boolean);if(r.pop(),r.length){let n=this._t(r.join(Qo)+Qo,this._testCache,!0,r);if(n.ignored)return n}return this._rules.test(e,!1,Za)}_t(e,r,n,a){if(e in r)return r[e];if(a||(a=e.split(Qo).filter(Boolean)),a.pop(),!a.length)return r[e]=this._rules.test(e,n,ui);let c=this._t(a.join(Qo)+Qo,r,n,a);return r[e]=c.ignored?c:this._rules.test(e,n,ui)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return pg(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},td=i(t=>new ed(t),"factory"),lD=i(t=>Tr(t&&Tr.convert(t),t,mg),"isPathValid"),fg=i(()=>{let t=i(r=>/^\\\\\?\\/.test(r)||/["<>|\u0000-\u001F]+/u.test(r)?r:r.replace(/\\/g,"/"),"makePosix");Tr.convert=t;let e=/^[a-z]:\//i;Tr.isNotRelative=r=>e.test(r)||lg(r)},"setupWindows");typeof process<"u"&&process.platform==="win32"&&fg();tc.exports=td;td.default=td;tc.exports.isPathValid=lD;Yo(tc.exports,Symbol.for("setupWindows"),fg)});var md={};me(md,{Default:()=>aR,Server:()=>md,listen:()=>pR,openapi:()=>cR,url:()=>rc});var U={};me(U,{AdditionalSchemas:()=>Ds,isHttpApi:()=>cS,make:()=>dS,reflect:()=>Kc});var u={};me(u,{delete:()=>oS,get:()=>eS,getErrorSchemas:()=>Pn,getPayloadSchemas:()=>$h,getSuccessSchemas:()=>Hn,head:()=>sS,isHttpApiEndpoint:()=>Wh,make:()=>tn,options:()=>iS,patch:()=>nS,post:()=>tS,put:()=>rS});var k={};me(k,{Accepted:()=>Th,Created:()=>Ph,Empty:()=>va,MultipartStreamTypeId:()=>Nm,MultipartTypeId:()=>Um,NoContent:()=>jc,StreamSse:()=>bh,StreamUint8Array:()=>Oh,asFormUrlEncoded:()=>$c,asJson:()=>Nh,asMultipart:()=>Lh,asMultipartStream:()=>Uh,asNoContent:()=>Je,asText:()=>_h,asUint8Array:()=>Bh,getPayloadEncoding:()=>Aa,getResponseEncoding:()=>yr,getStatusError:()=>kn,getStatusStream:()=>xn,getStatusSuccess:()=>Qt,getStreamMetadata:()=>Mh,isNoContent:()=>en,isStreamSchema:()=>Ze,isStreamSse:()=>Is,isStreamUint8Array:()=>Gc,status:()=>Om});var Hh={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511},As="~effect/httpapi/HttpApiSchema/Stream";function Om(t){let e=typeof t=="string"?Hh[t]:t;return r=>r.annotate({httpApiStatus:e})}i(Om,"status");var va=i(t=>wc.pipe(Om(t)),"Empty"),jc=va(204),Ph=va(201),Th=va(202);function Je(t){return e=>wc.pipe(Mi(Zd(e),Od({decode:t.decode,encode:fd})))}i(Je,"asNoContent");var Mm=bi(ss),bh=i(t=>{let e=t.events??(t.data===void 0?void 0:En({id:tu(_r),event:_r,data:qh(t.data)}));if(e===void 0)throw new Error("StreamSse requires either an events schema or a data schema");return Ic(Mm.ast,{[As]:As,_tag:"StreamSse",mode:"sse",sseMode:t.events===void 0?"data":"events",contentType:t.contentType??Lm("sse"),events:e,error:t.error??qi})},"StreamSse"),qh=i(t=>{let e=os(t.ast);return e===void 0?ps(t):ps(t).annotate({identifier:`${e}Stream`})},"sseDataJsonSchema"),Oh=i(t=>Ic(Mm.ast,{[As]:As,_tag:"StreamUint8Array",mode:"uint8array",contentType:t?.contentType??Lm("uint8array")}),"StreamUint8Array"),Ze=i(t=>vn(t)&&St(t,As),"isStreamSchema"),Is=i(t=>Ze(t)&&t._tag==="StreamSse","isStreamSse"),Gc=i(t=>Ze(t)&&t._tag==="StreamUint8Array","isStreamUint8Array");function Mh(t){return t._tag==="StreamSse"?{mode:t.mode,sseMode:t.sseMode,contentType:t.contentType,events:t.events,error:t.error}:{mode:t.mode,contentType:t.contentType}}i(Mh,"getStreamMetadata");function Lm(t){switch(t){case"sse":return"text/event-stream";case"uint8array":return"application/octet-stream"}}i(Lm,"defaultStreamContentType");var Um="~effect/httpapi/HttpApiSchema/Multipart";function Lh(t){return e=>e.pipe(Dc(Um)).annotate({"~httpApiEncoding":{_tag:"Multipart",mode:"buffered",contentType:Wc("Multipart"),limits:t}})}i(Lh,"asMultipart");var Nm="~effect/httpapi/HttpApiSchema/MultipartStream";function Uh(t){return e=>e.pipe(Dc(Nm)).annotate({"~httpApiEncoding":{_tag:"Multipart",mode:"stream",contentType:Wc("Multipart"),limits:t}})}i(Uh,"asMultipartStream");function Ea(t,e){return t.annotate({"~httpApiEncoding":{_tag:e._tag,contentType:e.contentType??Wc(e._tag)}})}i(Ea,"asNonMultipartEncoding");function Wc(t){switch(t){case"Multipart":return"multipart/form-data";case"Json":return"application/json";case"FormUrlEncoded":return"application/x-www-form-urlencoded";case"Uint8Array":return"application/octet-stream";case"Text":return"text/plain"}}i(Wc,"defaultContentType");function Nh(t){return e=>Ea(e,{_tag:"Json",...t})}i(Nh,"asJson");function $c(t){return e=>Ea(e,{_tag:"FormUrlEncoded",...t})}i($c,"asFormUrlEncoded");function _h(t){return e=>Ea(e,{_tag:"Text",...t})}i(_h,"asText");function Bh(t){return e=>Ea(e,{_tag:"Uint8Array",...t})}i(Bh,"asUint8Array");var en=i(t=>{if(Ii(t))return!0;let e=Sn(t);if(Ii(e))return!0;let r=t.encoding?.[0].to;return r===void 0?!1:Ii(r)},"isNoContent"),_m=Ec("~httpApiEncoding"),Bm=Ec("httpApiStatus"),Fm={_tag:"Json",contentType:"application/json"},Fh={_tag:"FormUrlEncoded",contentType:"application/x-www-form-urlencoded"};function jh(t){return _m(t)??Fm}i(jh,"getEncoding");function Aa(t,e){let r=_m(t);return r||(ao(e)?Fm:Fh)}i(Aa,"getPayloadEncoding");function yr(t){let e=jh(t);if(e._tag==="Multipart")throw new Error("Multipart is not supported in response");return e}i(yr,"getResponseEncoding");function Qt(t){return Bm(t)??200}i(Qt,"getStatusSuccess");function xn(t){return Qt(t.ast)}i(xn,"getStatusStream");function kn(t){return Bm(t)??500}i(kn,"getStatusError");var zc="~effect/httpapi/HttpApiEndpoint",Wh=i(t=>St(t,zc),"isHttpApiEndpoint");function $h(t){let e=[];for(let{schemas:r}of t.payload.values())e.push(...r);return e}i($h,"getPayloadSchemas");function Hn(t){let e=Array.from(t.success);return yi(e)?e:[jc]}i(Hn,"getSuccessSchemas");function Pn(t){let e=new Set(t.error);for(let r of t.middlewares){let n=r;for(let a of n.error)e.add(a)}return Array.from(e)}i(Pn,"getErrorSchemas");var Vh={[zc]:zc,pipe(){return qr(this,arguments)},prefix(t){return ws({...this,path:Eu(this.path,t)})},middleware(t){return ws({...this,middlewares:new Set([...this.middlewares,t])})},annotate(t,e){return ws({...this,annotations:Lr(this.annotations,t,e)})},annotateMerge(t){return ws({...this,annotations:Ct(this.annotations,t)})}};function ws(t){return Object.assign(Object.create(Vh),t)}i(ws,"makeProto");var tn=i(t=>(e,r,n)=>{let a=n?.disableCodecs??!1,c=a?hn:Ni;return ws({name:e,path:r,method:t,params:Vc(n?.params,c),query:Vc(n?.query,c),headers:Vc(n?.headers,c),payload:zh(n?.payload,t,a),success:Qh(n?.success,t,a),error:Yh(n?.error,a),annotations:Mr(),middlewares:new Set})},"make");function Vc(t,e){if(t!==void 0)return vn(t)?e(t):e(En(t))}i(Vc,"ensureStruct");function zh(t,e,r){let n=new Map;if(t===void 0)return n;let a=Array.isArray(t)?t:vn(t)?[t]:[En(t).pipe($c())],c=r?hn:Zh;for(let p of a){let f=Aa(p.ast,e),l=n.get(f.contentType);if(l){if(l.encoding._tag!==f._tag)throw new Error(`Multiple payload encodings for content-type: ${f.contentType}`);if(l.encoding._tag==="Multipart")throw new Error(`Multiple multipart payloads for content-type: ${f.contentType}`);l.schemas.push(c(p,e))}else n.set(f.contentType,{encoding:f,schemas:[c(p,e)]})}return n}i(zh,"getPayload");var Gm="effect/httpapi/stream/failure";function Qh(t,e,r){if(t===void 0)return new Set;let n=ic(t);return Kh(n,e),new Set(r?n:n.map(a=>Ze(a)?a:Wm(a)))}i(Qh,"getSuccessResponse");function Yh(t,e){if(t===void 0)return new Set;let r=ic(t);for(let n of r)if(Ze(n))throw new Error("Streaming schemas are not supported in error responses");return new Set(e?r:r.map(Wm))}i(Yh,"getErrorResponse");function Kh(t,e){let r=new Map;for(let n of t)if(Ze(n)){Xh(n,e);let a=xn(n),c=jm(r,a);if(c.stream!==void 0)throw new Error(`Multiple streaming success responses for status: ${a}`);if(c.noContent)throw new Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(c.bufferedContentTypes.has(Ia(n.contentType)))throw new Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${n.contentType}`);r.set(a,{...c,stream:n})}else{let a=Qt(n.ast),c=jm(r,a),p=en(n.ast);if(c.stream!==void 0){if(p)throw new Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let f=yr(n.ast);if(Ia(f.contentType)===Ia(c.stream.contentType))throw new Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${f.contentType}`)}p||c.bufferedContentTypes.add(Ia(yr(n.ast).contentType)),c.noContent=c.noContent||p}}i(Kh,"validateSuccessResponse");function Ia(t){let e=t.toLowerCase().trim(),r=e.indexOf(";");return r===-1?e:e.slice(0,r).trim()}i(Ia,"normalizeResponseContentType");function jm(t,e){let r=t.get(e);return r===void 0&&(r={bufferedContentTypes:new Set,noContent:!1},t.set(e,r)),r}i(jm,"getStatusEntry");function Xh(t,e){if(e==="HEAD")throw new Error("HEAD endpoints cannot declare streaming success responses");if(Is(t)&&Jh(t.events.ast))throw new Error(`SSE event name is reserved: ${Gm}`)}i(Xh,"validateStreamSuccess");function Jh(t){return Qc(Sn(t),new Set)}i(Jh,"hasReservedSseEventName");function Qc(t,e){if(e.has(t))return!1;if(e.add(t),hc(t))return t.types.some(n=>Qc(n,e));if(Sc(t))return Qc(t.thunk(),e);if(!wi(t))return!1;let r=t.propertySignatures.find(n=>n.name==="event");return r!==void 0&&wa(r.type,e)}i(Qc,"hasReservedEventName");function wa(t,e){if(e.has(t))return!1;e.add(t);let r=Sn(t);return r!==t?wa(r,e):Ud(t)?t.literal===Gm:hc(t)?t.types.some(n=>wa(n,e)):Sc(t)?wa(t.thunk(),e):!1}i(wa,"hasReservedEventLiteral");function Wm(t){switch(yr(t.ast)._tag){case"Json":return An(t);case"FormUrlEncoded":return Ni(t);case"Text":case"Uint8Array":return t}}i(Wm,"transformResponse");function Zh(t,e){switch(Aa(t.ast,e)._tag){case"Json":return An(t);case"FormUrlEncoded":return Ni(t);case"Text":case"Uint8Array":case"Multipart":return t}}i(Zh,"transformPayload");var eS=tn("GET"),tS=tn("POST"),rS=tn("PUT"),nS=tn("PATCH"),oS=tn("DELETE");var sS=tn("HEAD"),iS=tn("OPTIONS");var Yc="~effect/httpapi/HttpApi",cS=i(t=>St(t,Yc),"isHttpApi"),pS={[Yc]:Yc,pipe(){return qr(this,arguments)},add(...t){let e={...this.groups};for(let r of t)e[r.identifier]=r;return Tn({identifier:this.identifier,groups:e,annotations:this.annotations})},addHttpApi(t){let e={...this.groups};for(let r in t.groups){let n=t.groups[r];n.annotations=Ct(t.annotations,n.annotations),e[r]=n}return Tn({identifier:this.identifier,groups:e,annotations:this.annotations})},prefix(t){return Tn({identifier:this.identifier,groups:Or(this.groups,e=>e.prefix(t)),annotations:this.annotations})},middleware(t){return Tn({identifier:this.identifier,groups:Or(this.groups,e=>e.middleware(t)),annotations:this.annotations})},annotate(t,e){return Tn({identifier:this.identifier,groups:this.groups,annotations:Lr(this.annotations,t,e)})},annotateMerge(t){return Tn({identifier:this.identifier,groups:this.groups,annotations:Ct(this.annotations,t)})}},Tn=i(t=>{function e(){}return i(e,"HttpApi"),Object.setPrototypeOf(e,pS),e.groups=t.groups,e.annotations=t.annotations,e},"makeProto"),dS=i(t=>Tn({identifier:t,groups:new Map,annotations:Mr()}),"make"),Kc=i((t,e)=>{let r=Object.values(t.groups);for(let n of r){let a=Ct(t.annotations,n.annotations);e.onGroup({group:n,mergedAnnotations:a});let c=Object.values(n.endpoints);for(let p of c)e.predicate&&!e.predicate({endpoint:p,group:n})||e.onEndpoint({group:n,endpoint:p,middleware:p.middlewares,mergedAnnotations:Ct(a,p.annotations),successes:$m(Hn(p),Qt),errors:$m(Pn(p),kn)})}},"reflect"),$m=i((t,e)=>{let r=new Map;return t.forEach(n),r;function n(a){if(Ze(a))return;let c=a.ast,p=e(c),f=r.get(p);f===void 0?r.set(p,[a]):f.push(a)}i(n,"add")},"extractResponseContent"),Ds=class extends Te()("effect/httpapi/HttpApi/AdditionalSchemas"){static{i(this,"AdditionalSchemas")}};var x={};me(x,{HandlersTypeId:()=>rl,endpoint:()=>VS,group:()=>$S,handlerToRoute:()=>sl,layer:()=>WS,securityDecode:()=>nl,securitySetCookie:()=>zS});var D={};me(D,{BadRequest:()=>Rs,BadRequestNoContent:()=>IS,Conflict:()=>bs,ConflictNoContent:()=>HS,Forbidden:()=>xs,ForbiddenNoContent:()=>DS,Gone:()=>qs,GoneNoContent:()=>PS,HttpApiSchemaError:()=>ct,HttpApiSchemaErrorTypeId:()=>Da,InternalServerError:()=>Os,InternalServerErrorNoContent:()=>TS,MethodNotAllowed:()=>Hs,MethodNotAllowedNoContent:()=>CS,NotAcceptable:()=>Ps,NotAcceptableNoContent:()=>xS,NotFound:()=>ks,NotFoundNoContent:()=>RS,NotImplemented:()=>Ms,NotImplementedNoContent:()=>bS,RequestTimeout:()=>Ts,RequestTimeoutNoContent:()=>kS,ServiceUnavailable:()=>Ls,ServiceUnavailableNoContent:()=>qS,Unauthorized:()=>Cs,UnauthorizedNoContent:()=>wS});var Vm=Be({status:400}),uS=Be({status:401}),mS=Be({status:403}),lS=Be({status:404}),fS=Be({status:405}),yS=Be({status:406}),gS=Be({status:408}),hS=Be({status:409}),SS=Be({status:410}),vS=Be({status:500}),ES=Be({status:501}),AS=Be({status:503}),Rs=class t extends ot("effect/HttpApiError/BadRequest")({_tag:nt("BadRequest")},{description:"BadRequest",httpApiStatus:400}){static{i(this,"BadRequest")}[jt]=!0;[Qe](){return re(Vm)}static singleton=new t},IS=Rs.pipe(Je({decode:i(()=>new Rs({}),"decode")})),Cs=class extends ot("effect/HttpApiError/Unauthorized")({_tag:nt("Unauthorized")},{description:"Unauthorized",httpApiStatus:401}){static{i(this,"Unauthorized")}[jt]=!0;[Qe](){return re(uS)}},wS=Cs.pipe(Je({decode:i(()=>new Cs({}),"decode")})),xs=class extends ot("effect/HttpApiError/Forbidden")({_tag:nt("Forbidden")},{description:"Forbidden",httpApiStatus:403}){static{i(this,"Forbidden")}[jt]=!0;[Qe](){return re(mS)}},DS=xs.pipe(Je({decode:i(()=>new xs({}),"decode")})),ks=class extends ot("effect/HttpApiError/NotFound")({_tag:nt("NotFound")},{description:"NotFound",httpApiStatus:404}){static{i(this,"NotFound")}[jt]=!0;[Qe](){return re(lS)}},RS=ks.pipe(Je({decode:i(()=>new ks({}),"decode")})),Hs=class extends ot("effect/HttpApiError/MethodNotAllowed")({_tag:nt("MethodNotAllowed")},{description:"MethodNotAllowed",httpApiStatus:405}){static{i(this,"MethodNotAllowed")}[jt]=!0;[Qe](){return re(fS)}},CS=Hs.pipe(Je({decode:i(()=>new Hs({}),"decode")})),Ps=class extends ot("effect/HttpApiError/NotAcceptable")({_tag:nt("NotAcceptable")},{description:"NotAcceptable",httpApiStatus:406}){static{i(this,"NotAcceptable")}[jt]=!0;[Qe](){return re(yS)}},xS=Ps.pipe(Je({decode:i(()=>new Ps({}),"decode")})),Ts=class extends ot("effect/HttpApiError/RequestTimeout")({_tag:nt("RequestTimeout")},{description:"RequestTimeout",httpApiStatus:408}){static{i(this,"RequestTimeout")}[jt]=!0;[Qe](){return re(gS)}},kS=Ts.pipe(Je({decode:i(()=>new Ts({}),"decode")})),bs=class extends ot("effect/HttpApiError/Conflict")({_tag:nt("Conflict")},{description:"Conflict",httpApiStatus:409}){static{i(this,"Conflict")}[jt]=!0;[Qe](){return re(hS)}},HS=bs.pipe(Je({decode:i(()=>new bs({}),"decode")})),qs=class extends ot("effect/HttpApiError/Gone")({_tag:nt("Gone")},{description:"Gone",httpApiStatus:410}){static{i(this,"Gone")}[jt]=!0;[Qe](){return re(SS)}},PS=qs.pipe(Je({decode:i(()=>new qs({}),"decode")})),Os=class extends ot("effect/HttpApiError/InternalServerError")({_tag:nt("InternalServerError")},{description:"InternalServerError",httpApiStatus:500}){static{i(this,"InternalServerError")}[Qe](){return re(vS)}},TS=Os.pipe(Je({decode:i(()=>new Os({}),"decode")})),Ms=class extends ot("effect/HttpApiError/NotImplemented")({_tag:nt("NotImplemented")},{description:"NotImplemented",httpApiStatus:501}){static{i(this,"NotImplemented")}[Qe](){return re(ES)}},bS=Ms.pipe(Je({decode:i(()=>new Ms({}),"decode")})),Ls=class extends ot("effect/HttpApiError/ServiceUnavailable")({_tag:nt("ServiceUnavailable")},{description:"ServiceUnavailable",httpApiStatus:503}){static{i(this,"ServiceUnavailable")}[Qe](){return re(AS)}},qS=Ls.pipe(Je({decode:i(()=>new Ls({}),"decode")})),Da="~effect/httpapi/HttpApiError/HttpApiSchemaError",ct=class t extends wd("HttpApiSchemaError"){static{i(this,"HttpApiSchemaError")}[Da]=Da;static is(e){return St(e,Da)}static wrap(e,r){return Cd(r,n=>new t({kind:e,cause:n}))}name="HttpApiSchemaError";message=this.kind;[Qe](){return re(Vm)}};var ge={};me(ge,{Service:()=>OS,isSecurity:()=>Us,layerClient:()=>US,layerSchemaErrorTransform:()=>LS});var zm="~effect/httpapi/HttpApiMiddleware",Xc="~effect/httpapi/HttpApiMiddleware/Security",Us=i(t=>St(t,Xc),"isSecurity"),OS=i(()=>(t,e)=>{let r=globalThis.Error,n=r.stackTraceLimit;r.stackTraceLimit=2;let a=new r;r.stackTraceLimit=n;class c extends Te()(t){static{i(this,"Service")}}let p=c;if(Object.defineProperty(c,"stack",{get(){return a.stack}}),p[zm]=zm,p.error=MS(e?.error),p.requiredForClient=e?.requiredForClient??!1,e?.security!==void 0){if(Object.keys(e.security).length===0)throw new Error("HttpApiMiddleware.Service: security object must not be empty");p[Xc]=Xc,p.security=e.security}return p},"Service");function MS(t){return t===void 0?new Set:new Set(Array.isArray(t)?t:[t])}i(MS,"getError");var LS=i((t,e)=>Id(t,(r,n)=>Ai(r,a=>ct.is(a)?e(a,n):no(a))),"layerSchemaErrorTransform"),US=i((t,e)=>vi(es(function*(){let r=(yield*rs()).pipe(Jo(Zo)),n=Ei(e)?yield*e:e;return gi(new Map([[`${t.key}/Client`,a=>Hd(n(a),c=>Ct(r,c))]]))})),"layerClient");var d={};me(d,{Deprecated:()=>Gs,Description:()=>rn,Exclude:()=>Ra,ExternalDocs:()=>Do,Format:()=>js,Identifier:()=>Ns,License:()=>Bs,Override:()=>qn,Servers:()=>Fs,Summary:()=>Ro,Title:()=>bn,Transform:()=>On,Version:()=>_s,annotations:()=>BS,fromApi:()=>Jc});var Ns=class extends Te()("effect/httpapi/OpenApi/Identifier"){static{i(this,"Identifier")}},bn=class extends Te()("effect/httpapi/OpenApi/Title"){static{i(this,"Title")}},_s=class extends Te()("effect/httpapi/OpenApi/Version"){static{i(this,"Version")}},rn=class extends Te()("effect/httpapi/OpenApi/Description"){static{i(this,"Description")}},Bs=class extends Te()("effect/httpapi/OpenApi/License"){static{i(this,"License")}},Do=class extends Te()("effect/httpapi/OpenApi/ExternalDocs"){static{i(this,"ExternalDocs")}},Fs=class extends Te()("effect/httpapi/OpenApi/Servers"){static{i(this,"Servers")}},js=class extends Te()("effect/httpapi/OpenApi/Format"){static{i(this,"Format")}},Ro=class extends Te()("effect/httpapi/OpenApi/Summary"){static{i(this,"Summary")}},Gs=class extends Te()("effect/httpapi/OpenApi/Deprecated"){static{i(this,"Deprecated")}},qn=class extends Te()("effect/httpapi/OpenApi/Override"){static{i(this,"Override")}},Ra=Ad("effect/httpapi/OpenApi/Exclude",{defaultValue:ld}),On=class extends Te()("effect/httpapi/OpenApi/Transform"){static{i(this,"Transform")}},_S=i(t=>{let e=Object.entries(t);return r=>{let n=Mr();for(let[a,c]of e)r[a]!==void 0&&(n=Lr(n,c,r[a]));return n}},"servicesPartial"),BS=_S({identifier:Ns,title:bn,version:_s,description:rn,license:Bs,summary:Ro,deprecated:Gs,externalDocs:Do,servers:Fs,format:js,override:qn,exclude:Ra,transform:On}),Qm=new WeakMap;function De(t,e,r){let n=cc(t,e);yd(n)&&r(n.value)}i(De,"processAnnotation");function Jc(t){let e=Qm.get(t);if(e!==void 0)return e;let r={openapi:"3.1.0",info:{title:"Api",version:"0.0.1"},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]},n=[];De(t.annotations,bn,c=>{r.info.title=c}),De(t.annotations,_s,c=>{r.info.version=c}),De(t.annotations,rn,c=>{r.info.description=c}),De(t.annotations,Bs,c=>{r.info.license=c}),De(t.annotations,Ro,c=>{r.info.summary=c}),De(t.annotations,Fs,c=>{r.servers=[...c]}),Kc(t,{onGroup({group:c}){if(ac(c.annotations,Ra))return;let p={name:hi(c.annotations,bn,()=>c.identifier)};De(c.annotations,rn,f=>{p.description=f}),De(c.annotations,Do,f=>{p.externalDocs=f}),De(c.annotations,qn,f=>{Object.assign(p,f)}),De(c.annotations,On,f=>{p=f(p)}),r.tags.push(p)},onEndpoint({endpoint:c,group:p,mergedAnnotations:f,middleware:l}){if(ac(f,Ra))return;let m={tags:[hi(p.annotations,bn,()=>p.identifier)],operationId:hi(c.annotations,Ns,()=>p.topLevel?c.name:`${p.identifier}.${c.name}`),parameters:[],security:[],responses:{}},y=c.path.replace(/:(\w+)\??/g,"{$1}"),g=c.method.toLowerCase();function E(R){if(R.size>0){let b={},O=!1;R.forEach(({encoding:Z,schemas:Se},Re)=>{let ar=Se.filter(ke=>!en(ke.ast));if(ar.length===0)return;O=!0;let F=ar.map(so),ue=F.length===1?F[0]:new vc(F,"anyOf");n.push({_tag:"schema",ast:Ym(ue,Z._tag),path:["paths",y,g,"requestBody","content",Re,"schema"]}),b[Re]={schema:{}}}),O&&(m.requestBody={content:b,required:!0})}}i(E,"processRequestBodies");function v(R,b){for(let[O,{content:Z,descriptions:Se,streamContent:Re}]of R){let ar=Se.size>0?Array.from(Se).join(" | "):b();m.responses[O]={description:ar},Z!==void 0&&Z.forEach((F,ue)=>{F.forEach((ke,ne)=>{let Ve=Array.from(ke,so),nc=Ve.length===1?Ve[0]:new vc(Ve,"anyOf");n.push({_tag:"schema",ast:Ym(nc,ue),path:["paths",y,g,"responses",String(O),"content",ne,"schema"]}),m.responses[O].content??={},m.responses[O].content[ne]={schema:{}}})}),Re!==void 0&&Re.forEach((F,ue)=>{m.responses[O].content??={},Is(F)?(n.push({_tag:"schema",ast:so(F.events),path:["paths",y,g,"responses",String(O),"content",ue,"schema"]}),n.push({_tag:"schema",ast:so(An(Li(F.error,Ui()))),path:["paths",y,g,"responses",String(O),"content",ue,"x-effect-stream","causeSchema"]}),n.push({_tag:"schema",ast:so(F.error),path:["paths",y,g,"responses",String(O),"content",ue,"x-effect-stream","errorSchema"]}),m.responses[O].content[ue]={schema:{},"x-effect-stream":{encoding:"sse",causeSchema:{},errorSchema:{},failureEvent:FS}}):m.responses[O].content[ue]={schema:{type:"string",format:"binary"},"x-effect-stream":{encoding:"uint8array"}}})}}i(v,"processResponseBodies");function h(R,b){if(R){let O=Nd(R.ast);if(wi(O))for(let Z of O.propertySignatures)m.parameters.push({name:String(Z.name),in:b,schema:{},required:b==="path"||!_d(Z.type)}),n.push({_tag:"parameter",ast:Z.type,path:["paths",y,g,"parameters",String(m.parameters.length-1),"schema"]})}}i(h,"processParameters"),De(c.annotations,rn,R=>{m.description=R}),De(c.annotations,Ro,R=>{m.summary=R}),De(c.annotations,Gs,R=>{m.deprecated=R}),De(c.annotations,Do,R=>{m.externalDocs=R}),l.forEach(R=>{if(Us(R))for(let[b,O]of Object.entries(R.security))w(b,O),m.security.push({[b]:[]})});function w(R,b){r.components.securitySchemes[R]===void 0&&(r.components.securitySchemes[R]=GS(b))}i(w,"processHttpApiSecurity");let C=ao(c.method);if(C&&E(c.payload),h(c.params,"path"),!C&&c.payload.size===1){let R=c.payload.values().next().value;h(R.schemas[0],"query")}h(c.headers,"header"),h(c.query,"query"),v(jS(c),()=>"Success"),v(Km(Pn(c),kn,Xm),()=>"Error"),r.paths[y]||(r.paths[y]={}),De(c.annotations,qn,R=>{Object.assign(m,R)}),De(c.annotations,On,R=>{m=R(m)}),r.paths[y][g]=m}}),De(t.annotations,Ds,c=>{c.forEach(p=>{let f=os(p.ast);if(f!==void 0){if(f in r.components.schemas)throw new globalThis.Error(`Duplicate component schema identifier: ${f}`);r.components.schemas[f]={},n.push({_tag:"schema",ast:p.ast,path:["components","schemas",f]})}})});function a(c){return"/"+c.map(Qd).join("/")}if(i(a,"escapePath"),yi(n)){let c=Iu(Ed(n,l=>l.ast)),p=Xd(wu(c)),f=n.map((l,m)=>{let y=a(l.path),g=p.schemas[m];return{op:"replace",path:y,value:g}});Object.entries(p.definitions).forEach(([l,m])=>{f.push({op:"add",path:a(["components","schemas",l]),value:m})}),r=Kd(f,r)}return Object.keys(r.components.schemas).forEach(c=>{if(!Jd.test(c))throw new globalThis.Error(`Invalid component schema key: ${c}`)}),De(t.annotations,qn,c=>{Object.assign(r,c)}),De(t.annotations,On,c=>{r=c(r)}),Qm.set(t,r),r}i(Jc,"fromApi");var FS="effect/httpapi/stream/failure";function jS(t){return Km(Hn(t),Qt,Xm)}i(jS,"extractSuccessResponseBodies");function Km(t,e,r){let n=new Map;return t.forEach(a),n;function a(l){if(Ze(l)){f(l);return}let m=l.ast,y=e(m);en(m)?c(y,r(l.ast)??"<No Content>"):p(l,y,yr(m))}i(a,"process");function c(l,m){let y=n.get(l);y===void 0?n.set(l,{descriptions:new Set([m]),content:void 0,streamContent:void 0}):m!==void 0&&y.descriptions.add(m)}i(c,"addNoContent");function p(l,m,y){let g=r(l.ast),E=n.get(m),{_tag:v,contentType:h}=y;if(E===void 0)n.set(m,{descriptions:new Set(g!==void 0?[g]:[]),content:new Map([[v,new Map([[h,new Set([l])]])]]),streamContent:void 0});else if(g!==void 0&&E.descriptions.add(g),E.content===void 0)E.content=new Map([[v,new Map([[h,new Set([l])]])]]);else{let w=E.content.get(v);if(w===void 0)E.content.set(v,new Map([[h,new Set([l])]]));else{let C=w.get(h);C===void 0?w.set(h,new Set([l])):C.add(l)}}}i(p,"addContent");function f(l){let m=xn(l),y=n.get(m);y===void 0?n.set(m,{descriptions:new Set,content:void 0,streamContent:new Map([[l.contentType,l]])}):y.streamContent===void 0?y.streamContent=new Map([[l.contentType,l]]):y.streamContent.set(l.contentType,l)}i(f,"addStreamContent")}i(Km,"extractResponseBodies");function Xm(t){return Bd(t)??os(t)}i(Xm,"resolveDescriptionOrIdentifier");var Jm=_r.annotate({format:"binary"});function Ym(t,e){switch(e){case"Uint8Array":return Jm.ast;case"Text":return _r.ast;case"FormUrlEncoded":case"Json":return t;case"Multipart":return Zm(t)}}i(Ym,"toEncodingAST");function Zm(t){return Md(t)&&t.annotations?.typeConstructor?._tag==="effect/http/PersistedFile"?Jm.ast:typeof t?.recur=="function"?t.recur(Zm):t}i(Zm,"persistedFileToBinaryEncoding");var GS=i(t=>{let e={};switch(De(t.annotations,rn,r=>{e.description=r}),t._tag){case"Basic":return{...e,type:"http",scheme:"basic"};case"Http":{let r=cc(t.annotations,js).pipe(hd(n=>({bearerFormat:n})),gd);return{...e,type:"http",scheme:t.scheme,...r}}case"ApiKey":return{...e,type:"apiKey",name:t.key,in:t.in}}},"makeSecurityScheme");var WS=i((t,e)=>Su(fc(function*(r){let n=yield*rs(),a=[],c=Array.from(n.mapUnsafe.keys()).filter(p=>p.startsWith("effect/httpapi/HttpApiGroup/"));for(let p of Object.values(t.groups)){let f=n.mapUnsafe.get(p.key)?.routes;if(f===void 0){let l=c.length===0?"none":c.join(", ");return yield*dc(`HttpApiGroup "${p.identifier}" not found (key: "${p.key}"). Did you forget to provide HttpApiBuilder.group(api, "${p.identifier}", ...)? Available groups: ${l}`)}a.push(...f)}if(yield*r.addAll(a),e?.openapiPath){let p=Jc(t);yield*r.add("GET",e.openapiPath,re(Gi(p)))}})),"layer"),$S=i((t,e,r)=>vi(es(function*(){let n=(yield*rs()).pipe(Jo(Zo)),a=t.groups[e],c=r(KS(a)),p=Ei(c)?yield*c:c,f=[];for(let l of p.handlers.values())f.push(sl(a,l,n));return gi(new Map([[a.key,{routes:f,handlers:p.handlers}]]))})),"group"),rl=Symbol.for("@effect/platform/HttpApiBuilder/Handlers"),VS=i((t,e,r,n)=>kd(a=>{let c=t.groups[e],p=c.endpoints[r];return re(ol(c,p,Jo(Zo)(a),n,!1))}),"endpoint"),nl=i(t=>{switch(t._tag){case"Http":return ts(Wi,e=>oo((e.headers.authorization??"").slice(t.schemeLength+1)));case"ApiKey":{let e=t.in==="header"?t.key.toLowerCase():t.key,r=En({[e]:_r}),n=t.in==="query"?fu(r):t.in==="cookie"?mu(r):lu(r);return mc(n,{onFailure:i(()=>oo(""),"onFailure"),onSuccess:i(a=>oo(a[e]),"onSuccess")})}case"Basic":{let e={username:"",password:oo("")};return Wi.pipe(pr(r=>uc(Pd((r.headers.authorization??"").slice(QS)))),mc({onFailure:i(()=>e,"onFailure"),onSuccess:i(r=>{let n=r.split(":");return n.length!==2?e:{username:n[0],password:oo(n[1])}},"onSuccess")}))}}},"securityDecode"),zS=i((t,e,r)=>gu((n,a)=>Bt(iu(a,t.key,Td(e),{secure:!0,httpOnly:!0,...r}))),"securitySetCookie"),QS=6,YS={[rl]:{_Endpoints:hn},pipe(){return qr(this,arguments)},handle(t,e,r){let n=this.group.endpoints[t];return this.handlers.set(t,{endpoint:n,handler:e,isRaw:!1,uninterruptible:r?.uninterruptible??!1}),this},handleRaw(t,e,r){let n=this.group.endpoints[t];return this.handlers.set(t,{endpoint:n,handler:e,isRaw:!0,uninterruptible:r?.uninterruptible??!1}),this}},KS=i(t=>{let e=Object.create(YS);return e.group=t,e.handlers=new Map,e},"makeHandlers");function XS(t){let e=new Map;return t.forEach(({encoding:r,schemas:n},a)=>{let c=as(Oi(n));r._tag==="Multipart"?e.set(a,{_tag:"Multipart",mode:r.mode,limits:r.limits,decode:c}):e.set(a,{_tag:r._tag,decode:c,nullOnEmpty:n.some(p=>Ld(Sn(p.ast)))})}),e}i(XS,"buildPayloadDecoders");function JS(t,e,r){let n=ao(e.method),a=n?ev(e):"application/x-www-form-urlencoded",c=t.get(a);if(!c)return ji(`Unsupported content-type: ${a}`,{status:415});let{_tag:p,decode:f}=c;switch(p){case"Multipart":{if(c.mode==="buffered"){let m=Bt(e.multipart);return c.limits&&(m=lc(m,kc(c.limits))),pr(m,f)}return re(c.limits?Pi(e.multipartStream,kc(c.limits)):e.multipartStream)}case"Json":let l=Bt(pr(e.text,m=>m===""?c.nullOnEmpty?re(null):Dd:re(JSON.parse(m))));return pr(l,f);case"Text":return pr(Bt(e.text),f);case"FormUrlEncoded":{let m=n?ts(Bt(e.urlParamsBody),ru):re(r);return pr(m,f)}case"Uint8Array":return pr(ts(Bt(e.arrayBuffer),m=>new Uint8Array(m)),f)}}i(JS,"decodePayload");function ol(t,e,r,n,a){let c=cs(yv(e)),p=cs(gv(e)),f=Ti(e.params,as),l=Ti(e.headers,as),m=Ti(e.query,as),y=ov(e),E=e.payload.size>0&&!a?XS(e.payload):void 0;return tv(t,e,r,es(function*(){let h=Fd().context,w=Xo(h,Wi),C=Xo(h,hu),R=Xo(h,uu),b={request:w,endpoint:e,group:t};if(f&&(b.params=yield*ct.wrap("Params",f(C.params))),l&&(b.headers=yield*ct.wrap("Headers",l(w.headers))),m&&(b.query=yield*ct.wrap("Query",m(R))),E){let Se=JS(E,w,R);if(Fi(Se))return Se;Se!==void 0&&(b.payload=yield*ct.wrap("Payload",Se))}let O=yield*n(b);if(Fi(O))return O;let Z=y?.(O,h);return Z!==void 0?yield*ct.wrap("Body",Z):yield*ct.wrap("Body",c(O))})).pipe(xd,Ai(v=>ct.is(v)?dc(v):Bt(p(v))),lc(r))}i(ol,"handlerToHttpEffect");function sl(t,e,r){let n=e.endpoint;return vu(n.method,n.path,ol(t,n,r,e.handler,e.isRaw),{uninterruptible:e.uninterruptible})}i(sl,"handlerToRoute");var ZS=i(t=>t.headers["content-type"]?t.headers["content-type"].toLowerCase().trim():"application/json","getRequestContentType"),ev=i(t=>{let e=ZS(t),r=e.indexOf(";");return r===-1?e:e.slice(0,r).trim()},"getRequestMediaType"),tv=i((t,e,r,n)=>{let a={group:t,endpoint:e};for(let c of e.middlewares){let p=c,f=Xo(r,p);n=(Us(p)?rv(p,f):f)(n,a)}return n},"applyMiddleware"),el=new WeakMap,rv=i((t,e)=>{let r=el.get(e);if(r!==void 0)return r;let n=Object.entries(t.security).map(([c,p])=>({decode:nl(p),middleware:e[c]}));if(n.length===0)return hn;let a=fc(function*(c,p){let f;for(let l=0;l<n.length;l++){let{decode:m,middleware:y}=n[l],g=yield*Rd(pr(m,E=>y(c,{credential:E,endpoint:p.endpoint,group:p.group})));if(Sd(g)){f=g;continue}return g.success}return yield*uc(f)});return el.set(e,a),a},"makeSecurityMiddleware"),nv=bi(Fi);function ov(t){let e=sv(t);if(e===void 0)return;let r=iv(t),n=xn(e),a=e.contentType;if(Gc(e))return(p,f)=>ss(p)?re(Rc(Pi(p,f),{status:n,contentType:a})):r?void 0:tl(p);let c=av(e);return(p,f)=>ss(p)?re(Rc(Pi(cv(p,c),f),{status:n,contentType:a})):r?void 0:tl(p)}i(ov,"makeStreamEncoder");function sv(t){for(let e of t.success)if(Ze(e))return e}i(sv,"getStreamSuccessSchema");function iv(t){for(let e of t.success)if(vn(e)&&!Ze(e))return!0;return t.success.size===0}i(iv,"hasBufferedSuccess");function tl(t){return no(mv(new yc(fi(t),{message:"Expected a streaming response"})))}i(tl,"expectedStreamResponse");function av(t){let e=An(Li(t.error,Ui()));return{sseMode:t.sseMode,encodeEvents:cs(eu(t.events)),encodeCause:cs(ps(e))}}i(av,"makeSseEncoder");function cv(t,e){return t.pipe(e.sseMode==="data"?Ft(r=>({id:void 0,event:"message",data:r})):hn,Wd(r=>Bt(e.encodeEvents(r))),Vd(r=>jd(pv(r,e))),Ft(uv),Nr)}i(cv,"encodeSseStream");function pv(t,e){return e.encodeCause(t).pipe(Bt,ts(r=>({id:void 0,event:dv,data:r})))}i(pv,"encodeFailureEvent");var dv="effect/httpapi/stream/failure";function uv(t){return Mu.write({_tag:"Event",event:t.event,id:t.id,data:t.data})}i(uv,"renderSseEvent");function mv(t){return new Yd(t)}i(mv,"makeSchemaError");var lv=il(Qt),fv=il(kn);function yv(t){let e=Hn(t).map(lv);return e.length===1?e[0]:Oi(e)}i(yv,"makeSuccessSchema");function gv(t){let e=Pn(t).map(fv);return e.length===0?qi:e.length===1?e[0]:Oi(e)}i(gv,"makeErrorSchema");function il(t){let e=new WeakMap;return r=>{let n=e.get(r.ast);if(n!==void 0)return n;let a=nv.pipe(Mi(r,hv(t,r)));return e.set(a.ast,a),a}}i(il,"toResponseSchema");function hv(t,e){let r=e.ast,n=Sv(t(r),yr(r),en(r));return qd({decode:i(a=>no(new bd(fi(a),{message:"Encode only schema"})),"decode"),encode:n})}i(hv,"getResponseTransformation");function Sv(t,e,r){switch(e._tag){case"Json":return n=>{if(n===void 0||r)return re(Be({status:t}));try{let a=JSON.stringify(n);return re(ji(a,{status:t,contentType:e.contentType}))}catch(a){return no(new yc(fi(n),{message:globalThis.String(a)}))}};case"Text":return n=>re(ji(n,{status:t,contentType:e.contentType}));case"Uint8Array":return n=>re(nu(n,{status:t,contentType:e.contentType}));case"FormUrlEncoded":return n=>re(ou(n,{status:t}).pipe(su("content-type",e.contentType)))}}i(Sv,"getResponseEncode");var H={};me(H,{isHttpApiGroup:()=>vv,make:()=>Av});var ep="~effect/httpapi/HttpApiGroup",vv=i(t=>St(t,ep),"isHttpApiGroup"),Ev={[ep]:ep,add(...t){let e={...this.endpoints};for(let r of t)e[r.name]=r;return nn({identifier:this.identifier,topLevel:this.topLevel,endpoints:e,annotations:this.annotations})},prefix(t){return nn({identifier:this.identifier,topLevel:this.topLevel,endpoints:Or(this.endpoints,e=>e.prefix(t)),annotations:this.annotations})},middleware(t){return nn({identifier:this.identifier,topLevel:this.topLevel,endpoints:Or(this.endpoints,e=>e.middleware(t)),annotations:this.annotations})},annotateMerge(t){return nn({identifier:this.identifier,topLevel:this.topLevel,endpoints:this.endpoints,annotations:Ct(this.annotations,t)})},annotate(t,e){return nn({identifier:this.identifier,topLevel:this.topLevel,endpoints:this.endpoints,annotations:Lr(this.annotations,t,e)})},annotateEndpointsMerge(t){return nn({identifier:this.identifier,topLevel:this.topLevel,endpoints:Or(this.endpoints,e=>e.annotateMerge(t)),annotations:this.annotations})},annotateEndpoints(t,e){return nn({identifier:this.identifier,topLevel:this.topLevel,endpoints:Or(this.endpoints,r=>r.annotate(t,e)),annotations:this.annotations})},pipe(){return qr(this,arguments)}},nn=i(t=>{function e(){}return i(e,"HttpApiGroup"),Object.setPrototypeOf(e,Ev),e.key=`effect/httpapi/HttpApiGroup/${t.identifier}`,Object.assign(e,t)},"makeProto"),Av=i((t,e)=>nn({identifier:t,topLevel:e?.topLevel??!1,endpoints:vd(),annotations:Mr()}),"make");import{createServer as iR}from"node:http";var ko={};me(ko,{MDNS:()=>ko,publish:()=>pE,unpublish:()=>jl});var Fl=oc(Bl(),1);var rr,Ua;function pE(t,e){if(Ua!==t){rr&&jl();try{let r=e??"opencode.local",n=`opencode-${t}`;rr=new Fl.Bonjour,rr.publish({name:n,type:"http",host:r,port:t,txt:{path:"/"}}).on("error",()=>{}),Ua=t}catch{if(rr)try{rr.destroy()}catch{}rr=void 0,Ua=void 0}}}i(pE,"publish");function jl(){if(rr){try{rr.unpublishAll(),rr.destroy()}catch{}rr=void 0,Ua=void 0}}i(jl,"unpublish");var yn={};me(yn,{HttpApiApp:()=>yn,context:()=>$D,createRoutes:()=>uh,routes:()=>mh,webHandler:()=>sR});var zs={};me(zs,{PluginPtyEnvironment:()=>zs,layer:()=>uE});var nr={};me(nr,{PtyEnvironment:()=>nr,Service:()=>Ho,layer:()=>Gl,node:()=>dE});var Ho=class extends oe.Service()("@opencode/ServerPtyEnvironment"){static{i(this,"Service")}},Gl=P.succeed(Ho,Ho.of({get:i(()=>s.succeed({}),"get")})),dE=Fr({service:Ho,layer:Gl,deps:[]});var uE=P.effect(nr.Service,s.gen(function*(){let t=yield*wo.Service,e=yield*It.Service;return nr.Service.of({get:s.fn("PtyEnvironment.get")(function*(r){return yield*e.provide({directory:r.directory},t.trigger("shell.env",{cwd:r.cwd},{env:{}}).pipe(s.map(n=>n.env)))})})}));var Mt={};me(Mt,{ApplyChangesError:()=>Qs,CaptureChangesError:()=>Ys,Destination:()=>Wl,DestinationProjectMismatchError:()=>Na,Input:()=>lE,MoveSession:()=>Mt,ResetSourceChangesError:()=>Ks,Service:()=>Po,node:()=>yE});import mE from"path";var Wl=o.Struct({directory:we}).annotate({identifier:"MoveSession.Destination"}),lE=o.Struct({sessionID:Wu.ID,destination:Wl,moveChanges:o.optional(o.Boolean)}).annotate({identifier:"MoveSession.Input"}),Na=class extends o.TaggedErrorClass()("MoveSession.DestinationProjectMismatchError",{expected:Fe.ID,actual:Fe.ID}){static{i(this,"DestinationProjectMismatchError")}},Qs=class extends o.TaggedErrorClass()("MoveSession.ApplyChangesError",{message:o.String}){static{i(this,"ApplyChangesError")}},Ys=class extends o.TaggedErrorClass()("MoveSession.CaptureChangesError",{message:o.String}){static{i(this,"CaptureChangesError")}},Ks=class extends o.TaggedErrorClass()("MoveSession.ResetSourceChangesError",{directory:we,message:o.String,cause:o.optional(o.Defect())}){static{i(this,"ResetSourceChangesError")}},Po=class extends oe.Service()("@opencode/ControlPlaneMoveSession"){static{i(this,"Service")}},fE=P.effect(Po,s.gen(function*(){let t=yield*uo.Service,e=yield*fe.Service,r=yield*Fe.Service,n=yield*mo.Service,a=s.fn("MoveSession.moveSession")(function*(c){let p=yield*n.get(c.sessionID);if(!p)return yield*new Et.NotFoundError({sessionID:c.sessionID});let f=we.make(c.destination.directory);if(p.location.directory===f)return;let l=yield*r.resolve(p.location.directory),m=yield*r.resolve(f);if(p.projectID!==m.id)return yield*new Na({expected:p.projectID,actual:m.id});let y=c.moveChanges&&l.directory!==m.directory,g=y?yield*t.repo.discover(p.location.directory):void 0;if(y&&!g)return yield*new Ys({message:"Source is not a Git repository"});let E=g?yield*t.change.capture({repository:g,path:p.location.directory}).pipe(s.mapError(v=>new Ys({message:v.message}))):uo.ChangeSet.make("");if(E){let v=yield*t.repo.discover(f);if(!v)return yield*new Qs({message:"Destination is not a Git repository"});yield*t.change.apply({repository:v,path:f,changes:E}).pipe(s.mapError(h=>new Qs({message:h.message})))}if(yield*e.publish(Dn.Moved,{sessionID:c.sessionID,location:ce.Ref.make({directory:f}),subdirectory:vt.make(mE.relative(m.directory,f).replaceAll("\\","/")),timestamp:yield*ns.now}),E){let v=yield*t.repo.discover(p.location.directory);if(!v)return yield*new Ks({directory:p.location.directory,message:"Source is not a Git repository"});yield*t.change.discard({repository:v,path:p.location.directory,index:"preserve",untracked:"remove"}).pipe(s.mapError(h=>new Ks({directory:p.location.directory,message:h.message,cause:h.cause})))}});return Po.of({moveSession:a})})),yE=Fr({service:Po,layer:fE,deps:[uo.node,fe.node,Fe.node,mo.node]});var wt={};me(wt,{ConnectToken:()=>vE,PtyTicket:()=>wt,Service:()=>To,make:()=>$l,node:()=>wE});var Bn={};me(Bn,{ConnectToken:()=>gE,PtyTicket:()=>Bn});var gE=o.Struct({ticket:o.String,expires_in:In}).annotate({identifier:"PtyTicket.ConnectToken"});var hE=Si.seconds(60),SE=1e4,vE=Bn.ConnectToken,To=class extends oe.Service()("@opencode/PtyTicket"){static{i(this,"Service")}};function EE(t,e){return t.ptyID===e.ptyID&&t.directory===e.directory&&t.workspaceID===e.workspaceID}i(EE,"matches");var AE=i(()=>s.die("PtyTicket cache must be used via set/invalidateWhen, never get"),"noLookup"),$l=i((t=hE)=>s.gen(function*(){let e=yield*Vi.make({capacity:SE,lookup:AE,timeToLive:t}),r=Math.max(1,Math.round(Si.toSeconds(Si.fromInputUnsafe(t))));return To.of({issue:s.fn("PtyTicket.issue")(function*(n){let a=crypto.randomUUID();return yield*Vi.set(e,a,n),{ticket:a,expires_in:r}}),consume:s.fn("PtyTicket.consume")(function*(n){return yield*Vi.invalidateWhen(e,n.ticket,a=>EE(a,n))})})}),"make"),IE=P.effect(To,$l()),wE=Fr({service:To,layer:IE,deps:[]});var Xs={};me(Xs,{SessionRunCoordinator:()=>Xs,make:()=>DE});var DE=i(t=>s.gen(function*(){let e=new Map,r=yield*cu.makeRuntime(),n=i(()=>({done:cr.makeUnsafe(),pendingWake:!1,stopping:!1}),"makeEntry"),a=i((m,y,g,E=!1)=>{let v=cr.makeUnsafe(),h=r((E?s.yieldNow:cr.await(v)).pipe(s.andThen(s.suspend(()=>t.drain(m,g))),s.onExit(w=>s.sync(()=>c(m,y,w))),s.exit,s.asVoid));y.owner=h,E||cr.doneUnsafe(v,s.void)},"start"),c=i((m,y,g)=>{if(ro.isSuccess(g)&&!y.stopping&&y.pendingWake){y.pendingWake=!1,a(m,y,!1,!0);return}let E=y.pendingWake?n():void 0;E===void 0?e.delete(m):(e.set(m,E),a(m,E,!1,!0)),cr.doneUnsafe(y.done,g)},"settle"),p=i(m=>s.uninterruptibleMask(y=>{let g=e.get(m);if(g!==void 0)return g.stopping?y(cr.await(g.done).pipe(s.andThen(p(m)))):y(cr.await(g.done));let E=n();return e.set(m,E),a(m,E,!0),y(cr.await(E.done))}),"run"),f=i(m=>s.sync(()=>{let y=e.get(m);if(y!==void 0){y.pendingWake=!0;return}let g=n();e.set(m,g),a(m,g,!1)}),"wake"),l=i(m=>s.suspend(()=>{let y=e.get(m);return y?.owner===void 0?s.void:(y.stopping=!0,y.pendingWake=!1,Ac.interrupt(y.owner))}),"interrupt");return{active:s.sync(()=>new Set(e.keys())),run:p,wake:f,interrupt:l}}),"make");var RE=P.effect(lo.Service,s.gen(function*(){let t=yield*mo.Service,e=yield*Ge.Service,r=yield*Xs.make({drain:s.fnUntraced(function*(n,a){let c=yield*t.get(n);return c?yield*Ku.Service.use(p=>p.run({sessionID:n,force:a})).pipe(s.provide(e.get(c.location)),s.tapCause(p=>_t.hasInterruptsOnly(p)?s.void:s.logError("Failed to drain Session",p).pipe(s.annotateLogs({sessionID:n})))):yield*s.die(`Session not found: ${n}`)})});return lo.Service.of({active:r.active,interrupt:r.interrupt,resume:r.run,wake:r.wake})})),Vl=Fr({service:lo.Service,layer:RE,deps:[mo.node,Ge.node]});function Js(t){let e,r=!1,n=i(()=>(r||(e=t(),r=!0),e),"result");return n.reset=()=>{r=!1,e=void 0},n.loaded=()=>r,n}i(Js,"lazy");var CE=/^https:\/\/([a-z0-9-]+\.)*opencode\.ai$/,Fn=oe.Reference("@opencode/ServerCorsConfig",{defaultValue:i(()=>{},"defaultValue")});function Dp(t,e){return!t||t.startsWith("http://localhost:")||t.startsWith("http://127.0.0.1:")||t.startsWith("oc://renderer")||t==="tauri://localhost"||t==="http://tauri.localhost"||t==="https://tauri.localhost"||CE.test(t)?!0:e?.cors?.includes(t)??!1}i(Dp,"isAllowedCorsOrigin");function Zs(t,e,r){return!t||e&&xE(t,e)?!0:Dp(t,r)}i(Zs,"isAllowedRequestOrigin");function xE(t,e){try{return new URL(t).host===e}catch{return!1}}i(xE,"sameHost");import{createHash as qE}from"node:crypto";var Cr={};me(Cr,{ProxyUtil:()=>Cr,headers:()=>PE,websocketProtocols:()=>TE,websocketTargetURL:()=>bE});var kE=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade","host"]);function HE(t){for(let e of kE)t.delete(e);t.delete("accept-encoding"),t.delete("x-opencode-directory"),t.delete("x-opencode-workspace")}i(HE,"sanitize");function PE(t,e){let r=t instanceof Request?t.headers:t,n=new Headers(r instanceof Headers?r:Object.entries(r));if(HE(n),!e)return n;for(let[a,c]of new Headers(e).entries())n.set(a,c);return n}i(PE,"headers");function TE(t){let e=t instanceof Request?t.headers.get("sec-websocket-protocol"):t["sec-websocket-protocol"];return e?e.split(",").map(r=>r.trim()).filter(Boolean):[]}i(TE,"websocketProtocols");function bE(t){let e=new URL(t);return e.protocol==="http:"&&(e.protocol="ws:"),e.protocol==="https:"&&(e.protocol="wss:"),e.toString()}i(bE,"websocketTargetURL");var OE,Yl=new URL("https://app.opencode.ai"),Rp=i((t="")=>`default-src 'self'; script-src 'self' 'wasm-unsafe-eval'${t?` 'sha256-${t}'`:""}; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: blob:; font-src 'self' data:; media-src 'self' data:; connect-src * data: blob:`,"csp"),Wx=Rp();function ME(t){return t.match(/<script\b(?![^>]*\bsrc\s*=)[^>]*\bid=(['"])oc-theme-preload-script\1[^>]*>([\s\S]*?)<\/script>/i)}i(ME,"themePreloadHash");function Kl(t){let e=ME(t);return Rp(e?qE("sha256").update(e[2]).digest("base64"):"")}i(Kl,"cspForHtml");function LE(t){if(t.method==="GET"||t.method==="HEAD")return ur.empty;let e=t.headers["content-length"];return ur.stream(t.stream,t.headers["content-type"],e===void 0?void 0:Number(e))}i(LE,"requestBody");function UE(t){let e=new Headers(t);return e.delete("content-encoding"),e.delete("content-length"),e.delete("transfer-encoding"),e}i(UE,"proxyResponseHeaders");function NE(t){return new URL(t,Yl).toString()}i(NE,"upstreamURL");function _E(t){return t?Promise.resolve(null):OE??=import("opencode-web-ui.gen.ts").then(e=>e.default).catch(()=>null)}i(_E,"embeddedUI");function Ql(){return q.jsonUnsafe({error:"Not Found"},{status:404})}i(Ql,"notFound");function BE(t,e){let r=mr.mimeType(t),n=new Headers({"content-type":r});return r.startsWith("text/html")&&n.set("content-security-policy",Kl(new TextDecoder().decode(e))),q.raw(e,{headers:n})}i(BE,"embeddedUIResponse");function FE(t,e,r){let n=r[t.replace(/^\//,"")]??r["index.html"]??null;return n?e.readFile(n).pipe(s.map(a=>BE(n,a)),s.catchReason("PlatformError","NotFound",()=>s.succeed(Ql()))):s.succeed(Ql())}i(FE,"serveEmbeddedUIEffect");function Xl(t,e){return s.gen(function*(){let r=yield*s.promise(()=>_E(e.disableEmbeddedWebUi)),n=new URL(t.url,"http://localhost").pathname;if(r)return yield*FE(n,e.fs,r);let a=yield*e.client.execute(_i.make(t.method)(NE(n),{headers:Cr.headers(t.headers,{host:Yl.host}),body:LE(t)})),c=UE(a.headers);if(a.headers["content-type"]?.includes("text/html")){let p=yield*a.text;return c.set("Content-Security-Policy",Kl(p)),q.text(p,{status:a.status,headers:c})}return c.set("Content-Security-Policy",Rp()),q.stream(a.stream.pipe(se.catchCause(()=>se.empty)),{status:a.status,headers:c})})}i(Xl,"serveUIEffect");var xr={};me(xr,{Definitions:()=>_a,Durable:()=>Ji,EventManifest:()=>xr,Latest:()=>Cp});var ei={};me(ei,{Definitions:()=>_a,Durable:()=>Ji,EventManifest:()=>ei,Latest:()=>Cp,ServerDefinitions:()=>VE});var jn={};me(jn,{Connected:()=>Jl,Definitions:()=>jE,Disposed:()=>Zl,ServerEvent:()=>jn});var Jl=st.define({type:"server.connected",schema:{}}),Zl=st.define({type:"global.disposed",schema:{}}),jE=st.inventory(Jl,Zl);var GE=Tc.Event.Definitions.filter(t=>t.durable!==void 0),WE=Tc.Event.Definitions.filter(t=>t.durable===void 0),$E=st.inventory(...GE,...Dn.Definitions),ef=st.inventory(...nm.Event.Definitions,...Ye.Event.Definitions,...Cu.Event.Definitions,...$E),tf=st.inventory(...Rn.Event.Definitions,...ta.Event.Definitions,...be.Event.Definitions,...Xu.Event.Definitions,...om.Event.Definitions,...Gu.Event.Definitions,...Ke.Event.Definitions,...Yr.Event.Definitions),VE=st.inventory(...ef,...tf,...Oc.Event.Definitions),_a=st.inventory(...ef,...WE,...bm.Definitions,...tf,...Oc.Event.Definitions,...Rm.Definitions,...Nu.Event.Definitions,...ie.Definitions,...Em.Definitions,...xm.Definitions,...Ht.Event.Definitions,...Sm.Definitions,...hm.Event.Definitions,...Im.Definitions,...km.Definitions,...$u.Definitions,...Tm.Definitions,...jn.Definitions),Cp=st.latest(_a);var rf=jn,Ba=o.Struct({id:o.String,type:o.Literal("server.instance.disposed"),properties:o.Struct({directory:o.String})}).annotate({identifier:"Event.server.instance.disposed"});var ti="ticket",nf="x-opencode-ticket";var zE=/^\/pty\/[^/]+\/connect$/;function QE(t){return zE.test(t)}i(QE,"isPtyConnectPath");function of(t){return QE(t.pathname)&&!!t.searchParams.get(ti)}i(of,"hasPtyConnectTicketURL");var YE=new Set(["/site.webmanifest","/web-app-manifest-192x192.png","/web-app-manifest-512x512.png"]);function sf(t,e){return t==="GET"&&YE.has(e)}i(sf,"isPublicUIPath");var Gn={};me(Gn,{Config:()=>xp,ServerAuth:()=>Gn,authorized:()=>XE,header:()=>af,headers:()=>JE,required:()=>KE});var xp=class t extends oe.Service()("@opencode/ServerAuthConfig"){static{i(this,"Config")}static configLayer(e){return P.succeed(this,this.of(e))}static get layer(){return P.effect(this,s.gen(function*(){return t.of(yield*co.all({password:co.string("OPENCODE_SERVER_PASSWORD").pipe(co.option),username:co.string("OPENCODE_SERVER_USERNAME").pipe(co.withDefault("opencode"))}))}))}};function KE(t){return Ce.isSome(t.password)&&t.password.value!==""}i(KE,"required");function XE(t,e){return Ce.isSome(e.password)&&t.username===e.username&&dr.value(t.password)===e.password.value}i(XE,"authorized");function af(t){let e=t?.password??process.env.OPENCODE_SERVER_PASSWORD;if(e)return`Basic ${Buffer.from(`${t?.username??process.env.OPENCODE_SERVER_USERNAME??"opencode"}:${e}`).toString("base64")}`}i(af,"header");function JE(t){let e=af(t);if(e)return{Authorization:e}}i(JE,"headers");var Pe=class extends o.TaggedErrorClass()("InvalidRequestError",{message:o.String,kind:o.optional(o.String),field:o.optional(o.String)},{httpApiStatus:400}){static{i(this,"InvalidRequestError")}},bo=class extends o.TaggedErrorClass()("UnauthorizedError",{message:o.String},{httpApiStatus:401}){static{i(this,"UnauthorizedError")}},qo=class extends o.TaggedErrorClass()("ConflictError",{message:o.String,resource:o.optional(o.String)},{httpApiStatus:409}){static{i(this,"ConflictError")}},mt=class extends o.TaggedErrorClass()("ServiceUnavailableError",{message:o.String,service:o.optional(o.String)},{httpApiStatus:503}){static{i(this,"ServiceUnavailableError")}},tt=class extends o.TaggedErrorClass()("UnknownError",{message:o.String,ref:o.optional(o.String)},{httpApiStatus:500}){static{i(this,"UnknownError")}},Oo=class extends o.TaggedErrorClass()("ProviderNotFoundError",{providerID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"ProviderNotFoundError")}},N=class extends o.TaggedErrorClass()("SessionNotFoundError",{sessionID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"SessionNotFoundError")}},an=class extends o.TaggedErrorClass()("MessageNotFoundError",{sessionID:o.String,messageID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"MessageNotFoundError")}},Lt=class extends o.TaggedErrorClass()("InvalidCursorError",{message:o.String},{httpApiStatus:400}){static{i(this,"InvalidCursorError")}},Wn=class extends o.TaggedErrorClass()("PermissionNotFoundError",{requestID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"PermissionNotFoundError")}},$n=class extends o.TaggedErrorClass()("QuestionNotFoundError",{requestID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"QuestionNotFoundError")}},Vn=class extends o.TaggedErrorClass()("ForbiddenError",{message:o.String},{httpApiStatus:403}){static{i(this,"ForbiddenError")}},lt=class extends o.TaggedErrorClass()("PtyNotFoundError",{ptyID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"PtyNotFoundError")}};var or=class extends ge.Service()("@opencode/HttpApiAuthorization",{error:bo}){static{i(this,"Authorization")}};var _=o.Struct({location:o.optional(o.Struct({directory:o.optional(o.String),workspace:o.optional(o.String)}))}).annotate({identifier:"LocationQuery"}),B=d.annotations({transform:i(t=>{let e=t.parameters;return Array.isArray(e)?{...t,parameters:e.map(r=>r?.name==="location"&&r?.in==="query"?{...r,style:"deepObject",explode:!0}:r)}:t},"transform")}),cf=H.make("server.location").add(u.get("location.get","/api/location",{query:_,success:z.Info}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.location.get",summary:"Get location",description:"Resolve the requested location or the server default location."})));var Fa="ticket",pf="x-opencode-ticket",df="1",ZE=/^\/api\/pty\/[^/]+\/connect$/;function uf(t){return ZE.test(t.pathname)&&!!t.searchParams.get(Fa)}i(uf,"hasPtyConnectTicketURL");var mf=H.make("server.pty").add(u.get("pty.list","/api/pty",{query:_,success:z.response(o.Array(Ke.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.list",summary:"List PTY sessions",description:"List PTY sessions for a location, including exited sessions retained until removal."}))).add(u.post("pty.create","/api/pty",{query:_,payload:Ke.CreateInput,success:z.response(Ke.Info)}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.create",summary:"Create PTY session",description:"Create a pseudo-terminal session for a location."}))).add(u.get("pty.get","/api/pty/:ptyID",{params:{ptyID:Ke.ID},query:_,success:z.response(Ke.Info),error:lt}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.get",summary:"Get PTY session",description:"Get one PTY session, including its exit code once exited."}))).add(u.put("pty.update","/api/pty/:ptyID",{params:{ptyID:Ke.ID},query:_,payload:Ke.UpdateInput,success:z.response(Ke.Info),error:lt}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.update",summary:"Update PTY session",description:"Update the title or viewport size of one PTY session."}))).add(u.delete("pty.remove","/api/pty/:ptyID",{params:{ptyID:Ke.ID},query:_,success:k.NoContent,error:lt}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.remove",summary:"Remove PTY session",description:"Terminate and remove one PTY session."}))).add(u.post("pty.connectToken","/api/pty/:ptyID/connect-token",{params:{ptyID:Ke.ID},query:_,success:z.response(Bn.ConnectToken),error:[Vn,lt]}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.connectToken",summary:"Create PTY WebSocket token",description:"Create a short-lived single-use ticket for opening a PTY WebSocket connection."}))).add(u.get("pty.connect","/api/pty/:ptyID/connect",{params:{ptyID:Ke.ID},success:o.Boolean,error:[Vn,lt]}).annotateMerge(d.annotations({identifier:"v2.pty.connect",summary:"Connect to PTY session",description:"Establish a WebSocket connection streaming PTY output and accepting terminal input.",transform:i(t=>({...t,"x-websocket":!0,parameters:[...t.parameters??[],...["location[directory]","location[workspace]","cursor",Fa].map(e=>({in:"query",name:e,schema:{type:"string"}}))]}),"transform")}))).annotateMerge(d.annotations({title:"pty",description:"Experimental location-scoped PTY routes."}));var eA="auth_token",tA='Basic realm="Secure Area"';function kp(){return{username:"",password:dr.make("")}}i(kp,"emptyCredential");function lf(t){return s.fromResult(Ur.decodeBase64String(t)).pipe(s.match({onFailure:kp,onSuccess:i(e=>{let r=e.indexOf(":");return r===-1?kp():{username:e.slice(0,r),password:dr.make(e.slice(r+1))}},"onSuccess")}))}i(lf,"decodeCredential");function rA(t){let r=new URL(t.url,"http://localhost").searchParams.get(eA);if(r)return lf(r);let n=/^Basic\s+(.+)$/i.exec(t.headers.authorization??"");return n?lf(n[1]):s.succeed(kp())}i(rA,"credentialFromRequest");var Hp=P.effect(or,s.gen(function*(){let t=yield*Gn.Config;return Gn.required(t)?or.of(e=>s.gen(function*(){let r=yield*le.HttpServerRequest;if(uf(new URL(r.url,"http://localhost")))return yield*e;let n=yield*rA(r);return Gn.authorized(n,t)?yield*e:(yield*Br.appendPreResponseHandler((a,c)=>s.succeed(q.setHeader(c,"www-authenticate",tA))),yield*new bo({message:"Authentication required"}))})):or.of(e=>e)}));var nA="auth_token",oA=401,yf='Basic realm="Secure Area"',j=class extends ge.Service()("@opencode/ExperimentalHttpApiAuthorization",{error:D.UnauthorizedNoContent}){static{i(this,"Authorization")}},zn=class extends ge.Service()("@opencode/ExperimentalHttpApiPtyConnectAuthorization",{error:D.UnauthorizedNoContent}){static{i(this,"PtyConnectAuthorization")}};function Pp(){return{username:"",password:dr.make("")}}i(Pp,"emptyCredential");function gf(t,e,r){return s.gen(function*(){return Ne.required(r)?Ne.authorized(e,r)?yield*t:(yield*Br.appendPreResponseHandler((n,a)=>s.succeed(q.setHeader(a,"www-authenticate",yf))),yield*new D.Unauthorized({})):yield*t})}i(gf,"validateCredential");function ff(t){return s.fromResult(Ur.decodeBase64String(t)).pipe(s.match({onFailure:Pp,onSuccess:i(e=>{let r=e.indexOf(":");return r===-1?Pp():{username:e.slice(0,r),password:dr.make(e.slice(r+1))}},"onSuccess")}))}i(ff,"decodeCredential");function sA(t){return Tp(new URL(t.url,"http://localhost"),t)}i(sA,"credentialFromRequest");function Tp(t,e){let r=t.searchParams.get(nA);if(r)return ff(r);let n=/^Basic\s+(.+)$/i.exec(e.headers.authorization??"");return n?ff(n[1]):s.succeed(Pp())}i(Tp,"credentialFromURL");function iA(t,e,r){return Ne.required(r)?Ne.authorized(e,r)?t:s.succeed(q.empty({status:oA,headers:{"www-authenticate":yf}})):t}i(iA,"validateRawCredential");var hf=Ee.middleware()(s.gen(function*(){let t=yield*Ne.Config;return Ne.required(t)?e=>s.gen(function*(){let r=yield*le.HttpServerRequest,n=new URL(r.url,"http://localhost");return sf(r.method,n.pathname)?yield*e:yield*Tp(n,r).pipe(s.flatMap(a=>iA(e,a,t)))}):e=>e})),Sf=P.effect(j,s.gen(function*(){let t=yield*Ne.Config;return Ne.required(t)?j.of(e=>s.gen(function*(){let r=yield*le.HttpServerRequest;return yield*sA(r).pipe(s.flatMap(n=>gf(e,n,t)))})):j.of(e=>e)})),vf=P.effect(zn,s.gen(function*(){let t=yield*Ne.Config;return Ne.required(t)?zn.of(e=>s.gen(function*(){let r=yield*le.HttpServerRequest,n=new URL(r.url,"http://localhost");return of(n)?yield*e:yield*Tp(n,r).pipe(s.flatMap(a=>gf(e,a,t)))})):zn.of(e=>e)}));var Mo={};me(Mo,{HttpApiProxy:()=>Mo,http:()=>lA,websocket:()=>mA});var $e={};me($e,{SERVER_CLOSING_EVENT:()=>aA,Service:()=>Qn,WebSocketTracker:()=>$e,node:()=>pA,register:()=>dA});var aA=i(()=>new Le(1001,"server closing"),"SERVER_CLOSING_EVENT"),Qn=class extends oe.Service()("@opencode/HttpApiWebSocketTracker"){static{i(this,"Service")}},cA=P.sync(Qn)(()=>{let t=new Set,e=!1;return Qn.of({add:i(r=>s.gen(function*(){return e?!1:(t.add(r),!0)}),"add"),remove:i(r=>s.sync(()=>{t.delete(r)}),"remove"),closeAll:s.gen(function*(){e=!0;let r=Array.from(t);t.clear(),yield*s.all(r.map(n=>n.pipe(s.timeout("1 second"),s.catch(()=>s.void))),{concurrency:"unbounded",discard:!0})})})}),pA=zi.make({service:Qn,layer:cA,deps:[]}),dA=i(t=>s.gen(function*(){let e=yield*s.serviceOption(Qn);return Ce.isNone(e)?!0:(yield*e.value.add(t))?(yield*s.addFinalizer(()=>e.value.remove(t)),!0):!1}),"register");function uA(t){if(t.method==="GET"||t.method==="HEAD")return ur.empty;if(t.source instanceof Request&&t.source.body===null)return ur.empty;let e=t.headers["content-length"];return ur.stream(t.stream,t.headers["content-type"],e?Number(e):void 0)}i(uA,"requestBody");function mA(t,e){return s.scoped(s.gen(function*(){let r=yield*s.orDie(t.upgrade),n=yield*du(Cr.websocketTargetURL(e),{protocols:Cr.websocketProtocols(t.headers)}),a=yield*r.writer,c=yield*n.writer,p=i((m,y)=>m.runRaw(()=>s.void,{onOpen:y($e.SERVER_CLOSING_EVENT()).pipe(s.catch(()=>s.void))}).pipe(s.timeout("1 second"),s.catchReason("SocketError","SocketCloseError",()=>s.void),s.catch(()=>s.void)),"closeSocket"),f=s.all([p(r,a),p(n,c)],{concurrency:"unbounded",discard:!0});return(yield*$e.register(s.all([a($e.SERVER_CLOSING_EVENT()),c($e.SERVER_CLOSING_EVENT())],{concurrency:"unbounded",discard:!0})))?(yield*n.runRaw(m=>a(m)).pipe(s.catchReason("SocketError","SocketCloseError",m=>a(new Le(m.code,m.closeReason)).pipe(s.catch(()=>s.void))),s.catch(()=>a(new Le(1011,"proxy error")).pipe(s.catch(()=>s.void))),s.forkScoped),yield*r.runRaw(m=>c(typeof m=="string"?m:m.slice())).pipe(s.catch(()=>s.void),s.ensuring(c(new Le).pipe(s.catch(()=>s.void)))),q.empty()):(yield*f,q.empty())}).pipe(s.orDie))}i(mA,"websocket");function Ef(t){return t.source?.statusText}i(Ef,"statusText");function lA(t,e,r,n){return s.gen(function*(){let a=yield*t.execute(_i.make(n.method)(e,{headers:Cr.headers(n.headers,r),body:uA(n)})),c=new Headers(a.headers);if(c.delete("content-encoding"),c.delete("content-length"),a.status>=500){let p=yield*a.text.pipe(s.catch(()=>s.succeed(""))),f=a.headers["content-type"]??"application/json";return c.delete("content-type"),yield*s.logError("workspace proxy upstream error",{url:e.toString(),method:n.method,status:a.status,body:p.slice(0,2e3)}),q.text(p,{status:a.status,statusText:Ef(a),headers:c,contentType:f})}return q.stream(a.stream.pipe(se.catchCause(()=>se.empty)),{status:a.status,statusText:Ef(a),headers:c})}).pipe(s.catch(()=>s.succeed(q.empty({status:500}))))}i(lA,"http");var bp="x-opencode-sync";function qp(t,e){return s.gen(function*(){let r=yield*(e?.length?t.select().from(Xi).where(Tu(Xi.aggregate_id,e)).all():t.select().from(Xi).all()).pipe(s.orDie);return Object.fromEntries(r.map(n=>[n.aggregate_id,n.seq]))})}i(qp,"load");function Af(t,e){let r=new Set([...Object.keys(t),...Object.keys(e)]);return Object.fromEntries([...r].map(n=>[n,e[n]??-1]).filter(([n,a])=>(t[n]??-1)!==a))}i(Af,"diff");function If(t){let e=t.get(bp);if(!e)return;let r;try{r=JSON.parse(e)}catch{return}if(!(!r||typeof r!="object"))return Object.fromEntries(Object.entries(r).filter(n=>typeof n[0]=="string"&&Number.isInteger(n[1])))}i(If,"parse");function wf(t,e,r){return s.gen(function*(){yield*s.logInfo("waiting for state",{workspaceID:t,state:e}),yield*ye.Service.use(n=>n.waitForSync(t,e,r)),yield*s.logInfo("state fully synced",{workspaceID:t,state:e})})}i(wf,"wait");var fA=[{path:"/experimental/workspace",action:"local"},{path:"/session/status",action:"forward"},{method:"GET",path:"/session",action:"local"}];function Rf(t,e){for(let r of fA){if(r.method&&r.method!==t)continue;if(r.exact?e===r.path:e===r.path||e.startsWith(r.path+"/"))return r.action==="local"}return!1}i(Rf,"isLocalWorkspaceRoute");function Cf(t){if(t.pathname==="/session/status")return null;let e=t.pathname.match(/^\/session\/([^/]+)(?:\/|$)/)?.[1]??t.pathname.match(/^\/experimental\/session\/([^/]+)\/background$/)?.[1];return e?Y.make(e):null}i(Cf,"getWorkspaceRouteSessionID");function xf(t,e){let r=new URL(t);return r.pathname=`${r.pathname.replace(/\/$/,"")}${e.pathname}`,r.search=e.search,r.hash=e.hash,r.searchParams.delete("workspace"),r.searchParams.delete("directory"),r}i(xf,"workspaceProxyURL");var Yn=class extends o.TaggedErrorClass()("InvalidRequestError",{message:o.String,kind:o.optional(o.String),field:o.optional(o.String)},{httpApiStatus:400}){static{i(this,"InvalidRequestError")}},kf=class extends o.TaggedErrorClass()("UnauthorizedError",{message:o.String},{httpApiStatus:401}){static{i(this,"UnauthorizedError")}},Hf=class extends o.TaggedErrorClass()("ForbiddenError",{message:o.String},{httpApiStatus:403}){static{i(this,"ForbiddenError")}},Pf=class extends o.TaggedErrorClass()("ConflictError",{message:o.String,resource:o.optional(o.String)},{httpApiStatus:409}){static{i(this,"ConflictError")}},Tf=class extends o.TaggedErrorClass()("UpstreamError",{message:o.String,service:o.optional(o.String),status:o.optional(o.Number)},{httpApiStatus:502}){static{i(this,"UpstreamError")}},bf=class extends o.TaggedErrorClass()("ServiceUnavailableError",{message:o.String,service:o.optional(o.String)},{httpApiStatus:503}){static{i(this,"ServiceUnavailableError")}},qf=class extends o.TaggedErrorClass()("TimeoutError",{message:o.String,operation:o.optional(o.String)},{httpApiStatus:504}){static{i(this,"TimeoutError")}},Of=class extends o.TaggedErrorClass()("UnknownError",{message:o.String,ref:o.optional(o.String)},{httpApiStatus:500}){static{i(this,"UnknownError")}},Mf=class extends o.TaggedErrorClass()("ProviderNotFoundError",{providerID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"ProviderNotFoundError")}},Lf=class extends o.TaggedErrorClass()("ModelNotFoundError",{providerID:o.String,modelID:o.String,suggestions:o.Array(o.String),message:o.String},{httpApiStatus:404}){static{i(this,"ModelNotFoundError")}},Uf=class extends o.TaggedErrorClass()("SessionNotFoundError",{sessionID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"SessionNotFoundError")}},Nf=class extends o.TaggedErrorClass()("MessageNotFoundError",{sessionID:o.String,messageID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"MessageNotFoundError")}},_f=class extends o.TaggedErrorClass()("InvalidCursorError",{message:o.String},{httpApiStatus:400}){static{i(this,"InvalidCursorError")}},kr=class extends o.TaggedErrorClass()("SessionBusyError",{sessionID:o.String,message:o.String},{httpApiStatus:409}){static{i(this,"SessionBusyError")}},cn=class extends o.TaggedErrorClass()("QuestionNotFoundError",{requestID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"QuestionNotFoundError")}},sr=class extends o.TaggedErrorClass()("PermissionNotFoundError",{requestID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"PermissionNotFoundError")}},_e=class extends o.TaggedErrorClass()("McpServerNotFoundError",{name:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"McpServerNotFoundError")}},Dt=class extends o.TaggedErrorClass()("PtyNotFoundError",{ptyID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"PtyNotFoundError")}},Lo=class extends o.TaggedErrorClass()("PtyForbiddenError",{message:o.String},{httpApiStatus:403}){static{i(this,"PtyForbiddenError")}},Uo=class extends o.TaggedErrorClass()("ProjectNotFoundError",{projectID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"ProjectNotFoundError")}},te=class extends o.ErrorClass("NotFoundError")({name:o.Literal("NotFoundError"),data:o.Struct({message:o.String})},{httpApiStatus:404}){static{i(this,"ApiNotFoundError")}};function ja(t){return new te({name:"NotFoundError",data:{message:t}})}i(ja,"notFound");var xe={directory:o.optional(o.String),workspace:o.optional(o.String)},I=o.Struct(xe),No=pc.taggedEnum(),Ff=Symbol("InvalidWorkspaceID"),_o=class extends oe.Service()("@opencode/ExperimentalHttpApiWorkspaceRouteContext"){static{i(this,"WorkspaceRouteContext")}},W=class extends ge.Service()("@opencode/ExperimentalHttpApiWorkspaceRouting"){static{i(this,"WorkspaceRoutingMiddleware")}};function jf(t){return new URL(t.url,"http://localhost")}i(jf,"requestURL");function yA(){return ms.OPENCODE_WORKSPACE_ID?Vr.ID.make(ms.OPENCODE_WORKSPACE_ID):void 0}i(yA,"configuredWorkspaceID");function gA(t,e){let r=t.searchParams.get("workspace");return e??(r?Vr.ID.make(r):void 0)}i(gA,"selectedWorkspaceID");function hA(t,e){if(e)return e;let r=t.searchParams.get("workspace");if(!r)return;let n=o.decodeUnknownOption(Vr.ID)(r);return Ce.isNone(n)?Ff:n.value}i(hA,"selectedV2WorkspaceID");function SA(t,e){return e.searchParams.get("directory")||t.headers["x-opencode-directory"]||process.cwd()}i(SA,"defaultDirectory");function vA(t,e){return Rf(t.method,e.pathname)||e.pathname.startsWith("/console")}i(vA,"shouldStayOnControlPlane");function EA(t,e){return!t||e?s.void:ye.Service.use(r=>r.get(t))}i(EA,"resolveWorkspace");function AA(t){return q.text(`Workspace not found: ${t}`,{status:500,contentType:"text/plain; charset=utf-8"})}i(AA,"missingWorkspaceResponse");function IA(t){return Hm.target(t)}i(IA,"resolveTarget");function wA(t,e,r,n,a){return s.gen(function*(){if(!(yield*ye.Service.use(y=>y.isSyncing(r.id))))return q.text(`broken sync connection for workspace: ${r.id}`,{status:503,contentType:"text/plain; charset=utf-8"});let p=xf(n.url,a);if(e.headers.upgrade?.toLowerCase()==="websocket")return yield*Mo.websocket(e,p);let l=yield*Mo.http(t,p,n.headers,e),m=If(new Headers(l.headers));if(m){let y=yield*wf(r.id,m,e.source instanceof Request?e.source.signal:void 0).pipe(s.as(void 0),s.catch(g=>s.succeed(q.text(g.message,{status:503}))));if(y)return y}return l})}i(wA,"proxyRemote");function DA(t,e,r){return s.gen(function*(){let n=yield*IA(r);return n.type==="remote"?No.Remote({request:t,workspace:r,target:n,url:e}):No.Local({directory:n.directory,workspaceID:r.id})})}i(DA,"planWorkspaceRequest");function RA(t,e){return s.gen(function*(){let r=jf(t),n=yA(),a=r.pathname.startsWith("/api/")?hA(r,e?.workspaceID):gA(r,e?.workspaceID);if(a===Ff)return No.InvalidWorkspace();let c=yield*EA(a,n);return a&&c===void 0&&!n?No.MissingWorkspace({workspaceID:a}):c!==void 0&&!n&&!vA(t,r)?yield*DA(t,r,c):No.Local({directory:e?.directory||SA(t,r),workspaceID:n??a})})}i(RA,"planRequest");function CA(t,e,r){return No.$match(r,{InvalidWorkspace:i(()=>s.succeed(q.jsonUnsafe(new Yn({message:"Invalid workspace query parameter",kind:"Query",field:"workspace"}),{status:400})),"InvalidWorkspace"),MissingWorkspace:i(({workspaceID:n})=>s.succeed(AA(n)),"MissingWorkspace"),Remote:i(({request:n,workspace:a,target:c,url:p})=>wA(t,n,a,c,p),"Remote"),Local:i(({directory:n,workspaceID:a})=>e.pipe(s.provideService(_o,_o.of({directory:n,workspaceID:a}))),"Local")})}i(CA,"routeWorkspace");function xA(t,e){return s.gen(function*(){let r=yield*le.HttpServerRequest,n=Cf(jf(r)),a=n?yield*X.Service.use(p=>p.get(n)).pipe(s.catchIf(p=>lm.isInstance(p),()=>s.succeed(void 0)),s.catchDefect(()=>s.succeed(void 0))):void 0,c=yield*RA(r,a);return yield*CA(t,e,c)})}i(xA,"routeHttpApiWorkspace");var Gf=P.effect(W,s.gen(function*(){let t=yield*xc,e=yield*ye.Service,r=yield*Bi.HttpClient;return W.of(n=>xA(r,n).pipe(s.provideService(xc,t),s.provideService(ye.Service,e)))}));var $=class extends ge.Service()("@opencode/ExperimentalHttpApiInstanceContext"){static{i(this,"InstanceContextMiddleware")}};function kA(t){try{return decodeURIComponent(t)}catch{return t}}i(kA,"decode");function HA(t,e){return s.gen(function*(){let r=yield*_o,n=yield*e.load({directory:kA(r.directory)});return yield*t.pipe(s.provideService(aa,n),s.provideService(ca,r.workspaceID))})}i(HA,"provideInstanceContext");var Ga=P.effect($,s.gen(function*(){let t=yield*It.Service;return $.of(e=>HA(e,t))}));function S(t,e){return t.annotate({description:e})}i(S,"described");var Op="/config",Wf=U.make("config").add(H.make("config").add(u.get("get",Op,{query:I,success:S(Wr.Info,"Get config info")}).annotateMerge(d.annotations({identifier:"config.get",summary:"Get configuration",description:"Retrieve the current OpenCode configuration settings and preferences."})),u.patch("update",Op,{query:I,payload:Wr.Info,success:S(Wr.Info,"Successfully updated config"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"config.update",summary:"Update configuration",description:"Update OpenCode configuration settings and preferences."})),u.get("providers",`${Op}/providers`,{query:I,success:S(Oe.ConfigProvidersResult,"List of providers")}).annotateMerge(d.annotations({identifier:"config.providers",summary:"List config providers",description:"Get a list of all configured AI providers and their default models."}))).annotateMerge(d.annotations({title:"config",description:"Experimental HttpApi config routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var PA=o.Struct({paused:o.Boolean,waiting:o.Array(o.String)}),TA=o.Struct({paused:o.Boolean}),bA=o.Struct({paused:o.Boolean,stopped:o.optional(o.Array(o.String)),waiting:o.optional(o.Array(o.String))}),qA=o.Struct({ok:o.Boolean,deferred:o.optional(o.Boolean)}),OA=o.Struct({kind:o.String,label:o.String,usedPercent:o.Number,resetsAt:o.NullOr(o.Number)}),MA=o.Struct({fetchedAt:o.Number,providers:o.Array(o.Struct({providerID:o.String,plan:o.NullOr(o.String),error:o.optional(o.String),readAt:o.optional(o.Number),windows:o.Array(OA)}))}),LA=o.Struct({exa:o.Boolean,tavily:o.Boolean}),$f=U.make("alchemy").add(H.make("alchemy").add(u.get("pauseState","/config/pause",{query:I,success:S(PA,"Pause state")}).annotateMerge(d.annotations({identifier:"config.pauseState",summary:"Pause state",description:"Whether this project's turns are paused, and the sessions whose turns wait for Resume."})),u.post("pause","/config/pause",{query:I,payload:TA,success:S(bA,"The new state; stopped on pause, waiting on resume")}).annotateMerge(d.annotations({identifier:"config.pause",summary:"Pause or resume the project",description:"Paused, no turn runs: running turns stop and their sessions wait, and anything sent meanwhile lands and waits. Resume returns the sessions that wait, for the caller to wake."})),u.post("reload","/config/reload",{query:I,success:S(qA,"Config cache invalidated")}).annotateMerge(d.annotations({identifier:"config.reload",summary:"Reload configuration",description:"Drop cached config and agent state so the next request reads them again. While a session is busy the reload waits for all sessions to be idle (two minutes at most)."})),u.get("usage","/config/usage",{query:o.Struct({...xe,force:o.optional(o.String)}),success:S(MA,"Per-provider usage windows")}).annotateMerge(d.annotations({identifier:"config.usage",summary:"Plan usage",description:"Percent used and reset times of the usage windows on the OAuth providers this instance is signed into."})),u.get("mcpTools","/mcp/tools",{query:I,success:S(o.Record(o.String,o.Array(qe.ToolManifestEntry)),"Tools per connected server")}).annotateMerge(d.annotations({identifier:"mcp.tools",summary:"List MCP tools",description:"The tool catalogue each connected MCP server advertises, with read-only annotations intact. This is the catalogue, not the callable tool set: use it to show or govern what a server offers."})),u.get("searchKeys","/websearch/keys",{query:I,success:S(LA,"Whether each search service has a key")}).annotateMerge(d.annotations({identifier:"websearch.keys",summary:"Web search keys",description:"Which web search services have a key of the user's own set. Yes or no, never a key."}))).annotateMerge(d.annotations({title:"alchemy",description:"AlchemyLab fork routes."})).middleware($).middleware(W).middleware(j));var Vf=o.Struct({providerID:kt.ID}),UA=o.Struct({directory:o.optional(o.String),workspace:o.optional(o.String)}),NA=o.Struct({service:o.String.annotate({description:"Service name for the log entry"}),level:o.Union([o.Literal("debug"),o.Literal("info"),o.Literal("error"),o.Literal("warn")]).annotate({description:"Log level"}),message:o.String.annotate({description:"Log message"}),extra:o.optional(o.Record(o.String,o.Unknown)).annotate({description:"Additional metadata for the log entry"})}),Mp={auth:"/auth/:providerID",log:"/log"},zf=U.make("control").add(H.make("control").add(u.put("authSet",Mp.auth,{params:Vf,payload:Gt.Info,success:S(o.Boolean,"Successfully set authentication credentials"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"auth.set",summary:"Set auth credentials",description:"Set authentication credentials"})),u.delete("authRemove",Mp.auth,{params:Vf,success:S(o.Boolean,"Successfully removed authentication credentials"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"auth.remove",summary:"Remove auth credentials",description:"Remove authentication credentials"})),u.post("log",Mp.log,{query:UA,payload:NA,success:S(o.Boolean,"Log entry written successfully"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"app.log",summary:"Write log",description:"Write a log entry to the server logs with specified level and metadata."}))).annotateMerge(d.annotations({title:"control",description:"Control plane routes."})));var _A="/experimental/control-plane",BA=o.Struct({...Mt.Input.fields}),ni=class extends o.ErrorClass("MoveSessionError")({name:o.Literal("MoveSessionError"),data:o.Struct({message:o.String})},{httpApiStatus:400}){static{i(this,"ApiMoveSessionError")}},Qf=U.make("controlPlane").add(H.make("controlPlane").add(u.post("moveSession",`${_A}/move-session`,{payload:BA,success:S(k.NoContent,"Session moved"),error:ni}).annotateMerge(d.annotations({identifier:"experimental.controlPlane.moveSession",summary:"Move session",description:"Move a session to another project directory, optionally transferring local changes."}))).annotateMerge(d.annotations({title:"controlPlane",description:"Control-plane orchestration routes."})));var FA={event:"/event"},Bo=U.make("event").add(H.make("event").add(u.get("subscribe",FA.event,{query:I,success:o.String.pipe(k.asText({contentType:"text/event-stream"}))}).annotateMerge(d.annotations({identifier:"event.subscribe",summary:"Subscribe to events",description:"Get events"}))).middleware($).middleware(W).middleware(j).annotateMerge(d.annotations({title:"event",description:"Instance event stream route."})));var oi=o.Literals(["true","false"]).pipe(o.decodeTo(o.Boolean,{decode:gc.transform(t=>t==="true"),encode:gc.transform(t=>t?"true":"false")})),si={anyOf:[{type:"boolean"},{type:"string",enum:["true","false"]}]};var jA=o.Struct({consoleManagedProviders:o.mutable(o.Array(o.String)),activeOrgName:o.optionalKey(o.String),switchableOrgCount:Ie}).annotate({identifier:"ConsoleState"}),GA=o.Struct({backgroundSubagents:o.Boolean}).annotate({identifier:"ExperimentalCapabilities"}),WA=o.Struct({accountID:o.String,accountEmail:o.String,accountUrl:o.String,orgID:o.String,orgName:o.String,active:o.Boolean}),$A=o.Struct({orgs:o.Array(WA)}),VA=o.Struct({accountID:cm,orgID:pm}),zA=o.Array(o.String).annotate({identifier:"ToolIDs"}),QA=o.Struct({id:o.String,description:o.String,parameters:o.Unknown}).annotate({identifier:"ToolListItem"}),YA=o.Array(QA).annotate({identifier:"ToolList"}),KA=o.Struct({...xe,provider:kt.ID,model:us.ID}),XA=o.Array(o.String),JA=o.Union([o.Literal("WorktreeNotGitError"),o.Literal("WorktreeNameGenerationFailedError"),o.Literal("WorktreeCreateFailedError"),o.Literal("WorktreeStartCommandFailedError"),o.Literal("WorktreeRemoveFailedError"),o.Literal("WorktreeResetFailedError"),o.Literal("WorktreeListFailedError")]),pn=class extends o.ErrorClass("WorktreeError")({name:JA,data:o.Struct({message:o.String})},{httpApiStatus:400}){static{i(this,"WorktreeApiError")}},ZA=o.Struct({...xe,roots:o.optional(oi),start:o.optional(o.NumberFromString),cursor:o.optional(o.NumberFromString),search:o.optional(o.String),limit:o.optional(o.NumberFromString),archived:o.optional(oi)}),ft={capabilities:"/experimental/capabilities",console:"/experimental/console",consoleOrgs:"/experimental/console/orgs",consoleSwitch:"/experimental/console/switch",tool:"/experimental/tool",toolIDs:"/experimental/tool/ids",worktree:"/experimental/worktree",worktreeReset:"/experimental/worktree/reset",session:"/experimental/session",sessionBackground:"/experimental/session/:sessionID/background",resource:"/experimental/resource"},Yf=U.make("experimental").add(H.make("experimental").add(u.get("capabilities",ft.capabilities,{query:I,success:S(GA,"Experimental capabilities")}).annotateMerge(d.annotations({identifier:"experimental.capabilities.get",summary:"Get experimental capabilities",description:"Get experimental features enabled on the OpenCode server."})),u.get("console",ft.console,{query:I,success:S(jA,"Active Console provider metadata"),error:D.InternalServerError}).annotateMerge(d.annotations({identifier:"experimental.console.get",summary:"Get active Console provider metadata",description:"Get the active Console org name and the set of provider IDs managed by that Console org."})),u.get("consoleOrgs",ft.consoleOrgs,{query:I,success:S($A,"Switchable Console orgs"),error:D.InternalServerError}).annotateMerge(d.annotations({identifier:"experimental.console.listOrgs",summary:"List switchable Console orgs",description:"Get the available Console orgs across logged-in accounts, including the current active org."})),u.post("consoleSwitch",ft.consoleSwitch,{query:I,payload:VA,success:S(o.Boolean,"Switch success"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"experimental.console.switchOrg",summary:"Switch active Console org",description:"Persist a new active Console account/org selection for the current local OpenCode state."})),u.get("tool",ft.tool,{query:KA,success:S(YA,"Tools"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"tool.list",summary:"List tools",description:"Get a list of available tools with their JSON schema parameters for a specific provider and model combination."})),u.get("toolIDs",ft.toolIDs,{query:I,success:S(zA,"Tool IDs"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"tool.ids",summary:"List tool IDs",description:"Get a list of all available tool IDs, including both built-in tools and dynamically registered tools."})),u.get("worktree",ft.worktree,{query:I,success:S(XA,"List of worktree directories"),error:pn}).annotateMerge(d.annotations({identifier:"worktree.list",summary:"List worktrees",description:"List all sandbox worktrees for the current project."})),u.post("worktreeCreate",ft.worktree,{disableCodecs:!0,query:I,payload:[k.NoContent,fr.CreateInput],success:S(fr.Info,"Worktree created"),error:pn}).annotateMerge(d.annotations({identifier:"worktree.create",summary:"Create worktree",description:"Create a new git worktree for the current project and run any configured startup scripts."})),u.delete("worktreeRemove",ft.worktree,{query:I,payload:fr.RemoveInput,success:S(o.Boolean,"Worktree removed"),error:pn}).annotateMerge(d.annotations({identifier:"worktree.remove",summary:"Remove worktree",description:"Remove a git worktree and delete its branch."})),u.post("worktreeReset",ft.worktreeReset,{query:I,payload:fr.ResetInput,success:S(o.Boolean,"Worktree reset"),error:pn}).annotateMerge(d.annotations({identifier:"worktree.reset",summary:"Reset worktree",description:"Reset a worktree branch to the primary default branch."})),u.get("session",ft.session,{query:ZA,success:S(o.Array(X.GlobalInfo),"List of sessions")}).annotateMerge(d.annotations({identifier:"experimental.session.list",summary:"List sessions",description:"Get a list of all OpenCode sessions across projects, sorted by most recently updated. Archived sessions are excluded by default."})),u.post("sessionBackground",ft.sessionBackground,{params:{sessionID:Y},query:I,success:S(o.Boolean,"Backgrounded subagents"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"experimental.session.background",summary:"Background subagents",description:"Detach any synchronous subagents currently blocking the session and continue them in the background."})),u.get("resource",ft.resource,{query:I,success:S(o.Record(o.String,qe.Resource),"MCP resources")}).annotateMerge(d.annotations({identifier:"experimental.resource.list",summary:"Get MCP resources",description:"Get all available MCP resources from connected servers. Optionally filter by name."}))).annotateMerge(d.annotations({title:"experimental",description:"Experimental HttpApi read-only routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var Kf=o.Struct({...xe,path:o.String}),eI=o.Struct({...xe,pattern:o.String}),tI=o.Struct({...xe,query:o.String,dirs:o.optional(o.Literals(["true","false"])),type:o.optional(o.Literals(["file","directory"])),limit:o.optional(o.NumberFromString.check(o.isInt(),o.isGreaterThanOrEqualTo(1),o.isLessThanOrEqualTo(200)))}),rI=o.Struct({...xe,query:o.String}),nI=o.Struct({path:o.Struct({text:o.String}),lines:o.Struct({text:o.String}),line_number:Ie,absolute_offset:Ie,submatches:o.Array(o.Struct({match:o.Struct({text:o.String}),start:Ie,end:Ie}))}),oI=o.Struct({name:o.String,path:o.String,absolute:o.String,type:o.Literals(["file","directory"]),ignored:o.Boolean}).annotate({identifier:"FileNode"}),sI=o.Struct({type:o.Literals(["text","binary"]),content:o.String,diff:o.optional(o.String),patch:o.optional(o.Struct({oldFileName:o.String,newFileName:o.String,oldHeader:o.optional(o.String),newHeader:o.optional(o.String),hunks:o.Array(o.Struct({oldStart:Ie,oldLines:Ie,newStart:Ie,newLines:Ie,lines:o.Array(o.String)})),index:o.optional(o.String)})),encoding:o.optional(o.Literal("base64")),mimeType:o.optional(o.String)}).annotate({identifier:"FileContent"}),iI=o.Struct({path:o.String,added:Ie,removed:Ie,status:o.Literals(["added","deleted","modified"])}).annotate({identifier:"File"}),Fo={findText:"/find",findFile:"/find/file",findSymbol:"/find/symbol",list:"/file",content:"/file/content",status:"/file/status"},Xf=U.make("file").add(H.make("file").add(u.get("findText",Fo.findText,{query:eI,success:S(o.Array(nI),"Matches")}).annotateMerge(d.annotations({identifier:"find.text",summary:"Find text",description:"Search for text patterns across files in the project using ripgrep."})),u.get("findFile",Fo.findFile,{query:tI,success:S(o.Array(o.String),"File paths")}).annotateMerge(d.annotations({identifier:"find.files",summary:"Find files",description:"Search for files or directories by name or pattern in the project directory."})),u.get("findSymbol",Fo.findSymbol,{query:rI,success:S(o.Array(Jr.Symbol),"Symbols")}).annotateMerge(d.annotations({identifier:"find.symbols",summary:"Find symbols",description:"Search for workspace symbols like functions, classes, and variables using LSP."})),u.get("list",Fo.list,{query:Kf,success:S(o.Array(oI),"Files and directories")}).annotateMerge(d.annotations({identifier:"file.list",summary:"List files",description:"List files and directories in a specified path."})),u.get("content",Fo.content,{query:Kf,success:S(sI,"File content")}).annotateMerge(d.annotations({identifier:"file.read",summary:"Read file",description:"Read the content of a specified file."})),u.get("status",Fo.status,{query:I,success:S(o.Array(iI),"File status")}).annotateMerge(d.annotations({identifier:"file.status",summary:"Get file status",description:"Get the git status of all files in the project."}))).annotateMerge(d.annotations({title:"file",description:"Experimental HttpApi file routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var aI=o.Struct({home:o.String,state:o.String,config:o.String,worktree:o.String,directory:o.String}).annotate({identifier:"Path"}),cI=o.Struct({...xe,mode:at.Mode,context:o.optional(o.NumberFromString.check(o.isInt(),o.isGreaterThanOrEqualTo(0)))}),Hr=class extends o.ErrorClass("VcsApplyError")({name:o.Literal("VcsApplyError"),data:o.Struct({message:o.String,reason:o.Literals(["non-git","not-clean"])})},{httpApiStatus:400}){static{i(this,"ApiVcsApplyError")}},Rt={dispose:"/instance/dispose",path:"/path",vcs:"/vcs",vcsStatus:"/vcs/status",vcsDiff:"/vcs/diff",vcsDiffRaw:"/vcs/diff/raw",vcsApply:"/vcs/apply",command:"/command",agent:"/agent",skill:"/skill",lsp:"/lsp",formatter:"/formatter"},Jf=U.make("instance").add(H.make("instance").add(u.post("dispose",Rt.dispose,{query:I,success:S(o.Boolean,"Instance disposed")}).annotateMerge(d.annotations({identifier:"instance.dispose",summary:"Dispose instance",description:"Clean up and dispose the current OpenCode instance, releasing all resources."})),u.get("path",Rt.path,{query:I,success:aI}).annotateMerge(d.annotations({identifier:"path.get",summary:"Get paths",description:"Retrieve the current working directory and related path information for the OpenCode instance."})),u.get("vcs",Rt.vcs,{query:I,success:S(at.Info,"VCS info")}).annotateMerge(d.annotations({identifier:"vcs.get",summary:"Get VCS info",description:"Retrieve version control system (VCS) information for the current project, such as git branch."})),u.get("vcsStatus",Rt.vcsStatus,{query:I,success:S(o.Array(at.FileStatus),"VCS status")}).annotateMerge(d.annotations({identifier:"vcs.status",summary:"Get VCS status",description:"Retrieve changed files in the current working tree without patches."})),u.get("vcsDiff",Rt.vcsDiff,{query:cI,success:S(o.Array(at.FileDiff),"VCS diff")}).annotateMerge(d.annotations({identifier:"vcs.diff",summary:"Get VCS diff",description:"Retrieve the current git diff for the working tree or against the default branch."})),u.get("vcsDiffRaw",Rt.vcsDiffRaw,{query:I,success:S(o.String.pipe(k.asText({contentType:"text/x-diff; charset=utf-8"})),"Raw VCS diff")}).annotateMerge(d.annotations({identifier:"vcs.diff.raw",summary:"Get raw VCS diff",description:"Retrieve a raw patch for current uncommitted changes."})),u.post("vcsApply",Rt.vcsApply,{query:I,payload:at.ApplyInput,success:S(at.ApplyResult,"VCS patch applied"),error:Hr}).annotateMerge(d.annotations({identifier:"vcs.apply",summary:"Apply VCS patch",description:"Apply a raw patch to the current working tree."})),u.get("command",Rt.command,{query:I,success:S(o.Array(Zr.Info),"List of commands")}).annotateMerge(d.annotations({identifier:"command.list",summary:"List commands",description:"Get a list of all available commands in the OpenCode system."})),u.get("agent",Rt.agent,{query:I,success:S(o.Array(zt.Info),"List of agents")}).annotateMerge(d.annotations({identifier:"app.agents",summary:"List agents",description:"Get a list of all available AI agents in the OpenCode system."})),u.get("skill",Rt.skill,{query:I,success:S(o.Array(So.Info),"List of skills")}).annotateMerge(d.annotations({identifier:"app.skills",summary:"List skills",description:"Get a list of all available skills in the OpenCode system."})),u.get("lsp",Rt.lsp,{query:I,success:S(o.Array(Jr.Status),"LSP server status")}).annotateMerge(d.annotations({identifier:"lsp.status",summary:"Get LSP status",description:"Get LSP server status"})),u.get("formatter",Rt.formatter,{query:I,success:S(o.Array(Io.Status),"Formatter status")}).annotateMerge(d.annotations({identifier:"formatter.status",summary:"Get formatter status",description:"Get formatter status"}))).annotateMerge(d.annotations({title:"instance",description:"Experimental HttpApi instance read routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var pI=o.Struct({name:o.String,config:ju.Info}),Lp=o.Record(o.String,qe.Status),dI=o.Struct({authorizationUrl:o.String,oauthState:o.String}),uI=o.Struct({code:o.String}),mI=o.Struct({success:o.Literal(!0)}),Kn=class extends o.ErrorClass("McpUnsupportedOAuthError")({error:o.String},{httpApiStatus:400}){static{i(this,"UnsupportedOAuthError")}},dn={status:"/mcp",auth:"/mcp/:name/auth",authCallback:"/mcp/:name/auth/callback",authAuthenticate:"/mcp/:name/auth/authenticate",connect:"/mcp/:name/connect",disconnect:"/mcp/:name/disconnect"},Zf=U.make("mcp").add(H.make("mcp").add(u.get("status",dn.status,{query:I,success:S(o.Record(o.String,qe.Status),"MCP server status")}).annotateMerge(d.annotations({identifier:"mcp.status",summary:"Get MCP status",description:"Get the status of all Model Context Protocol (MCP) servers."})),u.post("add",dn.status,{query:I,payload:pI,success:S(Lp,"MCP server added successfully"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"mcp.add",summary:"Add MCP server",description:"Dynamically add a new Model Context Protocol (MCP) server to the system."})),u.post("authStart",dn.auth,{params:{name:o.String},query:I,success:S(dI,"OAuth flow started"),error:[Kn,_e]}).annotateMerge(d.annotations({identifier:"mcp.auth.start",summary:"Start MCP OAuth",description:"Start OAuth authentication flow for a Model Context Protocol (MCP) server."})),u.post("authCallback",dn.authCallback,{params:{name:o.String},query:I,payload:uI,success:S(qe.Status,"OAuth authentication completed"),error:[D.BadRequest,_e]}).annotateMerge(d.annotations({identifier:"mcp.auth.callback",summary:"Complete MCP OAuth",description:"Complete OAuth authentication for a Model Context Protocol (MCP) server using the authorization code."})),u.post("authAuthenticate",dn.authAuthenticate,{params:{name:o.String},query:I,success:S(qe.Status,"OAuth authentication completed"),error:[Kn,_e]}).annotateMerge(d.annotations({identifier:"mcp.auth.authenticate",summary:"Authenticate MCP OAuth",description:"Start OAuth flow and wait for callback (opens browser)."})),u.delete("authRemove",dn.auth,{params:{name:o.String},query:I,success:S(mI,"OAuth credentials removed"),error:_e}).annotateMerge(d.annotations({identifier:"mcp.auth.remove",summary:"Remove MCP OAuth",description:"Remove OAuth credentials for an MCP server."})),u.post("connect",dn.connect,{params:{name:o.String},query:I,success:S(o.Boolean,"MCP server connected successfully"),error:_e}).annotateMerge(d.annotations({identifier:"mcp.connect",description:"Connect an MCP server."})),u.post("disconnect",dn.disconnect,{params:{name:o.String},query:I,success:S(o.Boolean,"MCP server disconnected successfully"),error:_e}).annotateMerge(d.annotations({identifier:"mcp.disconnect",description:"Disconnect an MCP server."}))).annotateMerge(d.annotations({title:"mcp",description:"Experimental HttpApi MCP routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var ey="/permission",lI=o.Struct({reply:Qr.Reply,message:o.optional(o.String)}),ty=U.make("permission").add(H.make("permission").add(u.get("list",ey,{query:I,success:S(o.Array(Qr.Request),"List of pending permissions")}).annotateMerge(d.annotations({identifier:"permission.list",summary:"List pending permissions",description:"Get all pending permission requests across all sessions."})),u.post("reply",`${ey}/:requestID/reply`,{params:{requestID:Qr.ID},query:I,payload:lI,success:S(o.Boolean,"Permission processed successfully"),error:[D.BadRequest,sr]}).annotateMerge(d.annotations({identifier:"permission.reply",summary:"Respond to permission request",description:"Approve or deny a permission request from the AI assistant."}))).annotateMerge(d.annotations({title:"permission",description:"Experimental HttpApi permission routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var ii="/project",fI=o.Struct({name:o.optional(o.String),icon:o.optional(it.Info.fields.icon),commands:o.optional(it.Info.fields.commands)}),ry=U.make("project").add(H.make("project").add(u.get("list",ii,{query:I,success:S(o.Array(it.Info),"List of projects")}).annotateMerge(d.annotations({identifier:"project.list",summary:"List all projects",description:"Get a list of projects that have been opened with OpenCode."})),u.get("current",`${ii}/current`,{query:I,success:S(it.Info,"Current project information")}).annotateMerge(d.annotations({identifier:"project.current",summary:"Get current project",description:"Retrieve the currently active project that OpenCode is working with."})),u.post("initGit",`${ii}/git/init`,{query:I,success:S(it.Info,"Project information after git initialization")}).annotateMerge(d.annotations({identifier:"project.initGit",summary:"Initialize git repository",description:"Create a git repository for the current project and return the refreshed project info."})),u.patch("update",`${ii}/:projectID`,{params:{projectID:Fe.ID},query:I,payload:fI,success:S(it.Info,"Updated project information"),error:[D.BadRequest,Uo]}).annotateMerge(d.annotations({identifier:"project.update",summary:"Update project",description:"Update project properties such as name, icon, and commands."})),u.get("directories",`${ii}/:projectID/directories`,{params:{projectID:Fe.ID},query:I,success:S(Fe.Directories,"Project directories")}).annotateMerge(d.annotations({identifier:"project.directories",summary:"List project directories",description:"List known local absolute directories for a project."}))).annotateMerge(d.annotations({title:"project",description:"Experimental HttpApi project routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var yI=o.Struct({context:o.optional(o.String)}),ny=U.make("projectCopyName").add(H.make("projectCopyName").add(u.post("generateName","/experimental/project/:projectID/copy/generate-name",{params:{projectID:Fe.ID},query:I,payload:yI,success:o.Struct({name:o.String})}).annotateMerge(d.annotations({identifier:"experimental.projectCopy.generateName",summary:"Generate project copy name",description:"Generate a short name for a project copy from task context."}))).annotateMerge(d.annotations({title:"projectCopy",description:"Project copy naming routes."})).middleware($).middleware(W).middleware(j));var Wa="/provider",gI=o.Union([o.Literal("BadRequest"),o.Literal("ProviderAuthOauthMissing"),o.Literal("ProviderAuthOauthCodeMissing"),o.Literal("ProviderAuthOauthCallbackFailed"),o.Literal("ProviderAuthValidationFailed")]),Ut=class extends o.ErrorClass("ProviderAuthError")({name:gI,data:o.Struct({providerID:o.optional(kt.ID),field:o.optional(o.String),message:o.optional(o.String),kind:o.optional(o.String)})},{httpApiStatus:400}){static{i(this,"ProviderAuthApiError")}},oy=U.make("provider").add(H.make("provider").add(u.get("list",Wa,{query:I,success:S(Oe.ListResult,"List of providers")}).annotateMerge(d.annotations({identifier:"provider.list",summary:"List providers",description:"Get a list of all available AI providers, including both available and connected ones."})),u.get("auth",`${Wa}/auth`,{query:I,success:S(Xe.Methods,"Provider auth methods")}).annotateMerge(d.annotations({identifier:"provider.auth",summary:"Get provider auth methods",description:"Retrieve available authentication methods for all AI providers."})),u.post("authorize",`${Wa}/:providerID/oauth/authorize`,{params:{providerID:kt.ID},query:I,payload:Xe.AuthorizeInput,success:S(o.UndefinedOr(Xe.Authorization),"Authorization URL and method"),error:Ut}).annotateMerge(d.annotations({identifier:"provider.oauth.authorize",summary:"Start OAuth authorization",description:"Start the OAuth authorization flow for a provider."})),u.post("callback",`${Wa}/:providerID/oauth/callback`,{params:{providerID:kt.ID},query:I,payload:Xe.CallbackInput,success:S(o.Boolean,"OAuth callback processed successfully"),error:Ut}).annotateMerge(d.annotations({identifier:"provider.oauth.callback",summary:"Handle OAuth callback",description:"Handle the OAuth callback from a provider after user authorization."}))).annotateMerge(d.annotations({title:"provider",description:"Experimental HttpApi provider routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var un="/pty",hI=o.Struct({ptyID:yo}),sy=o.Struct({...xe,cursor:o.optional(o.String)}),SI=o.Struct({path:o.String,name:o.String,acceptable:o.Boolean}),mn={shells:`${un}/shells`,list:un,create:un,get:`${un}/:ptyID`,update:`${un}/:ptyID`,remove:`${un}/:ptyID`,connectToken:`${un}/:ptyID/connect-token`,connect:`${un}/:ptyID/connect`},iy=U.make("pty").add(H.make("pty").add(u.get("shells",mn.shells,{query:I,success:S(o.Array(SI),"List of shells")}).annotateMerge(d.annotations({identifier:"pty.shells",summary:"List available shells",description:"Get a list of available shells on the system."})),u.get("list",mn.list,{query:I,success:S(o.Array(he.Info),"List of sessions")}).annotateMerge(d.annotations({identifier:"pty.list",summary:"List PTY sessions",description:"Get a list of all active pseudo-terminal (PTY) sessions managed by OpenCode."})),u.post("create",mn.create,{query:I,payload:he.CreateInput,success:S(he.Info,"Created session"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"pty.create",summary:"Create PTY session",description:"Create a new pseudo-terminal (PTY) session for running shell commands and processes."})),u.get("get",mn.get,{params:{ptyID:yo},query:I,success:S(he.Info,"Session info"),error:Dt}).annotateMerge(d.annotations({identifier:"pty.get",summary:"Get PTY session",description:"Retrieve detailed information about a specific pseudo-terminal (PTY) session."})),u.put("update",mn.update,{params:{ptyID:yo},query:I,payload:he.UpdateInput,success:S(he.Info,"Updated session"),error:[Dt,D.BadRequest]}).annotateMerge(d.annotations({identifier:"pty.update",summary:"Update PTY session",description:"Update properties of an existing pseudo-terminal (PTY) session."})),u.delete("remove",mn.remove,{params:{ptyID:yo},query:I,success:S(o.Boolean,"Session removed"),error:Dt}).annotateMerge(d.annotations({identifier:"pty.remove",summary:"Remove PTY session",description:"Remove and terminate a specific pseudo-terminal (PTY) session."})),u.post("connectToken",mn.connectToken,{params:{ptyID:yo},query:I,success:S(wt.ConnectToken,"WebSocket connect token"),error:[Lo,Dt]}).annotateMerge(d.annotations({identifier:"pty.connectToken",summary:"Create PTY WebSocket token",description:"Create a short-lived ticket for opening a PTY WebSocket connection."}))).annotateMerge(d.annotations({title:"pty",description:"Experimental HttpApi PTY routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."})),jo=U.make("pty-connect").add(H.make("pty-connect").add(u.get("connect",mn.connect,{params:hI,success:S(o.Boolean,"Connected session"),error:[D.Forbidden,D.NotFound]}).annotateMerge(d.annotations({identifier:"pty.connect",summary:"Connect to PTY session",description:"Establish a WebSocket connection to interact with a pseudo-terminal (PTY) session in real-time.",transform:i(t=>({...t,parameters:[...t.parameters??[],...["directory","workspace","cursor",ti].map(e=>({in:"query",name:e,schema:{type:"string"}}))]}),"transform")}))).annotateMerge(d.annotations({title:"pty",description:"PTY websocket route."})).middleware($).middleware(W).middleware(zn));var Up="/question",vI=o.Struct({answers:o.Array($t.Answer).annotate({description:"User answers in order of questions (each answer is an array of selected labels)"})}),ay=U.make("question").add(H.make("question").add(u.get("list",Up,{query:I,success:S(o.Array($t.Request),"List of pending questions")}).annotateMerge(d.annotations({identifier:"question.list",summary:"List pending questions",description:"Get all pending question requests across all sessions."})),u.post("reply",`${Up}/:requestID/reply`,{params:{requestID:Nc},query:I,payload:vI,success:S(o.Boolean,"Question answered successfully"),error:[D.BadRequest,cn]}).annotateMerge(d.annotations({identifier:"question.reply",summary:"Reply to question request",description:"Provide answers to a question request from the AI assistant."})),u.post("reject",`${Up}/:requestID/reject`,{params:{requestID:Nc},query:I,success:S(o.Boolean,"Question rejected successfully"),error:[D.BadRequest,cn]}).annotateMerge(d.annotations({identifier:"question.reject",summary:"Reject question request",description:"Reject a question request from the AI assistant."}))).annotateMerge(d.annotations({title:"question",description:"Question routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode HttpApi",version:"0.0.1",description:"Effect HttpApi surface for instance routes."}));var de="/session",EI=o.Struct({...xe,scope:o.optional(o.Literals(["project"])),path:o.optional(o.String),roots:o.optional(oi),start:o.optional(o.NumberFromString),search:o.optional(o.String),limit:o.optional(o.NumberFromString)}),AI=o.Struct({...xe,...ze.omit(Eo.DiffInput.fields,["sessionID"])}),II=o.Struct({...xe,limit:o.optional(o.NumberFromString.check(o.isInt(),o.isGreaterThanOrEqualTo(0))),before:o.optional(o.String)}),wI=o.Record(o.String,Xr.Info),DI=o.Struct({title:o.optional(o.String),metadata:o.optional(X.Metadata),permission:o.optional(Qr.Ruleset),time:o.optional(o.Struct({archived:o.optional(X.ArchivedTimestamp)}))}),Np=o.Struct(ze.omit(X.ForkInput.fields,["sessionID"])),RI=o.Struct({modelID:us.ID,providerID:kt.ID,messageID:Kr}),CI=o.Struct({providerID:kt.ID,modelID:us.ID,auto:o.optional(o.Boolean)}),cy=o.Struct(ze.omit(Vt.PromptInput.fields,["sessionID"])),xI=o.Struct(ze.omit(Vt.CommandInput.fields,["sessionID"])),kI=o.Struct(ze.omit(Vt.ShellInput.fields,["sessionID"])),HI=o.Struct(ze.omit(Ao.RevertInput.fields,["sessionID"])),PI=o.Struct({response:Qr.Reply}),ae={list:de,status:`${de}/status`,get:`${de}/:sessionID`,children:`${de}/:sessionID/children`,todo:`${de}/:sessionID/todo`,diff:`${de}/:sessionID/diff`,messages:`${de}/:sessionID/message`,message:`${de}/:sessionID/message/:messageID`,create:de,remove:`${de}/:sessionID`,update:`${de}/:sessionID`,fork:`${de}/:sessionID/fork`,abort:`${de}/:sessionID/abort`,share:`${de}/:sessionID/share`,init:`${de}/:sessionID/init`,summarize:`${de}/:sessionID/summarize`,prompt:`${de}/:sessionID/message`,promptAsync:`${de}/:sessionID/prompt_async`,command:`${de}/:sessionID/command`,shell:`${de}/:sessionID/shell`,revert:`${de}/:sessionID/revert`,unrevert:`${de}/:sessionID/unrevert`,permissions:`${de}/:sessionID/permissions/:permissionID`,deleteMessage:`${de}/:sessionID/message/:messageID`,deletePart:`${de}/:sessionID/message/:messageID/part/:partID`,updatePart:`${de}/:sessionID/message/:messageID/part/:partID`},py=U.make("session").add(H.make("session").add(u.get("list",ae.list,{query:EI,success:S(o.Array(X.Info),"List of sessions")}).annotateMerge(d.annotations({identifier:"session.list",summary:"List sessions",description:"Get a list of all OpenCode sessions, sorted by most recently updated."})),u.get("status",ae.status,{query:I,success:S(wI,"Get session status"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"session.status",summary:"Get session status",description:"Retrieve the current status of all sessions, including active, idle, and completed states."})),u.get("get",ae.get,{params:{sessionID:Y},query:I,success:S(X.Info,"Get session"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.get",summary:"Get session",description:"Retrieve detailed information about a specific OpenCode session."})),u.get("children",ae.children,{params:{sessionID:Y},query:I,success:S(o.Array(X.Info),"List of children"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.children",summary:"Get session children",description:"Retrieve all child sessions that were forked from the specified parent session."})),u.get("todo",ae.todo,{params:{sessionID:Y},query:I,success:S(o.Array(vo.Info),"Todo list"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.todo",summary:"Get session todos",description:"Retrieve the todo list associated with a specific session, showing tasks and action items."})),u.get("diff",ae.diff,{params:{sessionID:Y},query:AI,success:S(o.Array(ua.FileDiff),"Successfully retrieved diff")}).annotateMerge(d.annotations({identifier:"session.diff",summary:"Get message diff",description:"Get the file changes (diff) that resulted from a specific user message in the session."})),u.get("messages",ae.messages,{params:{sessionID:Y},query:II,success:S(o.Array(zr.WithParts),"List of messages"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.messages",summary:"Get session messages",description:"Retrieve all messages in a session, including user prompts and AI responses."})),u.get("message",ae.message,{params:{sessionID:Y,messageID:Kr},query:I,success:S(zr.WithParts,"Message"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.message",summary:"Get message",description:"Retrieve a specific message from a session by its message ID."})),u.post("create",ae.create,{query:I,payload:[k.NoContent,X.CreateInput],success:S(X.Info,"Successfully created session"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"session.create",summary:"Create session",description:"Create a new OpenCode session for interacting with AI assistants and managing conversations."})),u.delete("remove",ae.remove,{params:{sessionID:Y},query:I,success:S(o.Boolean,"Successfully deleted session"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.delete",summary:"Delete session",description:"Delete a session and permanently remove all associated data, including messages and history."})),u.patch("update",ae.update,{params:{sessionID:Y},query:I,payload:DI,success:S(X.Info,"Successfully updated session"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.update",summary:"Update session",description:"Update properties of an existing session, such as title or other metadata."})),u.post("fork",ae.fork,{params:{sessionID:Y},query:I,payload:[k.NoContent,Np],success:S(X.Info,"200"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.fork",summary:"Fork session",description:"Create a new session by forking an existing session at a specific message point."})),u.post("abort",ae.abort,{params:{sessionID:Y},query:I,success:S(o.Boolean,"Aborted session"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"session.abort",summary:"Abort session",description:"Abort an active session and stop any ongoing AI processing or command execution."})),u.post("init",ae.init,{params:{sessionID:Y},query:I,payload:RI,success:S(o.Boolean,"200"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.init",summary:"Initialize session",description:"Analyze the current application and create an AGENTS.md file with project-specific agent configurations."})),u.post("share",ae.share,{params:{sessionID:Y},query:I,success:S(X.Info,"Successfully shared session"),error:[D.InternalServerError,te]}).annotateMerge(d.annotations({identifier:"session.share",summary:"Share session",description:"Create a shareable link for a session, allowing others to view the conversation."})),u.delete("unshare",ae.share,{params:{sessionID:Y},query:I,success:S(X.Info,"Successfully unshared session"),error:[D.InternalServerError,te]}).annotateMerge(d.annotations({identifier:"session.unshare",summary:"Unshare session",description:"Remove the shareable link for a session, making it private again."})),u.post("summarize",ae.summarize,{params:{sessionID:Y},query:I,payload:CI,success:S(o.Boolean,"Summarized session"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.summarize",summary:"Summarize session",description:"Generate a concise summary of the session using AI compaction to preserve key information."})),u.post("prompt",ae.prompt,{params:{sessionID:Y},query:I,payload:cy,success:S(zr.WithParts,"Created message"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.prompt",summary:"Send message",description:"Create and send a new message to a session, streaming the AI response."})),u.post("promptAsync",ae.promptAsync,{params:{sessionID:Y},query:I,payload:cy,success:S(k.NoContent,"Prompt accepted"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.prompt_async",summary:"Send async message",description:"Create and send a new message to a session asynchronously, starting the session if needed and returning immediately."})),u.post("command",ae.command,{params:{sessionID:Y},query:I,payload:xI,success:S(zr.WithParts,"Created message"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.command",summary:"Send command",description:"Send a new command to a session for execution by the AI assistant."})),u.post("shell",ae.shell,{params:{sessionID:Y},query:I,payload:kI,success:S(zr.WithParts,"Created message"),error:[D.BadRequest,te,kr]}).annotateMerge(d.annotations({identifier:"session.shell",summary:"Run shell command",description:"Execute a shell command within the session context and return the AI's response."})),u.post("revert",ae.revert,{params:{sessionID:Y},query:I,payload:HI,success:S(X.Info,"Updated session"),error:[D.BadRequest,te,kr]}).annotateMerge(d.annotations({identifier:"session.revert",summary:"Revert message",description:"Revert a specific message in a session, undoing its effects and restoring the previous state."})),u.post("unrevert",ae.unrevert,{params:{sessionID:Y},query:I,success:S(X.Info,"Updated session"),error:[D.BadRequest,te,kr]}).annotateMerge(d.annotations({identifier:"session.unrevert",summary:"Restore reverted messages",description:"Restore all previously reverted messages in a session."})),u.post("permissionRespond",ae.permissions,{params:{sessionID:Y,permissionID:Qr.ID},query:I,payload:PI,success:S(o.Boolean,"Permission processed successfully"),error:[D.BadRequest,te,sr]}).annotateMerge(d.annotations({identifier:"permission.respond",summary:"Respond to permission",description:"Approve or deny a permission request from the AI assistant.",deprecated:!0})),u.delete("deleteMessage",ae.deleteMessage,{params:{sessionID:Y,messageID:Kr},query:I,success:S(o.Boolean,"Successfully deleted message"),error:[D.BadRequest,te,kr]}).annotateMerge(d.annotations({identifier:"session.deleteMessage",summary:"Delete message",description:"Permanently delete a specific message and all of its parts from a session without reverting file changes."})),u.delete("deletePart",ae.deletePart,{params:{sessionID:Y,messageID:Kr,partID:Uc},query:I,success:S(o.Boolean,"Successfully deleted part"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"part.delete",description:"Delete a part from a message."})),u.patch("updatePart",ae.updatePart,{params:{sessionID:Y,messageID:Kr,partID:Uc},query:I,payload:zr.Part,success:S(zr.Part,"Successfully updated part"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"part.update",description:"Update a part in a message."}))).annotateMerge(d.annotations({title:"session",description:"Experimental HttpApi session routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var $a="/sync",TI=o.Struct({id:fe.ID,aggregateID:o.String,seq:Ie,type:o.String,data:o.Record(o.String,o.Unknown)}),bI=o.Struct({directory:o.String,events:o.NonEmptyArray(TI)}),qI=o.Struct({sessionID:o.String}),dy=o.Struct({sessionID:Y}),OI=o.Record(o.String,Ie),MI=o.Struct({id:fe.ID,aggregate_id:o.String,seq:Ie,type:o.String,data:o.Record(o.String,o.Unknown)}),Va={start:`${$a}/start`,replay:`${$a}/replay`,steal:`${$a}/steal`,history:`${$a}/history`},uy=U.make("sync").add(H.make("sync").add(u.post("start",Va.start,{query:I,success:S(o.Boolean,"Workspace sync started")}).annotateMerge(d.annotations({identifier:"sync.start",summary:"Start workspace sync",description:"Start sync loops for workspaces in the current project that have active sessions."})),u.post("replay",Va.replay,{query:I,payload:bI,success:S(qI,"Replayed sync events"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"sync.replay",summary:"Replay sync events",description:"Validate and replay a complete sync event history."})),u.post("steal",Va.steal,{query:I,payload:dy,success:S(dy,"Session stolen into workspace"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"sync.steal",summary:"Steal session into workspace",description:"Update a session to belong to the current workspace through the sync event system."})),u.post("history",Va.history,{query:I,payload:OI,success:S(o.Array(MI),"Sync events"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"sync.history.list",summary:"List sync events",description:"List sync events for all aggregates. Keys are aggregate IDs the client already knows about, values are the last known sequence ID. Events with seq > value are returned for those aggregates. Aggregates not listed in the input get their full history."}))).annotateMerge(d.annotations({title:"sync",description:"Experimental HttpApi sync routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var ai=class{static{i(this,"AsyncQueue")}queue=[];resolvers=[];push(e){let r=this.resolvers.shift();r?r(e):this.queue.push(e)}async next(){return this.queue.length>0?this.queue.shift():new Promise(e=>this.resolvers.push(e))}async*[Symbol.asyncIterator](){for(;;)yield await this.next()}};var my=o.Struct({path:o.String,body:o.Unknown}),LI=new ai,UI=new ai;function ly(){return LI.next()}i(ly,"nextTuiRequest");function fy(t){UI.push(t)}i(fy,"submitTuiResponse");var yt="/tui",NI=o.Struct({command:o.String}),_I=o.Struct({type:o.Literal(ie.PromptAppend.type),properties:ie.PromptAppend.data}).annotate({identifier:"EventTuiPromptAppend"}),BI=o.Struct({type:o.Literal(ie.CommandExecute.type),properties:ie.CommandExecute.data}).annotate({identifier:"EventTuiCommandExecute"}),FI=o.Struct({type:o.Literal(ie.ToastShow.type),properties:ie.ToastShow.data}).annotate({identifier:"EventTuiToastShow"}),jI=o.Struct({type:o.Literal(ie.SessionSelect.type),properties:ie.SessionSelect.data}).annotate({identifier:"EventTuiSessionSelect"}),GI=o.Union([_I,BI,FI,jI]),gt={appendPrompt:`${yt}/append-prompt`,openHelp:`${yt}/open-help`,openSessions:`${yt}/open-sessions`,openThemes:`${yt}/open-themes`,openModels:`${yt}/open-models`,submitPrompt:`${yt}/submit-prompt`,clearPrompt:`${yt}/clear-prompt`,executeCommand:`${yt}/execute-command`,showToast:`${yt}/show-toast`,publish:`${yt}/publish`,selectSession:`${yt}/select-session`,controlNext:`${yt}/control/next`,controlResponse:`${yt}/control/response`},yy=U.make("tui").add(H.make("tui").add(u.post("appendPrompt",gt.appendPrompt,{query:I,payload:ie.PromptAppend.data,success:S(o.Boolean,"Prompt processed successfully"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"tui.appendPrompt",summary:"Append TUI prompt",description:"Append prompt to the TUI."})),u.post("openHelp",gt.openHelp,{query:I,success:S(o.Boolean,"Help dialog opened successfully")}).annotateMerge(d.annotations({identifier:"tui.openHelp",summary:"Open help dialog",description:"Open the help dialog in the TUI to display user assistance information."})),u.post("openSessions",gt.openSessions,{query:I,success:S(o.Boolean,"Session dialog opened successfully")}).annotateMerge(d.annotations({identifier:"tui.openSessions",summary:"Open sessions dialog",description:"Open the session dialog."})),u.post("openThemes",gt.openThemes,{query:I,success:S(o.Boolean,"Theme dialog opened successfully")}).annotateMerge(d.annotations({identifier:"tui.openThemes",summary:"Open themes dialog",description:"Open the theme dialog."})),u.post("openModels",gt.openModels,{query:I,success:S(o.Boolean,"Model dialog opened successfully")}).annotateMerge(d.annotations({identifier:"tui.openModels",summary:"Open models dialog",description:"Open the model dialog."})),u.post("submitPrompt",gt.submitPrompt,{query:I,success:S(o.Boolean,"Prompt submitted successfully")}).annotateMerge(d.annotations({identifier:"tui.submitPrompt",summary:"Submit TUI prompt",description:"Submit the prompt."})),u.post("clearPrompt",gt.clearPrompt,{query:I,success:S(o.Boolean,"Prompt cleared successfully")}).annotateMerge(d.annotations({identifier:"tui.clearPrompt",summary:"Clear TUI prompt",description:"Clear the prompt."})),u.post("executeCommand",gt.executeCommand,{query:I,payload:NI,success:S(o.Boolean,"Command executed successfully"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"tui.executeCommand",summary:"Execute TUI command",description:"Execute a TUI command."})),u.post("showToast",gt.showToast,{query:I,payload:ie.ToastShow.data,success:S(o.Boolean,"Toast notification shown successfully")}).annotateMerge(d.annotations({identifier:"tui.showToast",summary:"Show TUI toast",description:"Show a toast notification in the TUI."})),u.post("publish",gt.publish,{query:I,payload:GI,success:S(o.Boolean,"Event published successfully"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"tui.publish",summary:"Publish TUI event",description:"Publish a TUI event."})),u.post("selectSession",gt.selectSession,{query:I,payload:ie.SessionSelect.data,success:S(o.Boolean,"Session selected successfully"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"tui.selectSession",summary:"Select session",description:"Navigate the TUI to display the specified session."})),u.get("controlNext",gt.controlNext,{query:I,success:S(my,"Next TUI request")}).annotateMerge(d.annotations({identifier:"tui.control.next",summary:"Get next TUI request",description:"Retrieve the next TUI request from the queue for processing."})),u.post("controlResponse",gt.controlResponse,{query:I,payload:o.Unknown,success:S(o.Boolean,"Response submitted successfully")}).annotateMerge(d.annotations({identifier:"tui.control.response",summary:"Submit TUI response",description:"Submit a response to the TUI request queue to complete a pending request."}))).annotateMerge(d.annotations({title:"tui",description:"Experimental HttpApi TUI routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var Go="/experimental/workspace",WI=o.Struct(ze.omit(ye.CreateInput.fields,["projectID"])),$I=o.Struct({id:o.NullOr(ye.Info.fields.id),sessionID:ye.SessionWarpInput.fields.sessionID,copyChanges:ye.SessionWarpInput.fields.copyChanges}),ci=class extends o.ErrorClass("WorkspaceWarpError")({name:o.Literal("WorkspaceWarpError"),data:o.Struct({message:o.String})},{httpApiStatus:400}){static{i(this,"ApiWorkspaceWarpError")}},pi=class extends o.ErrorClass("WorkspaceCreateError")({name:o.Literal("WorkspaceCreateError"),data:o.Struct({message:o.String})},{httpApiStatus:400}){static{i(this,"ApiWorkspaceCreateError")}},Xn={adapters:`${Go}/adapter`,list:Go,syncList:`${Go}/sync-list`,status:`${Go}/status`,remove:`${Go}/:id`,warp:`${Go}/warp`},gy=U.make("workspace").add(H.make("workspace").add(u.get("adapters",Xn.adapters,{query:I,success:S(o.Array(ym),"Workspace adapters")}).annotateMerge(d.annotations({identifier:"experimental.workspace.adapter.list",summary:"List workspace adapters",description:"List all available workspace adapters for the current project."})),u.get("list",Xn.list,{query:I,success:S(o.Array(ye.Info),"Workspaces")}).annotateMerge(d.annotations({identifier:"experimental.workspace.list",summary:"List workspaces",description:"List all workspaces."})),u.post("create",Xn.list,{query:I,payload:WI,success:S(ye.Info,"Workspace created"),error:[pi,D.BadRequest]}).annotateMerge(d.annotations({identifier:"experimental.workspace.create",summary:"Create workspace",description:"Create a workspace for the current project."})),u.post("syncList",Xn.syncList,{query:I,success:S(k.NoContent,"Workspace list synced")}).annotateMerge(d.annotations({identifier:"experimental.workspace.syncList",summary:"Sync workspace list",description:"Register missing workspaces returned by workspace adapters."})),u.get("status",Xn.status,{query:I,success:S(o.Array(ye.ConnectionStatus),"Workspace status")}).annotateMerge(d.annotations({identifier:"experimental.workspace.status",summary:"Workspace status",description:"Get connection status for workspaces in the current project."})),u.delete("remove",Xn.remove,{params:{id:ye.Info.fields.id},query:I,success:S(o.UndefinedOr(ye.Info),"Workspace removed"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"experimental.workspace.remove",summary:"Remove workspace",description:"Remove an existing workspace."})),u.post("warp",Xn.warp,{query:I,payload:$I,success:S(k.NoContent,"Session warped"),error:[ci,Hr,te]}).annotateMerge(d.annotations({identifier:"experimental.workspace.warp",summary:"Warp session into workspace",description:"Move a session's sync history into the target workspace, or detach it to the local project."}))).annotateMerge(d.annotations({title:"workspace",description:"Experimental HttpApi workspace routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var Jn=class extends ge.Service()("@opencode/HttpApiSchemaError",{error:Pe}){static{i(this,"SchemaErrorMiddleware")}};var VI=o.Struct({limit:o.optional(o.NumberFromString.check(o.isInt(),o.isGreaterThanOrEqualTo(1),o.isLessThanOrEqualTo(200))).annotate({description:"Maximum number of messages to return. When omitted, the endpoint returns its default page size."}),order:o.optional(o.Union([o.Literal("asc"),o.Literal("desc")])).annotate({description:"Message order for the first page. Use desc for newest first or asc for oldest first."}),cursor:o.optional(o.String.annotate({description:"Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response. Do not combine with order."}))}).annotate({identifier:"SessionMessagesQuery"}),hy=H.make("server.message").add(u.get("session.messages","/api/session/:sessionID/message",{params:{sessionID:K.ID},query:VI,success:o.Struct({data:o.Array(Gr.Message),cursor:o.Struct({previous:o.String.pipe(o.optional),next:o.String.pipe(o.optional)})}).annotate({identifier:"SessionMessagesResponse"}),error:[Lt,N,tt]}).annotateMerge(d.annotations({identifier:"v2.session.messages",summary:"Get session messages",description:"Retrieve projected messages for a session. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline."}))).annotateMerge(d.annotations({title:"messages",description:"Experimental message routes."}));var Sy=H.make("server.model").add(u.get("model.list","/api/model",{query:_,success:z.response(o.Array(ds.Info)),error:mt}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.model.list",summary:"List models",description:"Retrieve available models ordered by release date."}))).annotateMerge(d.annotations({title:"models",description:"Experimental model routes."}));var vy=H.make("server.provider").add(u.get("provider.list","/api/provider",{query:_,success:z.response(o.Array(Qi.Info)),error:mt}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.provider.list",summary:"List providers",description:"Retrieve active AI providers so clients can show provider availability and configuration."}))).add(u.get("provider.get","/api/provider/:providerID",{params:{providerID:Qi.ID},query:_,success:z.response(Qi.Info),error:[Oo,mt]}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.provider.get",summary:"Get provider",description:"Retrieve a single AI provider so clients can inspect its availability and endpoint settings."}))).annotateMerge(d.annotations({title:"providers",description:"Experimental provider routes."}));var za={workspace:Vu.ID.pipe(o.optional),limit:o.NumberFromString.pipe(o.decodeTo(In),o.optional).annotate({description:"Maximum number of sessions to return. Defaults to the newest 50 sessions."}),order:o.optional(o.Union([o.Literal("asc"),o.Literal("desc")])).annotate({description:"Session order for the first page. Use desc for newest first or asc for oldest first."}),search:o.optional(o.String)},zI=o.Struct({...za,directory:we}),QI=o.Struct({...za,project:Ht.ID,subpath:vt.pipe(o.optional)}),YI=o.Struct(za),_p=i(t=>t.mapFields(e=>({...ze.omit(e,["limit"]),anchor:K.ListAnchor})),"withCursor"),KI=o.Union([_p(zI),_p(QI),_p(YI)]),Ay=o.fromJsonString(KI),XI=o.encodeSync(Ay),JI=o.decodeUnknownEffect(Ay),Ey="Invalid cursor",Zn=o.String.pipe(o.brand("SessionsCursor"),Du(t=>{let e=t.make.bind(t);return{make:i(r=>e(Ur.encodeBase64Url(XI(r))),"make"),parse:i(r=>s.suspend(()=>{let n=Ur.decodeBase64UrlString(r);return sc.isFailure(n)?s.fail(Ey):JI(n.success).pipe(s.mapError(()=>Ey))}),"parse")}})),ZI=o.Struct({type:o.Literal("running")}).annotate({identifier:"SessionActive"}),ew=In.check(o.isLessThanOrEqualTo(100)),tw=o.Struct({limit:o.NumberFromString.pipe(o.decodeTo(ew),o.optional),after:o.NumberFromString.pipe(o.decodeTo(Ie),o.optional)}),rw=Zn.annotate({description:"Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response."}),nw=o.Struct({...za,directory:we.pipe(o.optional),project:Ht.ID.pipe(o.optional),subpath:vt.pipe(o.optional),cursor:rw.pipe(o.optional)}).annotate({identifier:"SessionsQuery"}),Iy=i(t=>H.make("server.session").add(u.get("session.list","/api/session",{query:nw,success:o.Struct({data:o.Array(K.Info),cursor:o.Struct({previous:Zn.pipe(o.optional),next:Zn.pipe(o.optional)})}).annotate({identifier:"SessionsResponse"}),error:[Lt,Pe]}).annotateMerge(d.annotations({identifier:"v2.session.list",summary:"List sessions",description:"Retrieve sessions in the requested order. Items keep that order across pages; use cursor.next or cursor.previous to move through the ordered list."}))).add(u.post("session.create","/api/session",{payload:o.Struct({id:K.ID.pipe(o.optional),agent:wn.ID.pipe(o.optional),model:ds.Ref.pipe(o.optional),location:z.Ref.pipe(o.optional)}),success:o.Struct({data:K.Info})}).annotateMerge(d.annotations({identifier:"v2.session.create",summary:"Create session",description:"Create a session at the requested location."}))).add(u.get("session.active","/api/session/active",{success:o.Struct({data:o.Record(K.ID,ZI)})}).annotateMerge(d.annotations({identifier:"v2.session.active",summary:"List active sessions",description:"Retrieve foreground Session drains currently owned by this OpenCode process. Sessions absent from the result are inactive."}))).add(u.get("session.get","/api/session/:sessionID",{params:{sessionID:K.ID},success:o.Struct({data:K.Info}),error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.get",summary:"Get session",description:"Retrieve a session by ID."}))).add(u.post("session.switchAgent","/api/session/:sessionID/agent",{params:{sessionID:K.ID},payload:o.Struct({agent:wn.ID}),success:k.NoContent,error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.switchAgent",summary:"Switch session agent",description:"Switch the agent used by subsequent provider turns."}))).add(u.post("session.switchModel","/api/session/:sessionID/model",{params:{sessionID:K.ID},payload:o.Struct({model:ds.Ref}),success:k.NoContent,error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.switchModel",summary:"Switch session model",description:"Switch the model used by subsequent provider turns."}))).add(u.post("session.prompt","/api/session/:sessionID/prompt",{params:{sessionID:K.ID},payload:o.Struct({id:Gr.ID.pipe(o.optional),prompt:Qu.Prompt,delivery:bc.Delivery.pipe(o.optional),resume:o.Boolean.pipe(o.optional)}),success:o.Struct({data:bc.Admitted}),error:[qo,N]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.prompt",summary:"Send message",description:"Durably admit one session input and schedule agent-loop execution unless resume is false."}))).add(u.post("session.compact","/api/session/:sessionID/compact",{params:{sessionID:K.ID},success:k.NoContent,error:[N,mt]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.compact",summary:"Compact session",description:"Compact a session conversation."}))).add(u.post("session.wait","/api/session/:sessionID/wait",{params:{sessionID:K.ID},success:k.NoContent,error:[N,mt]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.wait",summary:"Wait for session",description:"Wait for a session agent loop to become idle."}))).add(u.post("session.revert.stage","/api/session/:sessionID/revert/stage",{params:{sessionID:K.ID},payload:o.Struct({messageID:Gr.ID,files:o.Boolean.pipe(o.optional)}),success:o.Struct({data:Uu.State}),error:[an,N,tt]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.revert.stage",summary:"Stage session revert",description:"Stage or move a reversible session boundary and optionally apply its file changes."}))).add(u.post("session.revert.clear","/api/session/:sessionID/revert/clear",{params:{sessionID:K.ID},success:k.NoContent,error:[N,tt]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.revert.clear",summary:"Clear staged revert"}))).add(u.post("session.revert.commit","/api/session/:sessionID/revert/commit",{params:{sessionID:K.ID},success:k.NoContent,error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.revert.commit",summary:"Commit staged revert"}))).add(u.get("session.context","/api/session/:sessionID/context",{params:{sessionID:K.ID},success:o.Struct({data:o.Array(Gr.Message)}),error:[N,tt]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.context",summary:"Get session context",description:"Retrieve the active context messages for a session (all messages after the last compaction)."}))).add(u.get("session.history","/api/session/:sessionID/history",{params:{sessionID:K.ID},query:tw,success:o.Struct({data:o.Array(Dn.Durable),hasMore:o.Boolean}).annotate({identifier:"SessionHistory"}),error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.history",summary:"Get session history",description:"Read one finite page of public durable Session events after an exclusive aggregate sequence. Newly committed events may appear on later pages."}))).add(u.get("session.events","/api/session/:sessionID/event",{params:{sessionID:K.ID},query:{after:o.NumberFromString.pipe(o.decodeTo(Ie),o.optional)},success:k.StreamSse({data:Dn.Durable}),error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.events",summary:"Subscribe to session events",description:"Replay durable events after an aggregate sequence, then continue with new durable events."}))).add(u.post("session.interrupt","/api/session/:sessionID/interrupt",{params:{sessionID:K.ID},success:k.NoContent,error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.interrupt",summary:"Interrupt session execution",description:"Interrupt active execution owned by this OpenCode process. Idle interruption is a no-op."}))).add(u.get("session.message","/api/session/:sessionID/message/:messageID",{params:{sessionID:K.ID,messageID:Gr.ID},success:o.Struct({data:Gr.Message}),error:[N,an]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.message",summary:"Get session message",description:"Retrieve one projected message owned by the Session."}))).annotateMerge(d.annotations({title:"sessions",description:"Experimental session routes."})),"makeSessionGroup");var wy=i((t,e)=>H.make("server.permission").add(u.get("permission.request.list","/api/permission/request",{query:_,success:z.response(o.Array(be.Request))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.permission.request.list",summary:"List pending permission requests",description:"Retrieve pending permission requests for a location."}))).add(u.get("permission.saved.list","/api/permission/saved",{query:o.Struct({projectID:Ht.ID.pipe(o.optional)}),success:o.Struct({data:o.Array(qc.Info)})}).annotateMerge(d.annotations({identifier:"v2.permission.saved.list",summary:"List saved permissions",description:"Retrieve saved permissions, optionally filtered by project."}))).add(u.delete("permission.saved.remove","/api/permission/saved/:id",{params:{id:qc.ID},success:k.NoContent}).annotateMerge(d.annotations({identifier:"v2.permission.saved.remove",summary:"Remove saved permission",description:"Remove a saved permission by ID."}))).middleware(t).add(u.post("session.permission.create","/api/session/:sessionID/permission",{params:{sessionID:K.ID},payload:o.Struct({id:be.ID.pipe(o.optional),action:be.Request.fields.action,resources:be.Request.fields.resources,save:be.Request.fields.save,metadata:be.Request.fields.metadata,source:be.Request.fields.source,agent:wn.ID.pipe(o.optional)}),success:o.Struct({data:o.Struct({id:be.ID,effect:be.Effect})}),error:N}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.permission.create",summary:"Create permission request",description:"Evaluate and, when approval is required, create a permission request for a session."}))).add(u.get("session.permission.list","/api/session/:sessionID/permission",{params:{sessionID:K.ID},success:o.Struct({data:o.Array(be.Request)}),error:N}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.permission.list",summary:"List session permission requests",description:"Retrieve pending permission requests owned by a session."}))).add(u.get("session.permission.get","/api/session/:sessionID/permission/:requestID",{params:{sessionID:K.ID,requestID:be.ID},success:o.Struct({data:be.Request}),error:[N,Wn]}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.permission.get",summary:"Get permission request",description:"Retrieve a pending permission request owned by a session."}))).add(u.post("session.permission.reply","/api/session/:sessionID/permission/:requestID/reply",{params:{sessionID:K.ID,requestID:be.ID},payload:o.Struct({reply:be.Reply,message:o.String.pipe(o.optional)}),success:k.NoContent,error:[N,Wn]}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.permission.reply",summary:"Reply to pending permission request",description:"Respond to a pending permission request owned by a session."}))).annotateMerge(d.annotations({title:"permissions",description:"Experimental permission routes."})),"makePermissionGroup");var ow=o.Struct({..._.fields,path:vt.pipe(o.optional)}),sw=o.Struct({..._.fields,query:Rn.FindInput.fields.query,type:Rn.FindInput.fields.type,limit:o.NumberFromString.pipe(o.decodeTo(In),o.optional)}),Dy=H.make("server.fs").add(u.get("fs.read","/api/fs/read/*",{query:_,success:o.Uint8Array.pipe(k.asUint8Array())}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.fs.read",summary:"Read file",description:"Serve one file relative to the requested location."}))).add(u.get("fs.list","/api/fs/list",{query:ow,success:z.response(o.Array(Rn.Entry))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.fs.list",summary:"List directory",description:"List direct children of one directory relative to the requested location."}))).add(u.get("fs.find","/api/fs/find",{query:sw,success:z.response(o.Array(Rn.Entry))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.fs.find",summary:"Find files",description:"Find recursively ranked filesystem entries relative to the requested location."}))).annotateMerge(d.annotations({title:"filesystem",description:"Experimental location-scoped filesystem routes."}));var Ry=H.make("server.command").add(u.get("command.list","/api/command",{query:_,success:z.response(o.Array(Bu.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.command.list",summary:"List commands",description:"Retrieve currently registered commands."}))).annotateMerge(d.annotations({title:"commands",description:"Experimental command routes."}));var Cy=H.make("server.skill").add(u.get("skill.list","/api/skill",{query:_,success:z.response(o.Array(Zu.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.skill.list",summary:"List skills",description:"Retrieve currently registered skills."}))).annotateMerge(d.annotations({title:"skills",description:"Experimental skill routes."}));var iw={id:st.ID,metadata:o.optional(o.Record(o.String,o.Unknown)),durable:o.optional(o.Struct({aggregateID:o.String,seq:o.Int,version:o.Int})),location:o.optional(z.Ref)},aw=i(t=>o.Union([...t,...t.some(e=>e.type==="server.connected")?[]:[o.Struct({...iw,type:o.Literal("server.connected"),data:o.Struct({})}).annotate({identifier:"V2Event.server.connected"})]]).annotate({identifier:"V2Event"}),"schema"),xy=i(t=>{let e=aw(t);return{schema:e,group:H.make("server.event").add(u.get("event.subscribe","/api/event",{success:k.StreamSse({data:e})}).annotateMerge(d.annotations({identifier:"v2.event.subscribe",summary:"Subscribe to events",description:"Subscribe to native event payloads for the server."}))).annotateMerge(d.annotations({title:"events",description:"Experimental event stream route."}))}},"make"),ky=i(t=>xy(t).group,"makeEventGroup"),Hy=xy(ei.ServerDefinitions),Py=Hy.group,Ty=Hy.schema;var by=H.make("server.agent").add(u.get("agent.list","/api/agent",{query:_,success:z.response(o.Array(wn.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.agent.list",summary:"List agents",description:"Retrieve currently registered agents."})));var qy=H.make("server.health").add(u.get("health.get","/api/health",{success:o.Struct({healthy:o.Literal(!0)})}).annotateMerge(d.annotations({identifier:"v2.health.get",summary:"Check server health",description:"Check whether the API server is ready to accept requests."})));var Oy=i((t,e)=>H.make("server.question").add(u.get("question.request.list","/api/question/request",{query:_,success:z.response(o.Array(Yr.Request))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.question.request.list",summary:"List pending question requests",description:"Retrieve pending question requests for a location."}))).annotateMerge(d.annotations({title:"questions",description:"Experimental question routes."})).middleware(t).add(u.get("session.question.list","/api/session/:sessionID/question",{params:{sessionID:K.ID},success:o.Struct({data:o.Array(Yr.Request)}),error:N}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.question.list",summary:"List session question requests",description:"Retrieve pending question requests owned by a session."}))).add(u.post("session.question.reply","/api/session/:sessionID/question/:requestID/reply",{params:{sessionID:K.ID,requestID:Yr.ID},payload:Yr.Reply,success:k.NoContent,error:[N,$n]}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.question.reply",summary:"Reply to pending question request",description:"Answer a pending question request owned by a session."}))).add(u.post("session.question.reject","/api/session/:sessionID/question/:requestID/reject",{params:{sessionID:K.ID,requestID:Yr.ID},success:k.NoContent,error:[N,$n]}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.question.reject",summary:"Reject pending question request",description:"Reject a pending question request owned by a session."}))).annotateMerge(d.annotations({title:"session questions",description:"Experimental session question routes."})),"makeQuestionGroup");var My=H.make("server.reference").add(u.get("reference.list","/api/reference",{query:_,success:z.response(o.Array(ta.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.reference.list",summary:"List references",description:"List references available in the requested location."}))).annotateMerge(d.annotations({title:"reference",description:"Location-scoped project references."}));var cw=o.Record(o.String,o.String),Ly=H.make("server.integration").add(u.get("integration.list","/api/integration",{query:_,success:z.response(o.Array(Ye.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.list",summary:"List integrations",description:"Retrieve available integrations and their authentication methods."}))).add(u.get("integration.get","/api/integration/:integrationID",{params:{integrationID:Ye.ID},query:_,success:z.response(o.UndefinedOr(Ye.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.get",summary:"Get integration",description:"Retrieve one integration and its authentication methods."}))).add(u.post("integration.connect.key","/api/integration/:integrationID/connect/key",{params:{integrationID:Ye.ID},query:_,payload:o.Struct({key:o.String,label:o.optional(o.String)}),success:k.NoContent,error:Pe}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.connect.key",summary:"Connect with key",description:"Run a key authentication method and store the resulting credential."}))).add(u.post("integration.connect.oauth","/api/integration/:integrationID/connect/oauth",{params:{integrationID:Ye.ID},query:_,payload:o.Struct({methodID:Ye.MethodID,inputs:cw,label:o.optional(o.String)}),success:z.response(Ye.Attempt),error:Pe}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.connect.oauth",summary:"Begin OAuth connection",description:"Start an OAuth attempt and return the authorization details."}))).add(u.get("integration.attempt.status","/api/integration/attempt/:attemptID",{params:{attemptID:Ye.AttemptID},query:_,success:z.response(Ye.AttemptStatus)}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.attempt.status",summary:"Get OAuth attempt status",description:"Poll the current status of an OAuth attempt."}))).add(u.post("integration.attempt.complete","/api/integration/attempt/:attemptID/complete",{params:{attemptID:Ye.AttemptID},query:_,payload:o.Struct({code:o.optional(o.String)}),success:k.NoContent,error:Pe}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.attempt.complete",summary:"Complete OAuth connection",description:"Complete a code-based OAuth attempt and store the resulting credential."}))).add(u.delete("integration.attempt.cancel","/api/integration/attempt/:attemptID",{params:{attemptID:Ye.AttemptID},query:_,success:k.NoContent}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.attempt.cancel",summary:"Cancel OAuth connection",description:"Cancel an OAuth attempt and release its resources."}))).annotateMerge(d.annotations({title:"integrations",description:"Integration discovery and authentication routes."}));var Uy=H.make("server.credential").add(u.patch("credential.update","/api/credential/:credentialID",{params:{credentialID:Pc.ID},query:_,payload:o.Struct({label:o.String}),success:k.NoContent}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.credential.update",summary:"Update credential",description:"Update a stored credential label."}))).add(u.delete("credential.remove","/api/credential/:credentialID",{params:{credentialID:Pc.ID},query:_,success:k.NoContent}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.credential.remove",summary:"Remove credential",description:"Remove a stored integration credential."})));var Bp="/experimental/project/:projectID/copy",eo=class extends o.ErrorClass("ProjectCopyError")({name:o.Literal("ProjectCopyError"),data:o.Struct({message:o.String,forceRequired:o.optional(o.Boolean)})},{httpApiStatus:400}){static{i(this,"ProjectCopyError")}},pw=o.Struct(ze.omit(oa.CreateInput.fields,["projectID","sourceDirectory"])),dw=o.Struct(ze.omit(oa.RemoveInput.fields,["projectID"])),Ny=H.make("server.projectCopy").add(u.post("projectCopy.create",Bp,{params:{projectID:Ht.ID},query:_,payload:pw,success:oa.Copy,error:eo}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.projectCopy.create"}))).add(u.delete("projectCopy.remove",Bp,{params:{projectID:Ht.ID},query:_,payload:dw,success:k.NoContent,error:eo}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.projectCopy.remove"}))).add(u.post("projectCopy.refresh",`${Bp}/refresh`,{params:{projectID:Ht.ID},query:_,success:k.NoContent,error:eo}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.projectCopy.refresh"}))).annotateMerge(d.annotations({title:"projectCopy",description:"Project copy management routes."}));var _y=i((t,e,r)=>U.make("server").add(qy).add(cf.middleware(e)).add(by.middleware(e)).add(Iy(r)).add(hy.middleware(r)).add(Sy.middleware(e)).add(vy.middleware(e)).add(Ly.middleware(e)).add(Uy.middleware(e)).add(wy(e,r)).add(Dy.middleware(e)).add(Ry.middleware(e)).add(Cy.middleware(e)).add(t).add(mf.middleware(e)).add(Oy(e,r)).add(My.middleware(e)).add(Ny.middleware(e)).annotateMerge(d.annotations({title:"opencode HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."})).middleware(or).middleware(Jn),"makeApiFromGroup"),By=i(t=>_y(ky(t.definitions),t.locationMiddleware,t.sessionLocationMiddleware),"makeApi"),Fy=i(t=>_y(Py,t.locationMiddleware,t.sessionLocationMiddleware),"makeDefaultApi");var ln=class extends ge.Service()("@opencode/HttpApiLocation"){static{i(this,"LocationMiddleware")}};function J(t){return s.gen(function*(){let e=yield*ce.Service;return{location:new ce.Info({directory:e.directory,workspaceID:e.workspaceID,project:e.project}),data:yield*t}})}i(J,"response");function uw(t){let e=new URL(t.url,"http://localhost").searchParams,r=e.get("location[workspace]")||t.headers["x-opencode-workspace"],n=e.get("location[directory]")||(t.headers["x-opencode-directory"]?mw(t.headers["x-opencode-directory"]):process.cwd());return ce.Ref.make({directory:we.make(n),workspaceID:r?Vr.ID.make(r):void 0})}i(uw,"ref");function mw(t){try{return decodeURIComponent(t)}catch{return t}}i(mw,"decode");var jy=P.effect(ln,s.gen(function*(){let t=yield*Ge.Service;return ln.of(e=>s.gen(function*(){let r=yield*le.HttpServerRequest;return yield*e.pipe(s.provide(t.get(uw(r))))}))}));var fn=class extends ge.Service()("@opencode/HttpApiSessionLocation",{error:[Pe,N]}){static{i(this,"SessionLocationMiddleware")}},lw=o.decodeUnknownEffect(Et.ID),Gy=P.effect(fn,s.gen(function*(){let{db:t}=yield*jr.Service,e=yield*Ge.Service;return fn.of(r=>s.gen(function*(){let n=yield*Ee.RouteContext,a=yield*lw(n.params.sessionID).pipe(s.mapError(()=>new Pe({message:"Invalid session ID",field:"sessionID"}))),c=yield*t.select({directory:ys.directory,workspaceID:ys.workspace_id}).from(ys).where(Yi(ys.id,a)).get().pipe(s.orDie);return c?yield*r.pipe(s.provide(e.get(ce.Ref.make({directory:we.make(c.directory),workspaceID:c.workspaceID?Vr.ID.make(c.workspaceID):void 0})))):yield*new N({sessionID:a,message:`Session not found: ${a}`})}))}));var Wy=oc(xh(),1);var fw=o.Struct({healthy:o.Literal(!0),version:o.String}),yw=xr.Latest.values().flatMap(t=>t.durable?[o.Struct({type:o.Literal("sync"),id:fe.ID,syncEvent:o.Struct({type:o.Literal(fe.versionedType(t.type,t.durable.version)),id:fe.ID,seq:o.Finite,aggregateID:o.String,data:t.data})}).annotate({identifier:`SyncEvent.${t.type}`})]:[]).toArray(),gw=o.Struct({directory:o.String,project:o.optional(o.String),workspace:o.optional(o.String),payload:o.Union([...xr.Latest.values().map(t=>o.Struct({id:fe.ID,type:o.Literal(t.type),properties:t.data})).toArray(),Ba,...yw])}).annotate({identifier:"GlobalEvent"}),hw=o.Struct({target:o.String.check(o.makeFilter(t=>Wy.default.valid(t)===null?"Expected a semantic version":void 0))}),Sw=o.Union([o.Struct({success:o.Literal(!0),version:o.String}),o.Struct({success:o.Literal(!1),error:o.String})]),Wo={health:"/global/health",event:"/global/event",config:"/global/config",dispose:"/global/dispose",upgrade:"/global/upgrade"},$y=U.make("global").add(H.make("global").add(u.get("health",Wo.health,{success:S(fw,"Health information")}).annotateMerge(d.annotations({identifier:"global.health",summary:"Get health",description:"Get health information about the OpenCode server."})),u.get("event",Wo.event,{success:gw}).annotateMerge(d.annotations({identifier:"global.event",summary:"Get global events",description:"Subscribe to global events from the OpenCode system using server-sent events."})),u.get("configGet",Wo.config,{success:S(Wr.Info,"Get global config info")}).annotateMerge(d.annotations({identifier:"global.config.get",summary:"Get global configuration",description:"Retrieve the current global OpenCode configuration settings and preferences."})),u.patch("configUpdate",Wo.config,{payload:Wr.Info,success:S(Wr.Info,"Successfully updated global config"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"global.config.update",summary:"Update global configuration",description:"Update global OpenCode configuration settings and preferences."})),u.post("dispose",Wo.dispose,{success:S(o.Boolean,"Global disposed")}).annotateMerge(d.annotations({identifier:"global.dispose",summary:"Dispose instance",description:"Clean up and dispose all OpenCode instances, releasing all resources."})),u.post("upgrade",Wo.upgrade,{payload:hw,success:S(Sw,"Upgrade result"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"global.upgrade",summary:"Upgrade opencode",description:"Upgrade opencode to the specified version."}))).annotateMerge(d.annotations({title:"global",description:"Global server routes."})));var Fp=1024;function vw(t){return t.length<=Fp?t:t.slice(0,Fp)+`\u2026 (${t.length-Fp} more chars)`}i(vw,"truncateReason");var $o=class extends ge.Service()("@opencode/HttpApiSchemaError",{error:Yn}){static{i(this,"SchemaErrorMiddleware")}},jp=ge.layerSchemaErrorTransform($o,(t,e)=>{let r=vw(t.cause.message),n=e.endpoint.path.startsWith("/api/")?s.fail(new Yn({message:r,kind:t.kind})):s.succeed(q.jsonUnsafe({name:"BadRequest",data:{message:r,kind:t.kind}},{status:400}));return s.logWarning("schema rejection",{kind:t.kind,reason:r}).pipe(s.andThen(n))});var Ew=o.Union([...xr.Latest.values().map(t=>o.Struct({id:fe.ID,type:o.Literal(t.type),properties:t.data}).annotate({identifier:`Event.${t.type}`})).toArray(),Ba]).annotate({identifier:"Event"}),Aw=By({definitions:xr.Latest.values().toArray(),locationMiddleware:ln,sessionLocationMiddleware:fn}),Pr=U.make("opencode-root").addHttpApi(zf).addHttpApi(Qf).addHttpApi($y).middleware($o).middleware(j),Q=U.make("opencode-instance").addHttpApi($f).addHttpApi(Wf).addHttpApi(Yf).addHttpApi(Xf).addHttpApi(Jf).addHttpApi(Zf).addHttpApi(ry).addHttpApi(ny).addHttpApi(iy).addHttpApi(ay).addHttpApi(ty).addHttpApi(oy).addHttpApi(py).addHttpApi(uy).addHttpApi(yy).addHttpApi(gy).middleware($o),Gp=U.make("opencode").addHttpApi(Pr).addHttpApi(Bo).addHttpApi(Q).addHttpApi(Aw).addHttpApi(jo).annotate(U.AdditionalSchemas,[Ew,$t.Replied,$t.Rejected,_u.Value,je.Inputs,je.Method,je.Ref,ra.Source]);var V=Fy({locationMiddleware:ln,sessionLocationMiddleware:fn});var Iw={"GET /experimental/session start":{type:"number"},"GET /experimental/session roots":si,"GET /experimental/session archived":si,"GET /find/file limit":{type:"integer",minimum:1,maximum:200},"GET /experimental/session cursor":{type:"number"},"GET /experimental/session limit":{type:"number"},"GET /session start":{type:"number"},"GET /session roots":si,"GET /session limit":{type:"number"},"GET /session/{sessionID}/message limit":{type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER},"GET /vcs/diff context":{type:"integer",minimum:0},"GET /api/session limit":{type:"number"},"GET /api/session start":{type:"number"},"GET /api/session roots":si,"GET /api/session/{sessionID}/message limit":{type:"number"}},ww={LogLevel:"Log level",ServerConfig:"Server configuration for opencode serve and web commands",LayoutConfig:"@deprecated Always uses stretch layout."};function Dw(t){let e=t;Uw(e);for(let[r,n]of Object.entries(e.components?.schemas??{}))e.components.schemas[r]=ht(structuredClone(n));kw(e),xw(e),Pw(e),Tw(e),Cw(e),delete e.components?.securitySchemes;for(let[r,n]of Object.entries(e.paths??{}))for(let a of["get","post","put","delete","patch"]){let c=n[a];if(!c)continue;let p=Rw(r);if(c.requestBody){p||delete c.requestBody.required;let l=c.requestBody.content?.["application/json"];if(l?.schema&&(l.schema=ht(structuredClone(l.schema))),r==="/experimental/workspace"&&a==="post"){let m=c.requestBody.content?.["application/json"]?.schema?.$ref?.replace("#/components/schemas/",""),y=m?e.components?.schemas?.[m]?.properties:c.requestBody.content?.["application/json"]?.schema?.properties;y?.branch&&(y.branch={anyOf:[y.branch,{type:"null"}]}),y?.extra&&(y.extra={anyOf:[y.extra,{type:"null"}]})}if(r==="/experimental/workspace/warp"&&a==="post"){let m=c.requestBody.content?.["application/json"]?.schema?.$ref?.replace("#/components/schemas/",""),y=m?e.components?.schemas?.[m]?.properties:c.requestBody.content?.["application/json"]?.schema?.properties;y?.id&&(y.id={anyOf:[y.id,{type:"null"}]})}}for(let l of Object.values(c.responses??{}))for(let m of Object.values(l.content??{}))m.schema&&(m.schema=ht(structuredClone(m.schema)));p||(delete c.security,delete c.responses?.[401],qw(c)),Mw(c,r,a),(r==="/event"||r==="/global/event"||r==="/api/event")&&a==="get"&&(c.responses[200]={description:"Event stream",content:{"text/event-stream":{schema:r==="/event"?{$ref:"#/components/schemas/Event"}:r==="/global/event"?{$ref:"#/components/schemas/GlobalEvent"}:{$ref:"#/components/schemas/V2Event"}}}});let f=`${a.toUpperCase()} ${r}`;for(let l of c.parameters??[])Fw(l,f)}return Ow(e),t}i(Dw,"matchLegacyOpenApi");function Rw(t){return t==="/api"||t.startsWith("/api/")}i(Rw,"isV2ApiPath");function Cw(t){t.components?.schemas&&(t.components.schemas.BadRequestError={type:"object",required:["name","data"],properties:{name:{type:"string",enum:["BadRequest"]},data:{type:"object",required:["message"],properties:{message:{type:"string"},kind:{type:"string",enum:["Params","Headers","Query","Body","Payload"]}}}}},t.components.schemas.NotFoundError={type:"object",required:["name","data"],properties:{name:{type:"string",enum:["NotFoundError"]},data:{type:"object",required:["message"],properties:{message:{type:"string"}}}}})}i(Cw,"addLegacyErrorSchemas");function xw(t){let e=t.components?.schemas;if(e)for(let r of Object.keys(e)){let n=r.replace(/\d+$/,"");n===r||!e[n]||Qa(e[r],e)===Qa(e[n],e)&&(di(t,r,n),delete e[r])}}i(xw,"collapseDuplicateComponents");function kw(t){let e=t.components?.schemas;if(e)for(let r of Object.keys(e)){let n=Hw(r);if(n!==r){if(e[n]){Qa(e[r],e)===Qa(e[n],e)&&(di(t,r,n),delete e[r]);continue}e[n]=e[r],di(t,r,n),delete e[r]}}}i(kw,"normalizeComponentNames");function Hw(t){return t.includes(".")?t.split(".").filter(e=>!/^\d+$/.test(e)).map(e=>e.slice(0,1).toUpperCase()+e.slice(1)).join(""):t}i(Hw,"componentTypeName");function Pw(t){let e=t.components?.schemas;if(!e)return;e.AgentConfig&&(e.AgentConfig.additionalProperties={}),e.Command?.properties?.template&&(e.Command.properties.template={type:"string"}),e.Workspace?.properties&&(e.Workspace.properties.branch=Vo(e.Workspace.properties.branch),e.Workspace.properties.directory=Vo(e.Workspace.properties.directory),e.Workspace.properties.extra=Vo(e.Workspace.properties.extra)),e.GlobalSession?.properties?.project&&(e.GlobalSession.properties.project=Vo(e.GlobalSession.properties.project));let r=e.ProviderConfig?.properties?.options;r&&(r.additionalProperties={});let n=e.ProviderConfig?.properties?.models?.additionalProperties,a=typeof n=="object"?n.properties?.variants?.additionalProperties:void 0;a&&typeof a=="object"&&(a.additionalProperties={});let c=e.SyncEventSessionUpdated?.properties?.data?.properties?.info;c?.properties&&zy(c.properties)}i(Pw,"applyLegacySchemaOverrides");function Tw(t){for(let[e,r]of Object.entries(t.components?.schemas??{})){let n=ww[e];if(n){r.description=n;continue}delete r.description}}i(Tw,"normalizeComponentDescriptions");function zy(t){for(let[e,r]of Object.entries(t)){if(e==="share"&&r.properties?.url){r.properties.url=Vo(r.properties.url);continue}if(e==="time"&&r.properties){zy(r.properties);continue}t[e]=Vo(r)}}i(zy,"makePropertiesNullable");function Vo(t){return Vp(t.anyOf??t.oneOf)?.some(e=>e.type==="null")?t:{anyOf:[t,{type:"null"}]}}i(Vo,"nullable");function Qa(t,e){return JSON.stringify(Wp(t,e))}i(Qa,"stableSchema");function Wp(t,e){if(Array.isArray(t))return t.map(n=>Wp(n,e));if(!t||typeof t!="object")return t;let r=t;return r.$ref?{$ref:bw(r.$ref,e)}:Object.fromEntries(Object.entries(t).filter(([n])=>n!=="description").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,Wp(a,e)]))}i(Wp,"canonicalizeSchema");function bw(t,e){let r=t.replace("#/components/schemas/",""),n=r.replace(/\d+$/,"");return n!==r&&e[n]?`#/components/schemas/${n}`:t}i(bw,"canonicalRef");function di(t,e,r){if(Array.isArray(t)){for(let a of t)di(a,e,r);return}if(!t||typeof t!="object")return;let n=t;n.$ref===`#/components/schemas/${e}`&&(n.$ref=`#/components/schemas/${r}`);for(let a of Object.values(t))di(a,e,r)}i(di,"rewriteRefs");function qw(t){t.responses?.["400"]&&Lw(t.responses[400])&&(t.responses[400]=Vy("Bad request","BadRequestError")),t.responses?.["404"]&&Yy(t.responses[404],"NotFound")&&(t.responses[404]=Vy("Not found","NotFoundError"))}i(qw,"normalizeLegacyErrorResponses");function Ow(t){for(let e of["Unauthorized","EffectHttpApiErrorBadRequest","EffectHttpApiErrorNotFound","effect_HttpApiError_BadRequest","effect_HttpApiError_NotFound"])$p(t.paths,e)||delete t.components?.schemas?.[e]}i(Ow,"deleteUnusedLegacyErrorComponents");function $p(t,e){return Array.isArray(t)?t.some(r=>$p(r,e)):!t||typeof t!="object"?!1:t.$ref===`#/components/schemas/${e}`?!0:Object.values(t).some(r=>$p(r,e))}i($p,"referencesComponent");function Mw(t,e,r){if(e==="/experimental/console/switch"&&r==="post"&&delete t.responses?.[400],e!=="/session/{sessionID}/message"&&e!=="/session/{sessionID}/command"||r!=="post")return;let n=t.responses?.["200"]?.content?.["application/json"];n&&(n.schema={type:"object",required:["info","parts"],properties:{info:{$ref:"#/components/schemas/AssistantMessage"},parts:{type:"array",items:{$ref:"#/components/schemas/Part"}}}})}i(Mw,"normalizeLegacyOperation");function Qy(t,e){return t.content?.["application/json"]?.schema?.$ref===`#/components/schemas/${e}`}i(Qy,"isRefResponse");function Yy(t,e){return t.description===e||Qy(t,`EffectHttpApiError${e}`)}i(Yy,"isBuiltInErrorResponse");function Lw(t){return Yy(t,"BadRequest")||Qy(t,"InvalidRequestError")}i(Lw,"isLegacyBadRequestResponse");function Vy(t,e){return{description:t,content:{"application/json":{schema:{$ref:`#/components/schemas/${e}`}}}}}i(Vy,"legacyErrorResponse");function Uw(t){let e=t.components?.schemas;if(!e)return;let r=new Set;for(let[c,p]of Object.entries(e))p.$ref===`#/components/schemas/${c}`&&r.add(c);if(r.size===0)return;for(let[,c]of Object.entries(e))for(let p of c.anyOf??c.oneOf??[]){let f=p.$ref?.replace("#/components/schemas/","");!f||r.has(f)}let a=d.fromApi(Gp).components?.schemas;if(a)for(let c of r)a[c]&&(e[c]=a[c])}i(Uw,"fixSelfReferencingComponents");function ht(t){if(t.allOf?.length===1){let[r]=t.allOf;return delete t.allOf,ht({...t,...r})}if(Nw(t))return{type:"object",properties:{}};let e=Vp(t.anyOf??t.oneOf);if(e){let r=e.filter(n=>n.type!=="null");if(r.length===1)return ht(r[0]);t.anyOf&&(t.anyOf=r.map(ht)),t.oneOf&&(t.oneOf=r.map(ht))}if(t.allOf){let r=t.allOf.map(ht);if(t.type){delete t.allOf;for(let n of r)Object.assign(t,n)}else t.allOf=r}if(t.prefixItems&&t.items&&delete t.prefixItems,t.items&&(t.items=ht(t.items)),t.properties)for(let[r,n]of Object.entries(t.properties))t.properties[r]=ht(n);return t.additionalProperties&&typeof t.additionalProperties=="object"&&(t.additionalProperties=ht(t.additionalProperties)),t}i(ht,"stripOptionalNull");function Nw(t){let e=t.anyOf??t.oneOf;return e?.length===2&&e.some(_w)&&e.some(Bw)}i(Nw,"isEmptyObjectUnion");function _w(t){return t.type==="object"&&!t.properties&&!t.additionalProperties}i(_w,"isBareObjectSchema");function Bw(t){return t.type==="array"&&!t.items&&!t.prefixItems}i(Bw,"isBareArraySchema");function Vp(t){return t?.flatMap(e=>Vp(e.anyOf??e.oneOf)??[e])}i(Vp,"flattenOptions");function Fw(t,e){if(!(!t.schema||typeof t.schema!="object")){if(t.in==="path"){t.schema=ht(t.schema);return}if(t.in==="query"){let r=Iw[`${e} ${t.name}`];if(r){t.schema=r;return}}t.schema=ht(t.schema)}}i(Fw,"normalizeParameter");var Ya=Gp.annotateMerge(d.annotations({title:"opencode",version:"1.0.0",description:"opencode api",transform:Dw}));function jw(t){return{_tag:"Event",event:"message",id:void 0,data:JSON.stringify(t)}}i(jw,"eventData");function zp(){return fe.ID.create()}i(zp,"eventID");function Gw(t){return s.gen(function*(){let e=yield*Ue.context,r=yield*Ue.workspaceID,n=yield*Ae.unbounded(),a=yield*t.listen(m=>s.sync(()=>Ae.offerUnsafe(n,m)));yield*s.addFinalizer(()=>a);let c=Gd(n).pipe($d(m=>m.location?.directory===e.directory&&(m.location.workspaceID===void 0||m.location.workspaceID===r)),Ft(m=>({id:m.id,type:m.type,properties:m.data}))),p=Ri(m=>{let y=i(g=>{g.directory!==e.directory||g.payload.type!=="server.instance.disposed"||Ae.offerUnsafe(m,{id:g.payload.id??zp(),type:"server.instance.disposed",properties:g.payload.properties??{}})},"listener");return s.acquireRelease(s.sync(()=>lr.on("event",y)),()=>s.sync(()=>lr.off("event",y)))}),f=c.pipe(is(p,{haltStrategy:"left"}),zd(m=>m.type==="server.instance.disposed")),l=Di("10 seconds").pipe(xi(1),Ft(()=>({id:zp(),type:"server.heartbeat",properties:{}})));return yield*s.logInfo("event connected"),q.stream(io({id:zp(),type:"server.connected",properties:{}}).pipe(Ci(f.pipe(is(l,{haltStrategy:"left"}))),Ft(jw),ki(po()),Nr,Hi(s.logInfo("event disconnected"))),{contentType:"text/event-stream",headers:{"Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no","X-Content-Type-Options":"nosniff"}})})}i(Gw,"eventResponse");var Ky=x.group(Bo,"event",t=>s.gen(function*(){let e=yield*Wt.Service;return t.handleRaw("subscribe",s.fn("EventHttpApi.subscribe")(function*(){return yield*Gw(e)}))}));var Qp=new WeakMap,Xy=i(t=>s.gen(function*(){return{ctx:t,store:yield*It.Service,bridge:yield*ho.make()}}),"mark"),Ka=i(t=>s.gen(function*(){let e=yield*Xy(t);return yield*Br.appendPreResponseHandler((r,n)=>s.sync(()=>(Qp.set(r.source,e),n)))}),"markInstanceForDisposal"),Jy=i((t,e)=>s.gen(function*(){let r=yield*Xy(t);return yield*Br.appendPreResponseHandler((n,a)=>s.as(s.uninterruptible(r.bridge.run(r.store.reload(e))),a))}),"markInstanceForReload"),Xa=i(t=>s.gen(function*(){let e=yield*t,r=yield*le.HttpServerRequest,n=Qp.get(r.source);return n&&(Qp.delete(r.source),yield*s.uninterruptible(n.bridge.run(n.store.dispose(n.ctx))).pipe(s.catchCause(a=>s.logWarning("instance disposal failed",{cause:a})))),e}),"disposeMiddleware");var Zy=x.group(Q,"config",t=>s.gen(function*(){let e=yield*Oe.Service,r=yield*At.Service,n=s.fn("ConfigHttpApi.get")(function*(){return yield*r.get()}),a=s.fn("ConfigHttpApi.update")(function*(p){return yield*r.update(p.payload),yield*Ka(yield*pe),p.payload}),c=s.fn("ConfigHttpApi.providers")(function*(){let p=yield*e.list();return{providers:Object.values(p).map(Oe.toPublicInfo),default:Oe.defaultModelIDs(p)}});return t.handle("get",n).handle("update",a).handle("providers",c)}));var zo,eg=new Map;async function tg(t,e){let r=await fetch(t,{headers:e,signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`HTTP ${r.status}`);return r.json()}i(tg,"readUsageJson");function Ww(t){let e=[];for(let r of["primary_window","secondary_window"]){let n=t?.[r];if(!n||typeof n!="object")continue;let a=Number(n.limit_window_seconds??0),c=a>=5e5?"7d":a>0&&a<=21600?"5h":"other";e.push({kind:c,label:c==="7d"?"weekly":c==="5h"?"5-hour window":`${Math.round(a/3600)}h window`,usedPercent:Number(n.used_percent??0),resetsAt:typeof n.reset_at=="number"?n.reset_at:null})}return e}i(Ww,"openaiWindows");async function $w(t){let e={authorization:`Bearer ${t.access}`};t.accountId&&(e["ChatGPT-Account-Id"]=t.accountId);let r=await tg("https://chatgpt.com/backend-api/wham/usage",e);return{providerID:"openai",plan:typeof r?.plan_type=="string"?r.plan_type:null,windows:Ww(r?.rate_limit)}}i($w,"openaiUsage");async function Vw(t){let e=await tg("https://api.anthropic.com/api/oauth/usage",{authorization:`Bearer ${t.access}`,"anthropic-beta":"oauth-2025-04-20"}),r=i(a=>typeof a=="string"&&!Number.isNaN(Date.parse(a))?Math.floor(Date.parse(a)/1e3):null,"toTs"),n=[];e?.five_hour&&typeof e.five_hour=="object"&&n.push({kind:"5h",label:"5-hour window",usedPercent:Number(e.five_hour.utilization??0),resetsAt:r(e.five_hour.resets_at)}),e?.seven_day&&typeof e.seven_day=="object"&&n.push({kind:"7d",label:"weekly",usedPercent:Number(e.seven_day.utilization??0),resetsAt:r(e.seven_day.resets_at)});for(let a of Array.isArray(e?.limits)?e.limits:[]){let c=a?.scope?.model?.display_name;a?.kind==="weekly_scoped"&&typeof c=="string"&&c&&n.push({kind:"other",label:`weekly, ${c}`,usedPercent:Number(a.percent??0),resetsAt:r(a.resets_at)})}return{providerID:"anthropic",plan:null,windows:n}}i(Vw,"anthropicUsage");async function rg(t,e=!1){if(!e&&zo&&Date.now()-zo.at<6e4)return{providers:zo.data,fetchedAt:zo.at};let r=[];for(let[n,a]of Object.entries(t)){if(a.type!=="oauth"||n!=="openai"&&n!=="anthropic")continue;let c=a;if(c.expires<Date.now()){r.push({providerID:n,plan:null,windows:[],error:"token expired; it refreshes on the next model call"});continue}try{let p={...n==="openai"?await $w(c):await Vw(c),readAt:Date.now()};eg.set(n,p),r.push(p)}catch(p){let f=p instanceof Error?p.message:String(p),l=eg.get(n);r.push(l?{...l,error:f}:{providerID:n,plan:null,windows:[],error:f})}}return zo={at:Date.now(),data:r},{providers:r,fetchedAt:zo.at}}i(rg,"providerUsage");var Ja,ng=x.group(Q,"alchemy",t=>s.gen(function*(){let e=yield*Gt.Service,r=yield*At.Service,n=yield*qe.Service,a=yield*Vt.Service,c=yield*Xr.Service,p=yield*It.Service,f=s.fn("AlchemyHttpApi.anyBusy")(function*(){for(let w of(yield*c.list()).values())if(w.type!=="idle")return!0;return!1}),l=s.fn("AlchemyHttpApi.reloadNow")(function*(){yield*r.invalidate(),yield*p.disposeAll()}),m=s.fn("AlchemyHttpApi.pauseState")(function*(){return ga.state()}),y=s.fn("AlchemyHttpApi.pause")(function*(w){return w.payload.paused?(ga.pause(),{paused:!0,stopped:yield*a.stopForPause()}):{paused:!1,waiting:ga.resume()}}),g=s.fn("AlchemyHttpApi.reload")(function*(){if(yield*f()){if(!Ja){let w=yield*ho.make(),C=Date.now();Ja=setInterval(()=>{w.promise(s.gen(function*(){(yield*f())&&Date.now()-C<12e4||(clearInterval(Ja),Ja=void 0,yield*l())})).catch(()=>{})},2e3)}return{ok:!0,deferred:!0}}return yield*l(),{ok:!0}}),E=s.fn("AlchemyHttpApi.usage")(function*(w){let C=yield*e.all().pipe(s.orElseSucceed(()=>({})));return yield*s.promise(()=>rg(C,w.query.force==="1"))}),v=s.fn("AlchemyHttpApi.mcpTools")(function*(){return yield*n.defs()}),h=s.fn("AlchemyHttpApi.searchKeys")(function*(){let w=yield*e.all().pipe(s.orElseSucceed(()=>({}))),C=i(R=>{let b=w[R];return b?.type==="api"&&b.key.trim().length>0},"has");return{exa:C(_c.exa),tavily:C(_c.tavily)}});return t.handle("pauseState",m).handle("pause",y).handle("reload",g).handle("usage",E).handle("mcpTools",v).handle("searchKeys",h)}));var og=x.group(Pr,"control",t=>s.gen(function*(){let e=yield*Gt.Service,r=s.fn("ControlHttpApi.authSet")(function*(c){return yield*e.set(c.params.providerID,c.payload).pipe(s.orDie),!0}),n=s.fn("ControlHttpApi.authRemove")(function*(c){return yield*e.remove(c.params.providerID).pipe(s.orDie),!0}),a=s.fn("ControlHttpApi.log")(function*(c){return yield*(c.payload.level==="debug"?s.logDebug:c.payload.level==="info"?s.logInfo:c.payload.level==="warn"?s.logWarning:s.logError)(c.payload.message).pipe(s.annotateLogs(c.payload.extra??{})),!0});return t.handle("authSet",r).handle("authRemove",n).handle("log",a)}));var sg=x.group(Pr,"controlPlane",t=>s.gen(function*(){let e=yield*Mt.Service,r=s.fn("ControlPlaneHttpApi.moveSession")(function*(n){yield*e.moveSession(n.payload).pipe(s.mapError(a=>new ni({name:"MoveSessionError",data:{message:zw(a)}})))});return t.handle("moveSession",r)}));function zw(t){return t instanceof Et.NotFoundError?`Session not found: ${t.sessionID}`:t instanceof Mt.DestinationProjectMismatchError?"Destination directory belongs to another project":t instanceof Mt.ApplyChangesError?"Unable to apply your changes in the destination directory. The files may conflict with existing changes.":t.message}i(zw,"message");function Yp(t){return t.pipe(s.mapError(e=>new pn({name:e._tag,data:{message:e.message}})))}i(Yp,"mapWorktreeError");var ig=x.group(Q,"experimental",t=>s.gen(function*(){let e=yield*ia.Service,r=yield*zt.Service,n=yield*At.Service,a=yield*qe.Service,c=yield*it.Service,p=yield*ya.Service,f=yield*fr.Service,l=yield*X.Service,m=yield*pa.Service,y=yield*vs.Service,g=s.fn("ExperimentalHttpApi.capabilities")(function*(){return{backgroundSubagents:y.experimentalBackgroundSubagents}}),E=s.fn("ExperimentalHttpApi.console")(function*(){let[F,ue]=yield*s.all([n.getConsoleState(),e.orgsByAccount().pipe(s.catch(()=>s.fail(new D.InternalServerError({}))))],{concurrency:"unbounded"});return{consoleManagedProviders:F.consoleManagedProviders,...F.activeOrgName?{activeOrgName:F.activeOrgName}:{},switchableOrgCount:ue.reduce((ke,ne)=>ke+ne.orgs.length,0)}}),v=s.fn("ExperimentalHttpApi.consoleOrgs")(function*(){let[F,ue]=yield*s.all([e.orgsByAccount().pipe(s.catch(()=>s.fail(new D.InternalServerError({})))),e.active().pipe(s.catch(()=>s.fail(new D.InternalServerError({}))))],{concurrency:"unbounded"}),ke=Ce.getOrUndefined(ue);return{orgs:F.flatMap(ne=>ne.orgs.map(Ve=>({accountID:ne.account.id,accountEmail:ne.account.email,accountUrl:ne.account.url,orgID:Ve.id,orgName:Ve.name,active:!!ke&&ke.id===ne.account.id&&ke.active_org_id===Ve.id})))}}),h=s.fn("ExperimentalHttpApi.consoleSwitch")(function*(F){return yield*e.use(F.payload.accountID,Ce.some(F.payload.orgID)).pipe(s.catch(()=>s.fail(new D.BadRequest({})))),!0}),w=s.fn("ExperimentalHttpApi.tool")(function*(F){return(yield*p.tools({providerID:F.query.provider,modelID:F.query.model,agent:yield*r.defaultInfo()})).map(ke=>({id:ke.id,description:ke.description,parameters:Cm.fromTool(ke)}))}),C=s.fn("ExperimentalHttpApi.toolIDs")(function*(){return yield*p.ids()}),R=s.fn("ExperimentalHttpApi.worktree")(function*(){let F=yield*Ue.context;return yield*c.sandboxes(F.project.id)}),b=s.fn("ExperimentalHttpApi.worktreeCreate")(function*(F){return yield*Yp(f.create(F.payload??void 0))}),O=s.fn("ExperimentalHttpApi.worktreeRemove")(function*(F){let ue=yield*Ue.context;return yield*Yp(f.remove(F.payload)),yield*c.removeSandbox(ue.project.id,F.payload.directory),!0}),Z=s.fn("ExperimentalHttpApi.worktreeReset")(function*(F){return yield*Yp(f.reset(F.payload)),!0}),Se=s.fn("ExperimentalHttpApi.session")(function*(F){let ue=F.query.limit??100,ke=F.query.directory?yield*Ue.directory:void 0,ne=yield*l.listGlobal({directory:ke,roots:F.query.roots,start:F.query.start,cursor:F.query.cursor,search:F.query.search,limit:ue+1,archived:F.query.archived}),Ve=ne.length>ue?ne.slice(0,ue):ne;return Gi(Ve,{headers:ne.length>ue&&Ve.length>0?{"x-next-cursor":String(Ve[Ve.length-1].time.updated)}:void 0})}),Re=s.fn("ExperimentalHttpApi.sessionBackground")(function*(F){if(!y.experimentalBackgroundSubagents)return!1;let ue=(yield*m.list()).filter(ne=>ne.type==="task"&&ne.status==="running"&&ne.metadata?.parentSessionId===F.params.sessionID&&ne.metadata.background!==!0);return(yield*s.forEach(ue,ne=>m.promote(ne.id),{concurrency:"unbounded"})).some(ne=>ne!==void 0)}),ar=s.fn("ExperimentalHttpApi.resource")(function*(){return yield*a.resources()});return t.handle("capabilities",g).handle("console",E).handle("consoleOrgs",v).handle("consoleSwitch",h).handle("tool",w).handle("toolIDs",C).handle("worktree",R).handle("worktreeCreate",b).handle("worktreeRemove",O).handle("worktreeReset",Z).handle("session",Se).handle("sessionBackground",Re).handle("resource",ar)}));var gg=oc(yg(),1);import to from"path";var hg=x.group(Q,"file",t=>s.gen(function*(){let e=yield*Zi.Service,r=yield*Ge.Service,n=s.fnUntraced(function*(y){return yield*y.pipe(s.provide(r.get(ce.Ref.make({directory:we.make((yield*pe).directory)}))))}),a=s.fn("FileHttpApi.findText")(function*(y){return(yield*e.grep({cwd:(yield*pe).directory,pattern:y.query.pattern,limit:10}).pipe(s.orDie)).map(g=>({path:{text:g.entry.path},lines:{text:g.text},line_number:g.line,absolute_offset:g.offset,submatches:g.submatches.map(E=>({match:{text:E.text},start:E.start,end:E.end}))}))}),c=s.fn("FileHttpApi.findFile")(function*(y){let g=(yield*pe).directory,E=y.query.limit??10,v=y.query.type??(y.query.dirs==="false"?"file":void 0),h=performance.now(),w=yield*n($r.Service.use(C=>C.find({query:y.query.query,limit:E,type:v})));return yield*s.logInfo("find file",{query:y.query.query,type:v,directory:g,limit:E,results:w.length,duration:Math.round(performance.now()-h)}),w.map(C=>C.path)}),p=s.fn("FileHttpApi.findSymbol")(function*(){return[]}),f=s.fn("FileHttpApi.list")(function*(y){let g=(yield*pe).directory;return yield*n(s.gen(function*(){let E=yield*$r.Service,v=yield*mr.Service,h=yield*ce.Service,w=(0,gg.default)(),C=yield*v.readFileString(to.join(h.project.directory,".gitignore")).pipe(s.catch(()=>s.succeed("")));C&&w.add(C);let R=yield*v.readFileString(to.join(h.project.directory,".ignore")).pipe(s.catch(()=>s.succeed("")));return R&&w.add(R),(yield*E.list({path:vt.make(y.query.path)})).map(b=>({name:to.basename(b.path),path:b.path,absolute:to.resolve(h.directory,b.path),type:b.type,ignored:w.ignores(to.relative(h.project.directory,to.resolve(h.directory,b.path))+(b.type==="directory"?"/":""))}))}))}),l=s.fn("FileHttpApi.content")(function*(y){let g=(yield*pe).directory,E=to.resolve(g,y.query.path);return mr.contains(g,E)?(yield*mr.Service.use(v=>v.existsSafe(E)))?yield*n($r.Service.use(v=>v.read({path:vt.make(y.query.path)}))).pipe(s.flatMap(v=>s.gen(function*(){let h=v.content.includes(0)?Ce.none():yield*s.sync(()=>new TextDecoder("utf-8",{fatal:!0}).decode(v.content)).pipe(s.option);return{item:v,text:h}})),s.map(({item:v,text:h})=>Ce.isSome(h)?{type:"text",content:h.value.trim()}:{type:"binary",content:Buffer.from(v.content).toString("base64"),encoding:"base64",mimeType:v.mime})):{type:"text",content:""}:yield*s.die(new Error("Path escapes the location"))}),m=s.fn("FileHttpApi.status")(function*(){return[]});return t.handle("findText",a).handle("findFile",c).handle("findSymbol",p).handle("list",f).handle("content",l).handle("status",m)})).pipe(P.provide(Ss));var fD=s.sync(()=>lr.emit("event",{directory:"global",payload:{type:rf.Disposed.type,properties:{}}})),rd=s.fn("Server.disposeAllInstancesAndEmitGlobalDisposed")(function*(t){let e=yield*It.Service;yield*s.gen(function*(){yield*t?.swallowErrors?e.disposeAll().pipe(s.catchCause(r=>s.logWarning("global disposal failed",{cause:r}))):e.disposeAll(),yield*fD}).pipe(s.uninterruptible)});function gD(t){return{_tag:"Event",event:"message",id:void 0,data:JSON.stringify(t)}}i(gD,"eventData");function hD(){return s.gen(function*(){yield*s.logInfo("global event connected");let t=Ri(r=>{let n=i(a=>Ae.offerUnsafe(r,a),"handler");return s.acquireRelease(s.sync(()=>lr.on("event",n)),()=>s.sync(()=>lr.off("event",n)))}),e=Di("10 seconds").pipe(xi(1),Ft(()=>({payload:{id:fe.ID.create(),type:"server.heartbeat",properties:{}}})));return q.stream(io({payload:{id:fe.ID.create(),type:"server.connected",properties:{}}}).pipe(Ci(t.pipe(is(e,{haltStrategy:"left"}))),Ft(gD),ki(po()),Nr,Hi(s.logInfo("global event disconnected"))),{contentType:"text/event-stream",headers:{"Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no","X-Content-Type-Options":"nosniff"}})})}i(hD,"eventResponse");var Sg=x.group(Pr,"global",t=>s.gen(function*(){let e=yield*At.Service,r=yield*Es.Service,n=yield*ho.make(),a=s.fn("GlobalHttpApi.health")(function*(){return{healthy:!0,version:qu}}),c=s.fn("GlobalHttpApi.event")(function*(){return yield*hD()}),p=s.fn("GlobalHttpApi.configGet")(function*(){return yield*e.getGlobal()}),f=s.fn("GlobalHttpApi.configUpdate")(function*(y){let g=yield*e.updateGlobal(y.payload);return g.changed&&n.fork(rd({swallowErrors:!0})),g.info}),l=s.fn("GlobalHttpApi.dispose")(function*(){return yield*rd(),!0}),m=s.fn("GlobalHttpApi.upgrade")(function*(y){let g=yield*r.method();if(g==="unknown")return q.jsonUnsafe({success:!1,error:"Unknown installation method"},{status:400});let E=y.payload.target,v=yield*r.upgrade(g,E).pipe(s.as({success:!0,version:E}),s.catch(h=>s.succeed({success:!1,error:h instanceof Error?h.message:String(h)})));return v.success?(lr.emit("event",{directory:"global",payload:{type:Es.Event.Updated.type,properties:{version:E}}}),q.jsonUnsafe(v)):q.jsonUnsafe(v,{status:500})});return t.handle("health",a).handleRaw("event",c).handle("configGet",p).handle("configUpdate",f).handle("dispose",l).handle("upgrade",m)}));var vg=x.group(Q,"instance",t=>s.gen(function*(){let e=yield*zt.Service,r=yield*Zr.Service,n=yield*Io.Service,a=yield*Jr.Service,c=yield*So.Service,p=yield*at.Service,f=s.fn("InstanceHttpApi.dispose")(function*(){return yield*Ka(yield*pe),!0}),l=s.fn("InstanceHttpApi.path")(function*(){let O=yield*pe;return{home:Ki.Path.home,state:Ki.Path.state,config:Ki.Path.config,worktree:O.worktree,directory:O.directory}}),m=s.fn("InstanceHttpApi.vcs")(function*(){let[O,Z]=yield*s.all([p.branch(),p.defaultBranch()],{concurrency:"unbounded"});return{branch:O,default_branch:Z}}),y=s.fn("InstanceHttpApi.vcsStatus")(function*(){return yield*p.status()}),g=s.fn("InstanceHttpApi.vcsDiff")(function*(O){return yield*p.diff(O.query.mode,{context:O.query.context})}),E=s.fn("InstanceHttpApi.vcsDiffRaw")(function*(){return yield*p.diffRaw()}),v=s.fn("InstanceHttpApi.vcsApply")(function*(O){return yield*p.apply(O.payload).pipe(s.mapError(Z=>new Hr({name:"VcsApplyError",data:{message:Z.message,reason:Z.reason}})))}),h=s.fn("InstanceHttpApi.command")(function*(){return yield*r.list()}),w=s.fn("InstanceHttpApi.agent")(function*(){return yield*e.list()}),C=s.fn("InstanceHttpApi.skill")(function*(){return yield*c.all()}),R=s.fn("InstanceHttpApi.lsp")(function*(){return yield*a.status()}),b=s.fn("InstanceHttpApi.formatter")(function*(){return yield*n.status()});return t.handle("dispose",f).handle("path",l).handle("vcs",m).handle("vcsStatus",y).handle("vcsDiff",g).handle("vcsDiffRaw",E).handle("vcsApply",v).handle("command",h).handle("agent",w).handle("skill",C).handle("lsp",R).handle("formatter",b)}));var Eg=x.group(Q,"mcp",t=>s.gen(function*(){let e=yield*qe.Service,r=s.fn("McpHttpApi.status")(function*(){return yield*e.status()}),n=s.fn("McpHttpApi.add")(function*(y){let g=(yield*e.add(y.payload.name,y.payload.config)).status;return yield*o.decodeUnknownEffect(Lp)("status"in g?{[y.payload.name]:g}:g).pipe(s.mapError(()=>new D.BadRequest({})))}),a=s.fn("McpHttpApi.authStart")(function*(y){return yield*s.gen(function*(){return(yield*e.supportsOAuth(y.params.name))?yield*e.startAuth(y.params.name):yield*new Kn({error:`MCP server ${y.params.name} does not support OAuth`})}).pipe(s.catchTag("MCP.NotFoundError",g=>s.fail(new _e({name:g.name,message:`MCP server not found: ${g.name}`}))))}),c=s.fn("McpHttpApi.authCallback")(function*(y){return yield*e.finishAuth(y.params.name,y.payload.code).pipe(s.catchTag("MCP.NotFoundError",g=>s.fail(new _e({name:g.name,message:`MCP server not found: ${g.name}`}))))}),p=s.fn("McpHttpApi.authAuthenticate")(function*(y){return yield*s.gen(function*(){return(yield*e.supportsOAuth(y.params.name))?yield*e.authenticate(y.params.name):yield*new Kn({error:`MCP server ${y.params.name} does not support OAuth`})}).pipe(s.catchTag("MCP.NotFoundError",g=>s.fail(new _e({name:g.name,message:`MCP server not found: ${g.name}`}))))}),f=s.fn("McpHttpApi.authRemove")(function*(y){let g=yield*e.status();return y.params.name in g?(yield*e.removeAuth(y.params.name),{success:!0}):yield*new _e({name:y.params.name,message:`MCP server not found: ${y.params.name}`})}),l=s.fn("McpHttpApi.connect")(function*(y){return yield*e.connect(y.params.name).pipe(s.catchTag("MCP.NotFoundError",g=>s.fail(new _e({name:g.name,message:`MCP server not found: ${g.name}`})))),!0}),m=s.fn("McpHttpApi.disconnect")(function*(y){return yield*e.disconnect(y.params.name).pipe(s.catchTag("MCP.NotFoundError",g=>s.fail(new _e({name:g.name,message:`MCP server not found: ${g.name}`})))),!0});return t.handle("status",r).handle("add",n).handle("authStart",a).handle("authCallback",c).handle("authAuthenticate",p).handle("authRemove",f).handle("connect",l).handle("disconnect",m)}));var Ag=x.group(Q,"permission",t=>s.gen(function*(){let e=yield*Cn.Service,r=s.fn("PermissionHttpApi.list")(function*(){return yield*e.list()}),n=s.fn("PermissionHttpApi.reply")(function*(a){return yield*e.reply({requestID:a.params.requestID,reply:a.payload.reply,message:a.payload.message}).pipe(s.catchTag("Permission.NotFoundError",c=>s.fail(new sr({requestID:String(c.requestID),message:`Permission request not found: ${c.requestID}`})))),!0});return t.handle("list",r).handle("reply",n)}));var Ig=x.group(Q,"project",t=>s.gen(function*(){let e=yield*it.Service,r=yield*Fe.Service,n=s.fn("ProjectHttpApi.list")(function*(){return yield*e.list()}),a=s.fn("ProjectHttpApi.current")(function*(){return(yield*pe).project}),c=s.fn("ProjectHttpApi.initGit")(function*(){let l=yield*pe,m=yield*e.initGit({directory:l.directory,project:l.project});return m.id===l.project.id&&m.vcs===l.project.vcs&&m.worktree===l.project.worktree||(yield*Jy(l,{directory:l.directory,worktree:l.directory,project:m})),m}),p=s.fn("ProjectHttpApi.update")(function*(l){return yield*e.update({...l.payload,projectID:l.params.projectID}).pipe(s.catchTag("Project.NotFoundError",m=>s.fail(new Uo({projectID:m.projectID,message:`Project not found: ${m.projectID}`}))))}),f=s.fn("ProjectHttpApi.directories")(l=>r.directories({projectID:l.params.projectID}));return t.handle("list",n).handle("current",a).handle("initGit",c).handle("update",p).handle("directories",f)}));var wg={name:"project-copy-name",mode:"primary",permission:[],options:{},native:!0,prompt:""},Dg=x.group(Q,"projectCopyName",t=>s.gen(function*(){let e=yield*la.Service,r=yield*Oe.Service,n=s.fn("ProjectCopyHttpApi.generateName")(function*(a){let c=a?.trim();if(!c)return gs.create();let p=yield*r.defaultModel().pipe(s.catch(()=>s.succeed(void 0)));if(!p)return gs.create();let f=(yield*r.getSmallModel(p.providerID))??(yield*r.getModel(p.providerID,p.modelID)),l=Y.descending(),y=(yield*e.stream({agent:wg,user:{id:Kr.ascending(),sessionID:l,role:"user",time:{created:Date.now()},agent:wg.name,model:{providerID:f.providerID,modelID:f.id}},system:[],small:!0,tools:{},model:f,sessionID:l,retries:2,messages:[{role:"user",content:`Generate a short 2-3 word name that describes this task:
19
+ ${c}`}]}).pipe(se.filter(Ou.is.textDelta),se.map(g=>g.text),se.mkString)).trim();return y?SD(y.split(/\s+/).slice(0,3).join(" ")):gs.create()});return t.handle("generateName",a=>n(a.payload.context).pipe(s.catchCause(c=>s.logWarning("project copy name generation failed",{projectID:a.params.projectID,cause:c}).pipe(s.as(gs.create()))),s.map(c=>({name:c}))))}));function SD(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}i(SD,"slugify");function Rg(t){return t.pipe(s.mapError(e=>e instanceof Xe.OauthMissing?new Ut({name:e._tag,data:{providerID:e.providerID}}):e instanceof Xe.OauthCodeMissing?new Ut({name:e._tag,data:{providerID:e.providerID}}):e instanceof Xe.OauthCallbackFailed?new Ut({name:e._tag,data:{}}):e instanceof Xe.ValidationFailed?new Ut({name:e._tag,data:{field:e.field,message:e.message}}):new Ut({name:"BadRequest",data:{}})))}i(Rg,"mapProviderAuthError");var Cg=x.group(Q,"provider",t=>s.gen(function*(){let e=yield*At.Service,r=yield*Oe.Service,n=yield*Xe.Service,a=yield*Gt.Service,c=s.fn("ProviderHttpApi.list")(function*(){let y=yield*e.get(),g=yield*na.Service.use(b=>b.get()),E=new Set(y.disabled_providers??[]),v=y.enabled_providers?new Set(y.enabled_providers):void 0,h={};for(let[b,O]of Object.entries(g))(!v||v.has(b))&&!E.has(b)&&(h[b]=O);let w=yield*r.list(),C=yield*a.all().pipe(s.orDie),R=Object.assign(dm(h,b=>Oe.fromModelsDevProvider(b)),w);return{all:Object.values(R).map(Oe.toPublicInfo),default:Oe.defaultModelIDs(R),connected:Object.keys(R).filter(b=>b in w||C[b])}}),p=s.fn("ProviderHttpApi.auth")(function*(){return yield*n.methods()}),f=s.fn("ProviderHttpApi.authorize")(function*(y){return yield*Rg(n.authorize({providerID:y.params.providerID,method:y.payload.method,inputs:y.payload.inputs}))}),l=s.fn("ProviderHttpApi.authorizeRaw")(function*(y){let g=yield*s.orDie(y.request.text),E=yield*o.decodeUnknownEffect(o.fromJsonString(Xe.AuthorizeInput))(g).pipe(s.mapError(()=>new Ut({name:"BadRequest",data:{}}))),v=yield*f({params:y.params,payload:E});return q.jsonUnsafe(v??null)}),m=s.fn("ProviderHttpApi.callback")(function*(y){return yield*Rg(n.callback({providerID:y.params.providerID,method:y.payload.method,code:y.payload.code})),!0});return t.handle("list",c).handle("auth",p).handleRaw("authorize",l).handle("callback",m)}));var Nt={};me(Nt,{PtyProtocol:()=>Nt,REPLAY_CHUNK:()=>nd,chunks:()=>ID,decodeInput:()=>wD,metaFrame:()=>AD});var vD=new TextEncoder,ED=new TextDecoder("utf-8",{fatal:!0}),nd=64*1024;function AD(t){let e=vD.encode(JSON.stringify({cursor:t})),r=new Uint8Array(e.length+1);return r[0]=0,r.set(e,1),r}i(AD,"metaFrame");function ID(t){let e=[];for(let r=0;r<t.length;r+=nd)e.push(t.slice(r,r+nd));return e}i(ID,"chunks");function wD(t){if(typeof t=="string")return t;try{return ED.decode(t instanceof ArrayBuffer?new Uint8Array(t):t)}catch{return}}i(wD,"decodeInput");function xg(t,e){return Zs(t.headers.origin,t.headers.host,e)}i(xg,"validOrigin");var kg=s.gen(function*(){let t=yield*aa,e=yield*ca;return{directory:t?.directory,workspaceID:e}}),Hg=x.group(Q,"pty",t=>s.gen(function*(){let e=yield*wt.Service,r=yield*Fn,n=yield*wo.Service,a=yield*Ge.Service,c=Mc(h=>s.runPromise(a.invalidate(ce.Ref.make({directory:we.make(h)}))));yield*s.addFinalizer(()=>s.sync(c));let p=s.fnUntraced(function*(h){return yield*h.pipe(s.provide(a.get(ce.Ref.make({directory:we.make((yield*pe).directory)}))))}),f=s.fn("PtyHttpApi.shells")(function*(){return yield*s.promise(()=>sm.list())}),l=s.fn("PtyHttpApi.list")(function*(){return(yield*p(he.Service.use(w=>w.list()))).filter(w=>w.status==="running")}),m=s.fn("PtyHttpApi.create")(function*(h){let w=h.payload.cwd||(yield*pe).directory,C=yield*n.trigger("shell.env",{cwd:w},{env:{}});return yield*p(he.Service.use(R=>R.create({...h.payload,args:h.payload.args?[...h.payload.args]:void 0,cwd:w,env:{...h.payload.env,...C.env}})))}),y=s.fn("PtyHttpApi.get")(function*(h){return yield*p(he.Service.use(w=>w.get(h.params.ptyID))).pipe(s.catchTag("Pty.NotFoundError",w=>new Dt({ptyID:w.ptyID,message:`PTY session not found: ${w.ptyID}`})),s.flatMap(w=>w.status==="running"?s.succeed(w):new Dt({ptyID:h.params.ptyID,message:`PTY session not found: ${h.params.ptyID}`})))}),g=s.fn("PtyHttpApi.update")(function*(h){return yield*y(h),yield*p(he.Service.use(w=>w.update(h.params.ptyID,{...h.payload,size:h.payload.size?{...h.payload.size}:void 0}))).pipe(s.catchTag("Pty.NotFoundError",w=>new Dt({ptyID:w.ptyID,message:`PTY session not found: ${w.ptyID}`})))}),E=s.fn("PtyHttpApi.remove")(function*(h){return yield*y(h),yield*p(he.Service.use(w=>w.remove(h.params.ptyID))).pipe(s.catchTag("Pty.NotFoundError",w=>new Dt({ptyID:w.ptyID,message:`PTY session not found: ${w.ptyID}`}))),!0}),v=s.fn("PtyHttpApi.connectToken")(function*(h){let w=yield*le.HttpServerRequest;return w.headers[nf]!=="1"||!xg(w,r)?yield*new Lo({message:"Invalid PTY connect token request"}):(yield*y(h),yield*e.issue({ptyID:h.params.ptyID,...yield*kg}))});return t.handle("shells",f).handle("list",l).handle("create",m).handle("get",y).handle("update",g).handle("remove",E).handle("connectToken",v)})).pipe(P.provide(Ss)),Pg=x.group(jo,"pty-connect",t=>s.gen(function*(){let e=yield*wt.Service,r=yield*Fn,n=yield*Ge.Service,a=Mc(p=>s.runPromise(n.invalidate(ce.Ref.make({directory:we.make(p)}))));yield*s.addFinalizer(()=>s.sync(a));let c=s.fnUntraced(function*(p){return yield*p.pipe(s.provide(n.get(ce.Ref.make({directory:we.make((yield*pe).directory)}))))});return t.handleRaw("connect",s.fn("PtyHttpApi.connect")(function*(p){if(!(yield*c(he.Service.use(O=>O.get(p.params.ptyID))).pipe(s.map(O=>O.status==="running"),s.catchTag("Pty.NotFoundError",()=>s.succeed(!1)))))return q.empty({status:404});let l=o.decodeUnknownOption(sy)(yield*le.ParsedSearchParams);if(Ce.isNone(l))return q.empty({status:400});let m=new URL(p.request.url,"http://localhost").searchParams.get(ti);if(m&&!(xg(p.request,r)?yield*e.consume({ticket:m,ptyID:p.params.ptyID,...yield*kg}):!1))return q.empty({status:403});let y=l.value.cursor===void 0?void 0:Number(l.value.cursor),g=y!==void 0&&Number.isSafeInteger(y)&&y>=-1?y:void 0,E=yield*s.orDie(p.request.upgrade),v=yield*E.writer,h=i(O=>E.runRaw(()=>s.void,{onOpen:v(O).pipe(s.catch(()=>s.void))}).pipe(s.timeout("1 second"),s.catchReason("SocketError","SocketCloseError",()=>s.void),s.catch(()=>s.void)),"closeAccepted");if(!(yield*$e.register(v($e.SERVER_CLOSING_EVENT()))))return yield*h($e.SERVER_CLOSING_EVENT()),q.empty();let C=yield*Ae.unbounded(),R=yield*c(he.Service.use(O=>O.attach(p.params.ptyID,{cursor:g,onData:i(Z=>Ae.offerUnsafe(C,Z),"onData"),onEnd:i(()=>Ae.offerUnsafe(C,new Le(1e3)),"onEnd")}))).pipe(s.catchTags({"Pty.NotFoundError":i(()=>h(new Le(4404,"session not found")).pipe(s.as(void 0)),"Pty.NotFoundError"),"Pty.ExitedError":i(()=>h(new Le(4404,"session not found")).pipe(s.as(void 0)),"Pty.ExitedError")}));if(!R)return q.empty();for(let O of Nt.chunks(R.replay))Ae.offerUnsafe(C,O);Ae.offerUnsafe(C,Nt.metaFrame(R.cursor)),R.activate();let b=s.gen(function*(){for(;;){let O=yield*Ae.take(C);if(yield*v(O),O instanceof Le)return}});return yield*s.race(b,E.runRaw(O=>{let Z=Nt.decodeInput(O);Z!==void 0&&R.write(Z)})).pipe(s.catchReason("SocketError","SocketCloseError",()=>s.void),s.ensuring(s.sync(()=>R.detach())),s.orDie),q.empty()}))})).pipe(P.provide(Ss));var Tg=x.group(Q,"question",t=>s.gen(function*(){let e=yield*$t.Service,r=s.fn("QuestionHttpApi.list")(function*(){return yield*e.list()}),n=s.fn("QuestionHttpApi.reply")(function*(c){return yield*e.reply({requestID:c.params.requestID,answers:c.payload.answers}).pipe(s.catchTag("Question.NotFoundError",p=>s.fail(new cn({requestID:String(p.requestID),message:`Question request not found: ${p.requestID}`})))),!0}),a=s.fn("QuestionHttpApi.reject")(function*(c){return yield*e.reject(c.params.requestID).pipe(s.catchTag("Question.NotFoundError",p=>s.fail(new cn({requestID:String(p.requestID),message:`Question request not found: ${p.requestID}`})))),!0});return t.handle("list",r).handle("reply",n).handle("reject",a)}));function ir(t){return t.pipe(s.mapError(e=>ja(e.message)))}i(ir,"mapStorageNotFound");function mi(t){return t.pipe(s.catchTag("SessionBusyError",e=>s.fail(new kr({sessionID:e.sessionID,message:`Session is busy: ${e.sessionID}`}))))}i(mi,"mapBusy");var qg=i(t=>s.try({try:i(()=>JSON.parse(t),"try"),catch:i(()=>new D.BadRequest({}),"catch")}),"tryParseJson"),Og=x.group(Q,"session",t=>s.gen(function*(){let e=yield*X.Service,r=yield*Sa.Service,n=yield*Vt.Service,a=yield*Ao.Service,c=yield*fa.Service,p=yield*ma.Service,f=yield*zt.Service,l=yield*Cn.Service,m=yield*Xr.Service,y=yield*vo.Service,g=yield*Eo.Service,E=yield*Wt.Service,v=yield*xt.Scope,h=s.fn("SessionHttpApi.list")(function*(A){let ee=A.query.directory?yield*Ue.directory:void 0;return yield*e.list({directory:A.query.scope==="project"?void 0:ee,scope:A.query.scope,path:A.query.path,roots:A.query.roots,start:A.query.start,search:A.query.search,limit:A.query.limit})}),w=s.fn("SessionHttpApi.status")(function*(){return Object.fromEntries(yield*m.list())}),C=s.fn("SessionHttpApi.requireSession")(function*(A){return yield*ir(e.get(A))}),R=s.fn("SessionHttpApi.get")(function*(A){return yield*C(A.params.sessionID)}),b=s.fn("SessionHttpApi.children")(function*(A){return yield*C(A.params.sessionID),yield*e.children(A.params.sessionID)}),O=s.fn("SessionHttpApi.todo")(function*(A){return yield*C(A.params.sessionID),yield*y.get(A.params.sessionID)}),Z=s.fn("SessionHttpApi.diff")(function*(A){return yield*g.diff({sessionID:A.params.sessionID,messageID:A.query.messageID})}),Se=s.fn("SessionHttpApi.messages")(function*(A){if(A.query.before&&A.query.limit===void 0)return yield*new D.BadRequest({});if(A.query.before){let Ko=A.query.before;yield*s.try({try:i(()=>da.cursor.decode(Ko),"try"),catch:i(()=>new D.BadRequest({}),"catch")})}if(yield*C(A.params.sessionID),A.query.limit===void 0||A.query.limit===0)return yield*ir(e.messages({sessionID:A.params.sessionID}));let ee=yield*ir(da.page({sessionID:A.params.sessionID,limit:A.query.limit,before:A.query.before}));if(!ee.cursor)return ee.items;let br=yield*le.HttpServerRequest,rt=Ce.getOrElse(le.toURL(br),()=>new URL(br.url,"http://localhost"));return rt.searchParams.set("limit",A.query.limit.toString()),rt.searchParams.set("before",ee.cursor),q.jsonUnsafe(ee.items,{headers:{"Access-Control-Expose-Headers":"Link, X-Next-Cursor",Link:`<${rt.toString()}>; rel="next"`,"X-Next-Cursor":ee.cursor}})}),Re=s.fn("SessionHttpApi.message")(function*(A){return yield*ir(da.get({sessionID:A.params.sessionID,messageID:A.params.messageID}))}),ar=s.fn("SessionHttpApi.create")(function*(A){return yield*r.create(A.payload)}),F=s.fn("SessionHttpApi.createRaw")(function*(A){let ee=yield*s.orDie(A.request.text);if(ee.trim().length===0)return yield*ar({});let br=yield*qg(ee),rt=yield*o.decodeUnknownEffect(X.CreateInput)(br).pipe(s.mapError(()=>new D.BadRequest({}))),Ko=rt&&{...rt,permission:rt.permission?[...rt.permission]:void 0};return yield*ar({payload:Ko})}),ue=s.fn("SessionHttpApi.remove")(function*(A){return yield*ir(e.remove(A.params.sessionID)),!0}),ke=s.fn("SessionHttpApi.update")(function*(A){let ee=yield*C(A.params.sessionID);return A.payload.title!==void 0&&(yield*e.setTitle({sessionID:A.params.sessionID,title:A.payload.title})),A.payload.metadata!==void 0&&(yield*e.setMetadata({sessionID:A.params.sessionID,metadata:A.payload.metadata})),A.payload.permission!==void 0&&(yield*e.setPermission({sessionID:A.params.sessionID,permission:Cn.merge(ee.permission??[],A.payload.permission)})),A.payload.time?.archived!==void 0&&(yield*e.setArchived({sessionID:A.params.sessionID,time:A.payload.time.archived})),yield*C(A.params.sessionID)}),ne=s.fn("SessionHttpApi.fork")(function*(A){return yield*ir(e.fork({sessionID:A.params.sessionID,messageID:A.payload?.messageID}))}),Ve=s.fn("SessionHttpApi.forkRaw")(function*(A){let ee=yield*s.orDie(A.request.text);if(ee.trim().length===0)return yield*ne({params:A.params});let br=yield*qg(ee),rt=yield*o.decodeUnknownEffect(Np)(br).pipe(s.mapError(()=>new D.BadRequest({})));return yield*ne({params:A.params,payload:rt})}),nc=s.fn("SessionHttpApi.abort")(function*(A){return yield*n.cancel(A.params.sessionID),!0}),lh=s.fn("SessionHttpApi.init")(function*(A){return yield*C(A.params.sessionID),yield*n.command({sessionID:A.params.sessionID,messageID:A.payload.messageID,model:`${A.payload.providerID}/${A.payload.modelID}`,command:Zr.Default.INIT,arguments:""}).pipe(s.mapError(()=>new D.BadRequest({}))),!0}),fh=s.fn("SessionHttpApi.share")(function*(A){return yield*C(A.params.sessionID),yield*r.share(A.params.sessionID).pipe(s.mapError(()=>new D.InternalServerError({}))),yield*C(A.params.sessionID)}),yh=s.fn("SessionHttpApi.unshare")(function*(A){return yield*C(A.params.sessionID),yield*r.unshare(A.params.sessionID).pipe(s.mapError(()=>new D.InternalServerError({}))),yield*C(A.params.sessionID)}),gh=s.fn("SessionHttpApi.summarize")(function*(A){yield*a.cleanup(yield*C(A.params.sessionID));let ee=yield*ir(e.messages({sessionID:A.params.sessionID})),br=yield*f.defaultAgent(),rt=ee.findLast(Ko=>Ko.info.role==="user")?.info.agent??br;return yield*c.create({sessionID:A.params.sessionID,agent:rt,model:{providerID:A.payload.providerID,modelID:A.payload.modelID},auto:A.payload.auto??!1}),yield*n.loop({sessionID:A.params.sessionID}),!0}),hh=s.fn("SessionHttpApi.prompt")(function*(A){yield*C(A.params.sessionID);let ee=yield*n.prompt({...A.payload,sessionID:A.params.sessionID}).pipe(s.mapError(()=>new D.BadRequest({})));return q.stream(io(JSON.stringify(ee)).pipe(Nr),{contentType:"application/json"})}),Sh=s.fn("SessionHttpApi.promptAsync")(function*(A){return yield*C(A.params.sessionID),yield*n.prompt({...A.payload,sessionID:A.params.sessionID}).pipe(s.catchCause(ee=>s.gen(function*(){yield*s.logError("prompt_async failed",{sessionID:A.params.sessionID,cause:ee}),yield*E.publish(X.Event.Error,{sessionID:A.params.sessionID,error:new ea.Unknown({message:_t.pretty(ee)}).toObject()})})),s.forkIn(v,{startImmediately:!0})),k.NoContent.make()}),vh=s.fn("SessionHttpApi.command")(function*(A){return yield*C(A.params.sessionID),yield*n.command({...A.payload,sessionID:A.params.sessionID}).pipe(s.mapError(()=>new D.BadRequest({})))}),Eh=s.fn("SessionHttpApi.shell")(function*(A){return yield*C(A.params.sessionID),yield*mi(n.shell({...A.payload,sessionID:A.params.sessionID}))}),Ah=s.fn("SessionHttpApi.revert")(function*(A){return yield*C(A.params.sessionID),yield*mi(a.revert({sessionID:A.params.sessionID,...A.payload}))}),Ih=s.fn("SessionHttpApi.unrevert")(function*(A){return yield*C(A.params.sessionID),yield*mi(a.unrevert({sessionID:A.params.sessionID}))}),wh=s.fn("SessionHttpApi.permissionRespond")(function*(A){return yield*C(A.params.sessionID),yield*l.reply({requestID:A.params.permissionID,reply:A.payload.response}).pipe(s.catchTag("Permission.NotFoundError",ee=>s.fail(new sr({requestID:String(ee.requestID),message:`Permission request not found: ${ee.requestID}`})))),!0}),Dh=s.fn("SessionHttpApi.deleteMessage")(function*(A){return yield*C(A.params.sessionID),yield*mi(p.assertNotBusy(A.params.sessionID)),yield*e.removeMessage(A.params),!0}),Rh=s.fn("SessionHttpApi.deletePart")(function*(A){return yield*C(A.params.sessionID),yield*e.removePart(A.params),!0}),Ch=s.fn("SessionHttpApi.updatePart")(function*(A){yield*C(A.params.sessionID);let ee=A.payload;return ee.id!==A.params.partID||ee.messageID!==A.params.messageID||ee.sessionID!==A.params.sessionID?yield*new D.BadRequest({}):yield*e.updatePart(ee)});return t.handle("list",h).handle("status",w).handle("get",R).handle("children",b).handle("todo",O).handle("diff",Z).handle("messages",Se).handle("message",Re).handleRaw("create",F).handle("remove",ue).handle("update",ke).handleRaw("fork",Ve).handle("abort",nc).handle("init",lh).handle("share",fh).handle("unshare",yh).handle("summarize",gh).handle("prompt",hh).handle("promptAsync",Sh).handle("command",vh).handle("shell",Eh).handle("revert",Ah).handle("unrevert",Ih).handle("permissionRespond",wh).handle("deleteMessage",Dh).handle("deletePart",Rh).handle("updatePart",Ch)}));var Mg=x.group(Q,"sync",t=>s.gen(function*(){let e=yield*ye.Service,r=yield*X.Service,n=yield*xt.Scope,a=yield*Wt.Service,{db:c}=yield*jr.Service,p=s.fn("SyncHttpApi.start")(function*(){return yield*e.startWorkspaceSyncing((yield*pe).project.id).pipe(s.ignore,s.forkIn(n)),!0}),f=s.fn("SyncHttpApi.replay")(function*(y){let g=y.payload.events.map(h=>({id:h.id,aggregateID:h.aggregateID,seq:h.seq,type:h.type,data:{...h.data}})),E=g[0].aggregateID;yield*s.logInfo("sync replay requested",{sessionID:E,events:g.length,first:g[0]?.seq,last:g.at(-1)?.seq,directory:y.payload.directory});let v=yield*Lc;return yield*a.replayAll(g,{ownerID:v,strictOwner:!0}),yield*s.logInfo("sync replay complete",{sessionID:E,events:g.length,first:g[0]?.seq,last:g.at(-1)?.seq}),{sessionID:E}}),l=s.fn("SyncHttpApi.steal")(function*(y){let g=yield*Lc;return g?(yield*r.setWorkspace({sessionID:y.payload.sessionID,workspaceID:g}),yield*s.logInfo("sync session stolen",{sessionID:y.payload.sessionID,workspaceID:g}),{sessionID:y.payload.sessionID}):yield*new D.BadRequest({})}),m=s.fn("SyncHttpApi.history")(function*(y){let g=Object.entries(y.payload);return yield*c.select().from(ls).where(g.length>0?Hu(ku(...g.map(([E,v])=>xu(Yi(ls.aggregate_id,E),Pu(ls.seq,v))))):void 0).orderBy(bu(ls.seq)).all().pipe(s.orDie)});return t.handle("start",p).handle("replay",f).handle("steal",l).handle("history",m)}));var RD={session_new:"session.new",session_share:"session.share",session_interrupt:"session.interrupt",session_compact:"session.compact",messages_page_up:"session.page.up",messages_page_down:"session.page.down",messages_line_up:"session.line.up",messages_line_down:"session.line.down",messages_half_page_up:"session.half.page.up",messages_half_page_down:"session.half.page.down",messages_first:"session.first",messages_last:"session.last",agent_cycle:"agent.cycle"},Lg=x.group(Q,"tui",t=>s.gen(function*(){let e=yield*Wt.Service,r=yield*X.Service,n=i(R=>e.publish(ie.CommandExecute,{command:R}),"publishCommand"),a=s.fn("TuiHttpApi.appendPrompt")(function*(R){return yield*e.publish(ie.PromptAppend,R.payload),!0}),c=s.fn("TuiHttpApi.openHelp")(function*(){return yield*n("help.show"),!0}),p=s.fn("TuiHttpApi.openSessions")(function*(){return yield*n("session.list"),!0}),f=s.fn("TuiHttpApi.openThemes")(function*(){return yield*n("session.list"),!0}),l=s.fn("TuiHttpApi.openModels")(function*(){return yield*n("model.list"),!0}),m=s.fn("TuiHttpApi.submitPrompt")(function*(){return yield*n("prompt.submit"),!0}),y=s.fn("TuiHttpApi.clearPrompt")(function*(){return yield*n("prompt.clear"),!0}),g=s.fn("TuiHttpApi.executeCommand")(function*(R){return yield*n(RD[R.payload.command]),!0}),E=s.fn("TuiHttpApi.showToast")(function*(R){return yield*e.publish(ie.ToastShow,R.payload),!0}),v=s.fn("TuiHttpApi.publish")(function*(R){return R.payload.type===ie.PromptAppend.type&&(yield*e.publish(ie.PromptAppend,R.payload.properties)),R.payload.type===ie.CommandExecute.type&&(yield*e.publish(ie.CommandExecute,R.payload.properties)),R.payload.type===ie.ToastShow.type&&(yield*e.publish(ie.ToastShow,R.payload.properties)),R.payload.type===ie.SessionSelect.type&&(yield*e.publish(ie.SessionSelect,R.payload.properties)),!0}),h=s.fn("TuiHttpApi.selectSession")(function*(R){return R.payload.sessionID.startsWith("ses")?(yield*ir(r.get(R.payload.sessionID)),yield*e.publish(ie.SessionSelect,R.payload),!0):yield*new D.BadRequest({})}),w=s.fn("TuiHttpApi.controlNext")(function*(){return yield*s.promise(()=>ly())}),C=s.fn("TuiHttpApi.controlResponse")(function*(R){return fy(R.payload),!0});return t.handle("appendPrompt",a).handle("openHelp",c).handle("openSessions",p).handle("openThemes",f).handle("openModels",l).handle("submitPrompt",m).handle("clearPrompt",y).handle("executeCommand",g).handle("showToast",E).handle("publish",v).handle("selectSession",h).handle("controlNext",w).handle("controlResponse",C)}));var CD=50,xD=o.Struct({id:zu.ID,order:o.Union([o.Literal("asc"),o.Literal("desc")]),direction:o.Union([o.Literal("previous"),o.Literal("next")])}),kD=o.decodeUnknownSync(xD),od={encode(t,e,r){return Buffer.from(JSON.stringify({id:t.id,order:e,direction:r})).toString("base64url")},decode(t){return kD(JSON.parse(Buffer.from(t,"base64url").toString("utf8")))}},Ug=x.group(V,"server.message",t=>s.gen(function*(){let e=yield*Et.Service;return t.handle("session.messages",s.fn(function*(r){if(r.query.cursor&&r.query.order!==void 0)return yield*new Lt({message:"Cursor cannot be combined with order"});let n=yield*s.try({try:i(()=>r.query.cursor?od.decode(r.query.cursor):void 0,"try"),catch:i(()=>new Lt({message:"Invalid cursor"}),"catch")}),a=n?.order??r.query.order??"desc",c=yield*e.messages({sessionID:r.params.sessionID,limit:r.query.limit??CD,order:a,cursor:n?{id:n.id,direction:n.direction}:void 0}).pipe(s.catchTag("Session.NotFoundError",l=>s.fail(new N({sessionID:l.sessionID,message:`Session not found: ${l.sessionID}`}))),s.catchTag("Session.MessageDecodeError",l=>{let m=`err_${crypto.randomUUID().slice(0,8)}`;return s.logError("failed to decode session message").pipe(s.annotateLogs({ref:m,sessionID:l.sessionID,messageID:l.messageID}),s.andThen(s.fail(new tt({message:"Unexpected server error. Check server logs for details.",ref:m}))))})),p=c[0],f=c.at(-1);return{data:c,cursor:{previous:p?od.encode(p,a,"previous"):void 0,next:f?od.encode(f,a,"next"):void 0}}}))}));var Ng=x.group(V,"server.model",t=>s.gen(function*(){return t.handle("model.list",s.fn(function*(){let e=yield*fs.Service;return yield*J(e.model.available())}))}));var _g=x.group(V,"server.provider",t=>s.gen(function*(){return t.handle("provider.list",s.fn(function*(){let e=yield*fs.Service;return yield*J(e.provider.available())})).handle("provider.get",s.fn(function*(e){let n=yield*(yield*fs.Service).provider.get(e.params.providerID);return n?yield*J(s.succeed(n)):yield*new Oo({providerID:e.params.providerID,message:`Provider not found: ${e.params.providerID}`})}))}));var HD=50,PD=50,Bg=x.group(V,"server.session",t=>s.gen(function*(){let e=yield*Et.Service;return t.handle("session.list",s.fn(function*(r){let n=r.query.cursor!==void 0?yield*Zn.parse(r.query.cursor).pipe(s.mapError(()=>new Lt({message:"Invalid cursor"}))):r.query,a=yield*e.list({...n,workspaceID:n.workspace,limit:r.query.limit??HD}),c=a[0],p=a.at(-1);return{data:a,cursor:{previous:c?Zn.make({...n,anchor:{id:c.id,time:ns.toEpochMillis(c.time.created),direction:"previous"}}):void 0,next:p?Zn.make({...n,anchor:{id:p.id,time:ns.toEpochMillis(p.time.created),direction:"next"}}):void 0}}})).handle("session.create",s.fn(function*(r){return{data:yield*e.create({id:r.payload.id,agent:r.payload.agent,model:r.payload.model,location:r.payload.location??{directory:we.make(process.cwd())}})}})).handle("session.active",s.fn(function*(){return{data:Object.fromEntries(Array.from(yield*e.active,r=>[r,{type:"running"}]))}})).handle("session.get",s.fn(function*(r){return{data:yield*e.get(r.params.sessionID).pipe(s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})))}})).handle("session.switchAgent",s.fn(function*(r){return yield*e.switchAgent({sessionID:r.params.sessionID,agent:r.payload.agent}).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})))),k.NoContent.make()})).handle("session.switchModel",s.fn(function*(r){return yield*e.switchModel({sessionID:r.params.sessionID,model:r.payload.model}).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})))),k.NoContent.make()})).handle("session.prompt",s.fn(function*(r){return{data:yield*e.prompt({sessionID:r.params.sessionID,id:r.payload.id,prompt:r.payload.prompt,delivery:r.payload.delivery,resume:r.payload.resume}).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`}))),s.catchTag("Session.PromptConflictError",n=>s.fail(new qo({message:`Prompt message ID conflicts with an existing durable record: ${n.messageID}`,resource:n.messageID}))))}})).handle("session.compact",s.fn(function*(r){return yield*e.compact({sessionID:r.params.sessionID}).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`}))),s.catchTag("Session.OperationUnavailableError",n=>s.fail(new mt({message:`Session ${n.operation} is not available yet`,service:`session.${n.operation}`})))),k.NoContent.make()})).handle("session.wait",s.fn(function*(r){return yield*e.wait(r.params.sessionID).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`}))),s.catchTag("Session.OperationUnavailableError",n=>s.fail(new mt({message:`Session ${n.operation} is not available yet`,service:`session.${n.operation}`})))),k.NoContent.make()})).handle("session.revert.stage",s.fn(function*(r){return{data:yield*e.revert.stage({...r.params,...r.payload}).pipe(s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})),s.catchTag("Session.MessageNotFoundError",n=>new an({sessionID:n.sessionID,messageID:n.messageID,message:`Message not found: ${n.messageID}`})),s.catchTag("Snapshot.Error",n=>{let a=`err_${crypto.randomUUID().slice(0,8)}`;return s.logError("failed to stage session revert",{cause:n}).pipe(s.andThen(s.fail(new tt({message:"Unexpected server error. Check server logs for details.",ref:a}))))}))}})).handle("session.revert.clear",s.fn(function*(r){return yield*e.revert.clear(r.params.sessionID).pipe(s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})),s.catchTag("Snapshot.Error",n=>{let a=`err_${crypto.randomUUID().slice(0,8)}`;return s.logError("failed to clear session revert",{cause:n}).pipe(s.andThen(s.fail(new tt({message:"Unexpected server error. Check server logs for details.",ref:a}))))})),k.NoContent.make()})).handle("session.revert.commit",s.fn(function*(r){return yield*e.revert.commit(r.params.sessionID).pipe(s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`}))),k.NoContent.make()})).handle("session.context",s.fn(function*(r){return{data:yield*e.context(r.params.sessionID).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`}))),s.catchTag("Session.MessageDecodeError",n=>{let a=`err_${crypto.randomUUID().slice(0,8)}`;return s.logError("failed to decode session message").pipe(s.annotateLogs({ref:a,sessionID:n.sessionID,messageID:n.messageID}),s.andThen(s.fail(new tt({message:"Unexpected server error. Check server logs for details.",ref:a}))))}))}})).handle("session.history",s.fn(function*(r){return yield*e.history({sessionID:r.params.sessionID,after:r.query.after,limit:r.query.limit??PD}).pipe(s.map(n=>({data:n.events,hasMore:n.hasMore})),s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})))})).handle("session.events",s.fn(r=>s.succeed(e.events({sessionID:r.params.sessionID,after:r.query.after}).pipe(se.orDie)))).handle("session.interrupt",s.fn(function*(r){return yield*e.interrupt(r.params.sessionID),k.NoContent.make()})).handle("session.message",s.fn(function*(r){let n=yield*e.message(r.params);return n?{data:n}:yield*new an({sessionID:r.params.sessionID,messageID:r.params.messageID,message:`Message not found: ${r.params.messageID}`})}))}));function sd(t){return new Wn({requestID:t,message:`Permission request not found: ${t}`})}i(sd,"missingRequest");var Fg=x.group(V,"server.permission",t=>s.gen(function*(){return t.handle("permission.request.list",s.fn(function*(){return yield*J((yield*fo.Service).list())})).handle("session.permission.create",s.fn(function*(e){return{data:yield*(yield*fo.Service).ask({id:e.payload.id,sessionID:e.params.sessionID,action:e.payload.action,resources:e.payload.resources,save:e.payload.save,metadata:e.payload.metadata,source:e.payload.source,agent:e.payload.agent}).pipe(s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})))}})).handle("session.permission.list",s.fn(function*(e){return{data:yield*(yield*fo.Service).forSession(e.params.sessionID)}})).handle("session.permission.get",s.fn(function*(e){let r=yield*(yield*fo.Service).get(e.params.requestID);return!r||r.sessionID!==e.params.sessionID?yield*sd(e.params.requestID):{data:r}})).handle("session.permission.reply",s.fn(function*(e){let r=yield*fo.Service,n=yield*r.get(e.params.requestID);return!n||n.sessionID!==e.params.sessionID?yield*sd(e.params.requestID):(yield*r.reply({requestID:e.params.requestID,reply:e.payload.reply,message:e.payload.message}).pipe(s.catchTag("PermissionV2.NotFoundError",()=>sd(e.params.requestID))),k.NoContent.make())})).handle("permission.saved.list",s.fn(function*(e){let r=yield*ce.Service;return{data:yield*(yield*hs.Service).list({projectID:e.query.projectID??r.project.id})}})).handle("permission.saved.remove",s.fn(function*(e){return yield*(yield*hs.Service).remove(e.params.id),k.NoContent.make()}))}));var jg=x.group(V,"server.fs",t=>s.gen(function*(){return t.handleRaw("fs.read",e=>s.gen(function*(){let r=yield*(yield*$r.Service).read({path:vt.make(decodeURIComponent(new URL(e.request.url,"http://localhost").pathname.slice(13)))});return q.uint8Array(r.content,{contentType:r.mime})})).handle("fs.list",e=>J(s.gen(function*(){return yield*(yield*$r.Service).list(e.query)}))).handle("fs.find",e=>J(s.gen(function*(){return yield*(yield*$r.Service).find(e.query)})))}));var Gg=x.group(V,"server.command",t=>t.handle("command.list",()=>J(Fu.Service.use(e=>e.list()))));var Wg=x.group(V,"server.skill",t=>t.handle("skill.list",()=>J(ra.Service.use(e=>e.list()))));var TD=256;function bD(t){return{_tag:"Event",event:"message",id:void 0,data:JSON.stringify(o.encodeUnknownSync(Ty)(t))}}i(bD,"eventData");var $g=x.group(V,"server.event",t=>s.gen(function*(){let e=yield*fe.Service;return t.handleRaw("event.subscribe",()=>s.gen(function*(){let r={id:fe.ID.create(),type:"server.connected",data:{}},n=se.unwrap(s.gen(function*(){let c=yield*fe.allBounded(e,TD);return se.make(r).pipe(se.concat(c))})).pipe(se.map(bD),se.pipeThroughChannel(po())),a=se.tick("15 seconds").pipe(se.map(()=>`: heartbeat
20
+
21
+ `));return q.stream(n.pipe(se.merge(a,{haltStrategy:"left"}),se.encodeText),{contentType:"text/event-stream",headers:{"Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no","X-Content-Type-Options":"nosniff"}})}))}));var Vg=x.group(V,"server.agent",t=>t.handle("agent.list",()=>s.gen(function*(){return yield*J(Ru.Service.use(e=>e.all()))})));var zg=x.group(V,"server.health",t=>t.handle("health.get",()=>s.succeed({healthy:!0})));var Qg=s.gen(function*(){let t=yield*ce.Service;return{directory:t.directory,workspaceID:t.workspaceID}}),Yg=x.group(V,"server.pty",t=>s.gen(function*(){let e=yield*wt.Service,r=yield*Fn,n=yield*nr.Service;return t.handle("pty.list",s.fn(function*(){return yield*J((yield*he.Service).list())})).handle("pty.create",s.fn(function*(a){let c=yield*he.Service,p=yield*ce.Service,f=a.payload.cwd||p.directory;return yield*J(c.create({...a.payload,args:a.payload.args?[...a.payload.args]:void 0,cwd:f,env:{...a.payload.env,...yield*n.get({directory:p.directory,cwd:f})}}))})).handle("pty.get",s.fn(function*(a){let c=yield*he.Service;return yield*J(c.get(a.params.ptyID).pipe(s.catchTag("Pty.NotFoundError",()=>new lt({ptyID:a.params.ptyID,message:`PTY session not found: ${a.params.ptyID}`}))))})).handle("pty.update",s.fn(function*(a){let c=yield*he.Service;return yield*J(c.update(a.params.ptyID,{...a.payload,size:a.payload.size?{...a.payload.size}:void 0}).pipe(s.catchTag("Pty.NotFoundError",()=>new lt({ptyID:a.params.ptyID,message:`PTY session not found: ${a.params.ptyID}`}))))})).handle("pty.remove",s.fn(function*(a){return yield*(yield*he.Service).remove(a.params.ptyID).pipe(s.catchTag("Pty.NotFoundError",()=>new lt({ptyID:a.params.ptyID,message:`PTY session not found: ${a.params.ptyID}`}))),k.NoContent.make()})).handle("pty.connectToken",s.fn(function*(a){let c=yield*le.HttpServerRequest;return c.headers[pf]!==df||!Zs(c.headers.origin,c.headers.host,r)?yield*new Vn({message:"Invalid PTY connect token request"}):(yield*(yield*he.Service).get(a.params.ptyID).pipe(s.catchTag("Pty.NotFoundError",()=>new lt({ptyID:a.params.ptyID,message:`PTY session not found: ${a.params.ptyID}`}))),yield*J(e.issue({ptyID:a.params.ptyID,...yield*Qg})))})).handleRaw("pty.connect",s.fn("PtyHandler.connect")(function*(a){let c=yield*he.Service;if(!(yield*c.get(a.params.ptyID).pipe(s.as(!0),s.catchTag("Pty.NotFoundError",()=>s.succeed(!1)))))return q.empty({status:404});let f=new URL(a.request.url,"http://localhost"),l=f.searchParams.get(Fa);if(l&&!(Zs(a.request.headers.origin,a.request.headers.host,r)?yield*e.consume({ticket:l,ptyID:a.params.ptyID,...yield*Qg}):!1))return q.empty({status:403});let m=f.searchParams.get("cursor"),y=m===null?void 0:Number(m),g=y!==void 0&&Number.isSafeInteger(y)&&y>=-1?y:void 0,E=yield*s.orDie(a.request.upgrade),v=yield*E.writer,h=i(b=>E.runRaw(()=>s.void,{onOpen:v(b).pipe(s.catch(()=>s.void))}).pipe(s.timeout("1 second"),s.catchReason("SocketError","SocketCloseError",()=>s.void),s.catch(()=>s.void)),"closeAccepted"),w=yield*Ae.unbounded(),C=yield*c.attach(a.params.ptyID,{cursor:g,onData:i(b=>Ae.offerUnsafe(w,b),"onData"),onEnd:i(()=>Ae.offerUnsafe(w,new Le(1e3)),"onEnd")}).pipe(s.catchTags({"Pty.NotFoundError":i(()=>h(new Le(4404,"session not found")).pipe(s.as(void 0)),"Pty.NotFoundError"),"Pty.ExitedError":i(()=>h(new Le(4404,"session exited")).pipe(s.as(void 0)),"Pty.ExitedError")}));if(!C)return q.empty();for(let b of Nt.chunks(C.replay))Ae.offerUnsafe(w,b);Ae.offerUnsafe(w,Nt.metaFrame(C.cursor)),C.activate();let R=s.gen(function*(){for(;;){let b=yield*Ae.take(w);if(yield*v(b),b instanceof Le)return}});return yield*s.race(R,E.runRaw(b=>{let O=Nt.decodeInput(b);O!==void 0&&C.write(O)})).pipe(s.catchReason("SocketError","SocketCloseError",()=>s.void),s.ensuring(s.sync(()=>C.detach())),s.orDie),q.empty()}))}));function id(t){return new $n({requestID:t,message:`Question request not found: ${t}`})}i(id,"missingRequest");var Kg=x.group(V,"server.question",t=>s.gen(function*(){let e=s.fnUntraced(function*(r,n,a){let c=yield*sa.Service,p=(yield*c.list()).find(f=>f.id===n);return!p||p.sessionID!==r?yield*id(n):yield*a(c)});return t.handle("question.request.list",s.fn(function*(){return yield*J((yield*sa.Service).list())})).handle("session.question.list",s.fn(function*(r){return{data:(yield*(yield*sa.Service).list()).filter(a=>a.sessionID===r.params.sessionID)}})).handle("session.question.reply",s.fn(function*(r){return yield*e(r.params.sessionID,r.params.requestID,n=>n.reply({requestID:r.params.requestID,answers:r.payload.answers}).pipe(s.catchTag("QuestionV2.NotFoundError",()=>id(r.params.requestID)))),k.NoContent.make()})).handle("session.question.reject",s.fn(function*(r){return yield*e(r.params.sessionID,r.params.requestID,n=>n.reject(r.params.requestID).pipe(s.catchTag("QuestionV2.NotFoundError",()=>id(r.params.requestID)))),k.NoContent.make()}))}));var Xg=x.group(V,"server.reference",t=>t.handle("reference.list",()=>J(Ju.Service.use(e=>e.list()))));var Jg=x.group(V,"server.location",t=>t.handle("location.get",s.fn(function*(){let e=yield*ce.Service;return new ce.Info({directory:e.directory,workspaceID:e.workspaceID,project:e.project})})));var Zg=i(t=>t.pipe(s.mapError(()=>new Pe({message:"Authentication failed",kind:"integration_authorization"}))),"authorize"),eh=x.group(V,"server.integration",t=>s.gen(function*(){return t.handle("integration.list",s.fn(function*(){let e=yield*je.Service;return yield*J(e.list())})).handle("integration.get",s.fn(function*(e){let r=yield*je.Service;return yield*J(r.get(e.params.integrationID))})).handle("integration.connect.key",s.fn(function*(e){let r=yield*je.Service;return yield*Zg(r.connection.key({integrationID:e.params.integrationID,key:e.payload.key,label:e.payload.label})),k.NoContent.make()})).handle("integration.connect.oauth",s.fn(function*(e){let r=yield*je.Service;return yield*J(Zg(r.connection.oauth({integrationID:e.params.integrationID,methodID:e.payload.methodID,inputs:e.payload.inputs,label:e.payload.label})))})).handle("integration.attempt.status",s.fn(function*(e){let r=yield*je.Service;return yield*J(r.attempt.status(e.params.attemptID))})).handle("integration.attempt.complete",s.fn(function*(e){return yield*(yield*je.Service).attempt.complete({attemptID:e.params.attemptID,code:e.payload.code}).pipe(s.mapError(n=>new Pe({message:n._tag==="Integration.CodeRequired"?"Authorization code is required":"Authentication failed",kind:n._tag==="Integration.CodeRequired"?"integration_code_required":"integration_authorization"}))),k.NoContent.make()})).handle("integration.attempt.cancel",s.fn(function*(e){return yield*(yield*je.Service).attempt.cancel(e.params.attemptID),k.NoContent.make()}))}));var th=x.group(V,"server.credential",t=>t.handle("credential.update",s.fn(function*(e){return yield*(yield*je.Service).connection.update(e.params.credentialID,{label:e.payload.label}),k.NoContent.make()})).handle("credential.remove",s.fn(function*(e){return yield*(yield*je.Service).connection.remove(e.params.credentialID),k.NoContent.make()})));var rh=x.group(V,"server.projectCopy",t=>s.succeed(t.handle("projectCopy.create",e=>s.gen(function*(){let r=yield*Pt.Service,n=yield*ce.Service;return yield*ad(r.create({...e.payload,projectID:e.params.projectID,sourceDirectory:n.project.directory}))})).handle("projectCopy.remove",e=>Pt.Service.use(r=>ad(r.remove({...e.payload,projectID:e.params.projectID})).pipe(s.as(k.NoContent.make())))).handle("projectCopy.refresh",e=>Pt.Service.use(r=>ad(r.refresh({projectID:e.params.projectID})).pipe(s.as(k.NoContent.make()))))));function ad(t){return t.pipe(s.mapError(e=>new eo({name:"ProjectCopyError",data:{message:qD(e),forceRequired:e instanceof uo.WorktreeError?e.forceRequired:void 0}})))}i(ad,"badRequest");function qD(t){return t instanceof Pt.SourceDirectoryNotFoundError?`Project copy source not found: ${t.directory}`:t instanceof Pt.DestinationExistsError?`Project copy destination already exists: ${t.directory}`:t instanceof Pt.DirectoryUnavailableError?`Project copy directory unavailable: ${t.directory}`:t instanceof Pt.InvalidDirectoryError?`Invalid project copy directory: ${t.directory}`:t instanceof Pt.StrategyUnavailableError?`Project copy strategy unavailable: ${t.strategy}`:t.message}i(qD,"message");var nh=P.mergeAll(zg,Jg,Vg,Bg,Ug,Ng,_g,eh,th,Fg,jg,Gg,Wg,$g,Yg,Kg,Xg,rh);var cd=1024;function OD(t){return t.length<=cd?t:t.slice(0,cd)+`... (${t.length-cd} more chars)`}i(OD,"truncateReason");var oh=ge.layerSchemaErrorTransform(Jn,t=>{let e=OD(t.cause.message);return s.logWarning("schema rejection").pipe(s.annotateLogs({kind:t.kind,reason:e}),s.andThen(s.fail(new Pe({message:e,kind:t.kind}))))});var sh=x.group(Q,"workspace",t=>s.gen(function*(){let e=yield*ye.Service,r=s.fn("WorkspaceHttpApi.adapters")(function*(){let m=yield*pe;return yield*s.sync(()=>qm(m.project.id))}),n=s.fn("WorkspaceHttpApi.list")(function*(){return yield*e.list((yield*pe).project)}),a=s.fn("WorkspaceHttpApi.create")(function*(m){let y=yield*pe;return yield*e.create({...m.payload,extra:m.payload.extra??null,projectID:y.project.id}).pipe(s.catchCause(g=>{let E=g.reasons.find(_t.isDieReason),v=g.reasons.find(_t.isFailReason),h=E?.defect??v?.error,w=h instanceof Error?h.message:"Workspace creation failed";return s.fail(new pi({name:"WorkspaceCreateError",data:{message:w}}))}))}),c=s.fn("WorkspaceHttpApi.syncList")(function*(){yield*e.syncList((yield*pe).project)}),p=s.fn("WorkspaceHttpApi.status")(function*(){let m=new Set((yield*e.list((yield*pe).project)).map(y=>y.id));return(yield*e.status()).filter(y=>m.has(y.workspaceID))}),f=s.fn("WorkspaceHttpApi.remove")(function*(m){return yield*e.remove(m.params.id)}),l=s.fn("WorkspaceHttpApi.warp")(function*(m){yield*e.sessionWarp({workspaceID:m.payload.id,sessionID:m.payload.sessionID,copyChanges:m.payload.copyChanges}).pipe(s.mapError(y=>y instanceof ye.WorkspaceNotFoundError?ja(y.message):y instanceof at.PatchApplyError?new Hr({name:"VcsApplyError",data:{message:y.message,reason:y.reason}}):new ci({name:"WorkspaceWarpError",data:{message:y.message}})))});return t.handle("adapters",r).handle("list",n).handle("create",a).handle("syncList",c).handle("status",p).handle("remove",f).handle("warp",l)}));import{deflateSync as MD,gzipSync as LD}from"node:zlib";var UD=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,ND=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,_D=new Set(["/event","/global/event"]),BD=/^\/session\/[^/]+\/(?:message|prompt_async)$/,FD=1024;function jD(t){if(!t)return;let e=t.toLowerCase();if(e.includes("gzip"))return"gzip";if(e.includes("deflate"))return"deflate"}i(jD,"pickEncoding");function GD(t){let e=t.indexOf("?");return e===-1?t:t.slice(0,e)}i(GD,"pathOf");var ih=Ee.middleware()(t=>s.gen(function*(){let e=yield*t,r=yield*le.HttpServerRequest;if(r.method==="HEAD"||e.headers["content-encoding"]||e.headers["transfer-encoding"])return e;let n=e.body;if(n._tag!=="Uint8Array"||n.body.byteLength<FD)return e;let a=e.headers["cache-control"];if(a&&ND.test(a))return e;let c=GD(r.url);if(_D.has(c)||r.method==="POST"&&BD.test(c))return e;let p=n.contentType;if(!UD.test(p))return e;let f=jD(r.headers["accept-encoding"]);if(!f)return e;let l=f==="gzip"?LD(n.body):MD(n.body);return q.setHeader(q.setBody(e,ur.uint8Array(l,p)),"content-encoding",f)})).layer;var ah=Ee.middleware(t=>s.gen(function*(){let e=yield*t,r=e.headers["access-control-allow-origin"];if(!r||r==="*")return e;let n=e.headers.vary;if(!n)return q.setHeader(e,"vary","Origin");let a=n.split(",").map(c=>c.trim().toLowerCase());return a.includes("origin")||a.includes("*")?e:q.setHeader(e,"vary",`${n}, Origin`)}),{global:!0});var ch=Ee.middleware()(t=>t.pipe(s.catchCause(e=>{let r=e.reasons.filter(_t.isDieReason).find(c=>!(q.isHttpServerResponse(c.defect)||au.isHttpServerError(c.defect)||Cc.isRespondable(c.defect)));if(!r)return s.failCause(e);let n=r.defect;if(go.JsonError.isInstance(n)||go.InvalidError.isInstance(n)||go.FrontmatterError.isInstance(n)||go.DirectoryTypoError.isInstance(n)||go.RemoteAuthError.isInstance(n))return s.succeed(q.jsonUnsafe(n.toObject(),{status:400}));let a=`err_${crypto.randomUUID().slice(0,8)}`;return s.logError("failed",{ref:a,error:n,cause:_t.pretty(e)}).pipe(s.as(q.jsonUnsafe(new ea.Unknown({message:"Unexpected server error. Check server logs for details.",ref:a}).toObject(),{status:500})))}))).layer;var WD=new Set(["GET","HEAD","OPTIONS"]),ph=Ee.middleware()(s.gen(function*(){let{db:t}=yield*jr.Service;return e=>s.gen(function*(){let r=yield*le.HttpServerRequest;if(!ms.OPENCODE_WORKSPACE_ID||WD.has(r.method))return yield*e;let n=yield*qp(t),a=yield*e,c=Af(n,yield*qp(t));return Object.keys(c).length===0?a:q.setHeader(a,bp,JSON.stringify(c))})})).layer;var $D=oe.makeUnsafe(new Map),VD=i(t=>Ee.middleware(yu.cors({allowedOrigins:i(e=>Dp(e,t),"allowedOrigins"),maxAge:86400}),{global:!0}),"cors"),dh=hf.layer.pipe(P.provide(Ne.Config.layer)),pd=Sf.pipe(P.provide(Ne.Config.layer)),zD=vf.pipe(P.provide(Ne.Config.layer)),QD=Hp.pipe(P.provide(Ne.Config.layer)),dd=Gf.pipe(P.provide(pu)),YD=x.layer(Pr).pipe(P.provide([og,sg,Sg]),P.provide(jp),P.provide(pd)),KD=x.layer(Bo).pipe(P.provide(Ky),P.provide([pd,dd,Ga])),XD=x.layer(jo).pipe(P.provide(Pg),P.provide([zD,dd,Ga])),JD=x.layer(Q).pipe(P.provide([ng,Zy,ig,hg,vg,Eg,Ig,Dg,Hg,Tg,Ag,Cg,Og,Mg,Lg,sh])),ZD=JD.pipe(P.provide([pd,dd,Ga,jp])),eR=x.layer(V).pipe(P.provide(nh),P.provide(zs.layer),P.provide([QD,oh])),tR=Js(()=>q.jsonUnsafe(d.fromApi(Ya))),rR=Ee.use(t=>t.add("GET","/doc",()=>s.succeed(tR()))).pipe(P.provide(dh)),nR=Ee.use(t=>s.gen(function*(){let e=yield*mr.Service,r=yield*Bi.HttpClient,n=yield*vs.Service;yield*t.add("*","/*",a=>Xl(a,{fs:e,client:r,disableEmbeddedWebUi:n.disableEmbeddedWebUi}))})).pipe(P.provide(dh)),oR=zi.group([rm.node,mr.node,jr.node,Gt.node,ia.node,At.node,um.node,mm.node,Zi.node,fm.node,ua.node,wo.node,na.node,Oe.node,Xe.node,zt.node,So.node,gm.node,$t.node,Cn.node,hs.node,vo.node,X.node,Yu.node,Xr.node,pa.node,vs.node,Wt.node,ma.node,Am.node,fa.node,Ao.node,Eo.node,Vt.node,wm.node,la.node,Jr.node,qe.node,vm.node,Zr.node,Dm.node,ya.node,Io.node,it.node,at.node,ye.node,fr.node,Es.node,Pm.node,Sa.node,It.node,Lu,fe.node,Fe.node,Pt.node,wt.node]);function uh(t){let e=im();return P.mergeAll(YD,KD,XD,ZD,eR,rR,nR).pipe(P.provide([ch,ih,ah,ph,VD(t),ha.build(Mt.node,[[Ge.node,e]]),$i.layerServices]),P.provide(P.succeed(Fn)(t)),P.provide(Gy),P.provide(jy),P.provide(nr.layer),P.provide(ha.build(Et.node,[[Ge.node,e],[lo.node,Vl]])),P.provide(e),P.provide(ha.build(oR)),P.provideMerge(tm))}i(uh,"createRoutes");var mh=uh(),sR=Js(()=>Ee.toWebHandler(mh,{disableLogger:!0,memoMap:em,middleware:Xa}));globalThis.AI_SDK_LOG_WARNINGS=!1;var li=class extends oe.Service()("@opencode/ListenerServer"){static{i(this,"ListenerServerService")}},aR=Js(()=>{let t=yn.webHandler().handler,e={fetch:i(r=>t(r,yn.context),"fetch"),request(r,n){return e.fetch(r instanceof Request?r:new Request(new URL(r,"http://localhost"),n))}};return{app:e}});async function cR(){return d.fromApi(Ya)}i(cR,"openapi");var rc;async function pR(t){let e=await s.runPromise(dR(t));return{hostname:e.hostname,port:e.port,url:e.url,stop:i(r=>s.runPromiseExit(e.stop(r)).then(()=>{}),"stop")}}i(pR,"listen");var dR=s.fn("Server.listen")(function*(t){let e=yield*mR(t),r=yield*lR(e),n=fR(t.hostname,r.port),a=yield*yR(t,r.port,e.scope);return rc=n,{hostname:t.hostname,port:r.port,url:n,stop:yield*gR(e,a,n)}});function uR(t,e){return Ee.serve(yn.createRoutes(t),{middleware:Xa,disableLogger:!0,disableListenLog:!0}).pipe(P.provideMerge(am.build($e.node)),P.provideMerge(SR({port:e,hostname:t.hostname})),P.provide(Hc.layer(Hc.fromEnv())))}i(uR,"listenerLayer");function mR(t){return t.port!==0?ud(t,t.port):ud(t,4096).pipe(s.catch(()=>ud(t,0)))}i(mR,"startWithPortFallback");function ud(t,e){let r=xt.makeUnsafe();return P.buildWithMemoMap(uR(t,e),P.makeMemoMapUnsafe(),r).pipe(s.provide(yn.context),s.onError(()=>xt.close(r,ro.void).pipe(s.ignore)),s.map(n=>({scope:r,server:oe.get(n,$i.HttpServer),http:oe.get(n,li),websockets:oe.get(n,$e.Service)})))}i(ud,"startListener");function lR(t){return s.gen(function*(){return t.server.address._tag==="TcpAddress"?t.server.address:(yield*xt.close(t.scope,ro.void).pipe(s.ignore),yield*s.die(new Error(`Unexpected HttpServer address tag: ${t.server.address._tag}`)))})}i(lR,"tcpAddress");function fR(t,e){let r=new URL("http://localhost");return r.hostname=t,r.port=String(e),r}i(fR,"makeURL");function yR(t,e,r){return s.gen(function*(){if(t.mdns&&e&&t.hostname!=="127.0.0.1"&&t.hostname!=="localhost"&&t.hostname!=="::1"){let a=yield*s.cached(s.sync(()=>ko.unpublish()));return yield*s.sync(()=>ko.publish(e,t.mdnsDomain)),yield*xt.addFinalizer(r,a),a}return t.mdns&&(yield*s.logWarning("mDNS enabled but hostname is loopback; skipping mDNS publish")),s.void})}i(yR,"setupMdns");function gR(t,e,r){return s.gen(function*(){let n=yield*s.cached(hR(t).pipe(s.ignore)),a=yield*s.cached(xt.close(t.scope,ro.void).pipe(s.ignore,s.ensuring(s.sync(()=>{rc===r&&(rc=void 0)}))));return c=>s.gen(function*(){yield*e,c&&(yield*n),yield*a})})}i(gR,"makeStop");function hR(t){return s.all([t.http.closeAll,t.websockets.closeAll],{concurrency:"unbounded",discard:!0})}i(hR,"forceClose");function SR(t){let e=iR(),r={closeStarted:!1,forceStop:!1},n=e.close.bind(e);return e.close=(a=>{r.closeStarted=!0;let c=n(a);return r.forceStop&&e.closeAllConnections(),c}),P.mergeAll(Au.layer(()=>e,{port:t.port,host:t.hostname,gracefulShutdownTimeout:"1 second"}),P.succeed(li)(li.of({closeAll:s.sync(()=>{r.forceStop=!0,r.closeStarted&&e.closeAllConnections()})})))}i(SR,"serverLayer");export{aR as Default,md as Server,pR as listen,cR as openapi,rc as url};