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,780 @@
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 vy}from"./chunk-WZ4237YY.js";import{c as MA,d as PA,e as NA,f as py,g as LA,h as FA,q as jA,t as UA}from"./chunk-NDI67DRG.js";import{a as X,b as Te,c as ld,d as rn,e as my,f as Pn,h as Nn,m as ze,n as oo,o as cd,p as $i,r as yy}from"./chunk-WKZYINC7.js";import{a as re}from"./chunk-Q3WIUQXB.js";import{A as u,c as gy,e as hy}from"./chunk-WPMP2ZFE.js";import{$a as br,$b as G,$d as ty,Aa as Pi,Ac as sA,Ad as kh,Ae as Bi,Bb as tt,Bc as iA,Bd as Rh,Cc as aA,Cd as Ch,Da as Qg,Db as uh,Dc as lA,Dd as Dh,Ea as hl,Eb as dh,Ec as cA,Ed as Oh,Fa as yl,Fb as ph,Fc as uA,Fd as Mh,Gb as Xu,Gc as dA,Gd as Ph,Hb as Fi,Hc as pA,Hd as Nh,Ic as fA,Id as Lh,Ja as eh,Jc as mA,Jd as Fh,Ka as th,Kb as Zu,Kc as gA,Kd as jh,La as fs,Lb as gs,Lc as hA,Ld as Uh,Ma as Lr,Mb as Qu,Mc as yA,Md as qh,Nb as bl,Nc as vA,Nd as Bh,Oa as An,Ob as ed,Oc as SA,Od as $h,Pa as F,Pb as ji,Pc as wA,Pd as Vh,Qa as rh,Qb as hs,Qc as xA,Qd as Hh,Ra as ye,Rb as ro,Rc as bA,Rd as Wh,Sa as kn,Sb as ce,Sc as hh,Sd as Gh,Tb as yt,Tc as _l,Td as Jh,Ua as Kt,Ud as zh,Va as nh,Vc as On,Vd as Kh,Wa as vl,Wb as ys,Wc as yh,Wd as Yh,Xa as oh,Xb as Er,Xc as vh,Xd as Xh,Yb as ve,Yc as Sh,Yd as Zh,Za as Ni,Zb as td,Zc as tn,Zd as Qh,_a as sh,_b as fh,_c as vs,_d as ey,ab as Xr,ac as Cn,ae as ry,bb as qe,bc as Ui,bd as Mn,be as ny,c as Cg,cb as ih,cd as no,ce as oy,d as Og,db as z,dc as El,dd as wh,e as Mg,ea as Jg,eb as Ut,ec as Il,ed as oe,ee as sy,f as Pg,fa as zg,fb as Sl,fc as mh,gb as dr,gc as Qr,ge as ut,h as Ng,ha as Ue,hb as wl,hc as qi,hd as sd,i as Hu,ia as Pr,ib as xl,id as EA,ja as ds,jc as en,jd as IA,k as ul,ka as fl,kc as gh,kd as TA,ke as Al,l as dl,la as Yr,lb as Ee,ld as _A,le as id,ma as zt,mb as Fe,mc as Tl,md as AA,me as iy,na as _n,nb as ms,nd as kA,ne as ay,o as Lg,oa as Nr,ob as ah,od as RA,oe as ly,p as Fg,pa as Je,pb as lh,pc as Ie,pd as CA,pe as cy,q as Le,qa as ml,qb as Rt,qc as rA,qd as DA,r as En,ra as ps,rd as OA,s as jg,se as kl,t as Ug,tb as Zr,td as xh,te as uy,u as qg,ub as Li,uc as rd,ud as bh,ue as dy,v as Bg,vb as Rn,vc as nd,vd as Eh,ve as ad,w as $g,wa as gl,wc as od,wd as Ih,x as Mr,xa as Zg,xc as Dn,xd as Th,xe as Rl,yb as Yu,yc as nA,yd as _h,zb as ch,zc as oA,zd as Ah}from"./chunk-7XX6TY62.js";import{a as fy}from"./chunk-AZUMH3TO.js";import{p as Ku,r as Xg,w as us}from"./chunk-VWLJXTZ5.js";import{$ as $m,$d as dg,A as Fm,Aj as Wg,B as jm,Bf as p,Bj as cs,Cf as be,Cj as Gg,Dj as zu,Ej as Me,Fj as Kg,Gd as Bu,Ge as yg,Gj as Yg,Hc as qu,Hd as lg,Hj as Tn,Jc as tg,Jd as il,Ma as nl,Md as cg,Mf as Tg,Nc as rg,Nf as _g,Oa as Gm,Of as Ag,Pf as ll,Se as vg,Si as Kr,Tc as B,U as Um,Vd as ug,W as qm,Wa as ol,We as Sg,Y as Bm,Ye as wg,Z as rl,_ as ju,aa as P,af as xg,bb as ae,bi as Mi,bj as cl,cb as Jm,cd as ng,de as pg,df as bg,ej as Dg,fb as zm,hb as Uu,he as al,ib as os,ja as Vm,jd as ss,ji as Rg,l as Lm,lb as Km,lc as bn,le as fg,mc as Ym,nb as ur,nc as Xm,ne as mg,od as sl,of as is,pd as Oi,pf as $u,pj as c,qc as Zm,qd as og,qe as gg,qg as kg,qj as Wu,rc as Qm,rg as Vu,rj as Vg,sf as Eg,sj as Gu,tf as Ig,tj as Ju,uj as as,vj as ls,wa as Hm,wc as eg,wd as sg,xd as ig,xj as In,yd as ag,ye as hg,yj as pl,za as Wm,zd as xr,zj as Hg}from"./chunk-ELPXQ32J.js";import{a as s,b as Ve,d as V,e as H,g as wr}from"./chunk-2MRHL4B2.js";var Ev=V((sG,bv)=>{bv.exports=_0;function _0(...e){let t=e;e.length===1&&(Array.isArray(e[0])||typeof e[0]=="string")&&(t=[].concat(e[0]));for(let o=0,i=t.length;o<i;o++)t[o]=typeof t[o]=="string"?t[o]:String(t[o]);t=t.sort(A0);let r={},n="";for(let o=0,i=t.length;o<i;o++){let a=t[o],l=t[o+1]||"",d=!0,f=!0;if(a===l)continue;let m=0,g=a.length;for(;m<g;m++){let h=a.charAt(m);if(d=d&&h===l.charAt(m),f=f&&h===n.charAt(m),!d&&!f){m++;break}}if(n=a,m===g){r[a]=a;continue}for(let h=a.slice(0,m);m<=g;m++)r[h]=a,h+=a.charAt(m)}return r}s(_0,"abbrev");function A0(e,t){return e===t?0:e>t?1:-1}s(A0,"lexSort")});var jd=V((aG,Iv)=>{Iv.exports=process.env.DEBUG_NOPT||process.env.NOPT_DEBUG?(...e)=>console.error(...e):()=>{}});var qd=V((lG,kv)=>{var Tv=Ve("url"),Ud=Ve("path"),_v=Ve("stream").Stream,k0=Ve("os"),Av=jd();function R0(e,t,r){e[t]=String(r)}s(R0,"validateString");function C0(e,t,r){if(r===!0)return!1;if(r===null)return!0;r=String(r);let o=process.platform==="win32"?/^~(\/|\\)/:/^~\//,i=k0.homedir();return i&&r.match(o)?e[t]=Ud.resolve(i,r.slice(2)):e[t]=Ud.resolve(r),!0}s(C0,"validatePath");function D0(e,t,r){if(Av("validate Number %j %j %j",t,r,isNaN(r)),isNaN(r))return!1;e[t]=+r}s(D0,"validateNumber");function O0(e,t,r){let n=Date.parse(r);if(Av("validate Date %j %j %j",t,r,n),isNaN(n))return!1;e[t]=new Date(r)}s(O0,"validateDate");function M0(e,t,r){typeof r=="string"?isNaN(r)?r==="null"||r==="false"?r=!1:r=!0:r=!!+r:r=!!r,e[t]=r}s(M0,"validateBoolean");function P0(e,t,r){if(r=Tv.parse(String(r)),!r.host)return!1;e[t]=r.href}s(P0,"validateUrl");function N0(e,t,r){if(!(r instanceof _v))return!1;e[t]=r}s(N0,"validateStream");kv.exports={String:{type:String,validate:R0},Boolean:{type:Boolean,validate:M0},url:{type:Tv,validate:P0},Number:{type:Number,validate:D0},path:{type:Ud,validate:C0},Stream:{type:_v,validate:N0},Date:{type:Date,validate:O0},Array:{type:Array}}});var Lv=V((uG,Nv)=>{var lc=Ev(),Ce=jd(),L0=qd(),Cv=s((e,t)=>Object.prototype.hasOwnProperty.call(e,t),"hasOwn"),Dv=s((e,{types:t,dynamicTypes:r})=>{let n=Cv(t,e),o=t[e];if(!n&&typeof r=="function"){let i=r(e);i!==void 0&&(o=i,n=!0)}return[n,o]},"getType"),_s=s((e,t)=>t&&e===t,"isTypeDef"),Ur=s((e,t)=>t&&e.indexOf(t)!==-1,"hasTypeDef"),F0=s((e,t)=>t&&!Ur(e,t),"doesNotHaveTypeDef");function j0(e,{types:t,shorthands:r,typeDefs:n,invalidHandler:o,unknownHandler:i,abbrevHandler:a,typeDefault:l,dynamicTypes:d}={}){Ce(t,r,e,n);let f={},m={remain:[],cooked:e,original:e.slice(0)};return Mv(e,f,m.remain,{typeDefs:n,types:t,dynamicTypes:d,shorthands:r,unknownHandler:i,abbrevHandler:a}),Ov(f,{types:t,dynamicTypes:d,typeDefs:n,invalidHandler:o,typeDefault:l}),f.argv=m,Object.defineProperty(f.argv,"toString",{value:s(function(){return this.original.map(JSON.stringify).join(" ")},"value"),enumerable:!1}),f}s(j0,"nopt");function Ov(e,{types:t={},typeDefs:r={},dynamicTypes:n,invalidHandler:o,typeDefault:i}={}){let a=r.String?.type,l=r.Number?.type,d=r.Array?.type,f=r.Boolean?.type,m=r.Date?.type,g=typeof i<"u";g||(i=[!1,!0,null],a&&i.push(a),d&&i.push(d));let h={};Object.keys(e).forEach(y=>{if(y==="argv")return;let E=e[y];Ce("val=%j",E);let w=Array.isArray(E),[v,O]=Dv(y,{types:t,dynamicTypes:n}),k=O;w||(E=[E]),k||(k=i),_s(k,d)&&(k=i.concat(d)),Array.isArray(k)||(k=[k]),Ce("val=%j",E),Ce("types=",k),E=E.map(S=>{if(typeof S=="string"&&(Ce("string %j",S),S=S.trim(),S==="null"&&~k.indexOf(null)||S==="true"&&(~k.indexOf(!0)||Ur(k,f))||S==="false"&&(~k.indexOf(!1)||Ur(k,f))?(S=JSON.parse(S),Ce("jsonable %j",S)):Ur(k,l)&&!isNaN(S)?(Ce("convert to number",S),S=+S):Ur(k,m)&&!isNaN(Date.parse(S))&&(Ce("convert to date",S),S=new Date(S))),!v){if(!g)return S;O=i}S===!1&&~k.indexOf(null)&&!(~k.indexOf(!1)||Ur(k,f))&&(S=null);let R={};return R[y]=S,Ce("prevalidated val",R,S,O),Bd(R,y,S,O,{typeDefs:r})?(Ce("validated v",R,S,O),R[y]):(o?o(y,S,O,e):o!==!1&&Ce("invalid: "+y+"="+S,O),h)}).filter(S=>S!==h),!E.length&&F0(k,d)?(Ce("VAL HAS NO LENGTH, DELETE IT",E,y,k.indexOf(d)),delete e[y]):w?(Ce(w,e[y],E),e[y]=E):e[y]=E[0],Ce("k=%s val=%j",y,E,e[y])})}s(Ov,"clean");function Bd(e,t,r,n,{typeDefs:o}={}){let i=o?.Array?.type;if(Array.isArray(n)){for(let d=0,f=n.length;d<f;d++)if(!_s(n[d],i)&&Bd(e,t,r,n[d],{typeDefs:o}))return!0;return delete e[t],!1}if(_s(n,i))return!0;if(n!==n)return Ce("Poison NaN",t,r,n),delete e[t],!1;if(r===n)return Ce("Explicitly allowed %j",r),e[t]=r,!0;let a=!1,l=Object.keys(o);for(let d=0,f=l.length;d<f;d++){Ce("test type %j %j %j",t,r,l[d]);let m=o[l[d]];if(m&&(n&&n.name&&m.type&&m.type.name?n.name===m.type.name:n===m.type)){let g={};if(a=m.validate(g,t,r)!==!1,r=g[t],a){e[t]=r;break}}}return Ce("OK? %j (%j %j %j)",a,t,r,l[l.length-1]),a||delete e[t],a}s(Bd,"validate");function Mv(e,t,r,{types:n={},typeDefs:o={},shorthands:i={},dynamicTypes:a,unknownHandler:l,abbrevHandler:d}={}){let f=o.String?.type,m=o.Number?.type,g=o.Array?.type,h=o.Boolean?.type;Ce("parse",e,t,r);let y=lc(Object.keys(n));Ce("abbrevs=%j",y);let E=lc(Object.keys(i));for(let w=0;w<e.length;w++){let v=e[w];if(Ce("arg",v),v.match(/^-{2,}$/)){r.push.apply(r,e.slice(w+1)),e[w]="--";break}let O=!1;if(v.charAt(0)==="-"&&v.length>1){let k=v.indexOf("=");if(k>-1){O=!0;let N=v.slice(k+1);v=v.slice(0,k),e.splice(w,1,v,N)}let S=Pv(v,E,y,{shorthands:i,abbrevHandler:d});if(Ce("arg=%j shRes=%j",v,S),S&&(e.splice.apply(e,[w,1].concat(S)),v!==S[0])){w--;continue}v=v.replace(/^-+/,"");let R=null;for(;v.toLowerCase().indexOf("no-")===0;)R=!R,v=v.slice(3);y[v]&&y[v]!==v&&(d?d(v,y[v]):d!==!1&&Ce(`abbrev: ${v} -> ${y[v]}`),v=y[v]);let[M,C]=Dv(v,{types:n,dynamicTypes:a}),x=Array.isArray(C);x&&C.length===1&&(x=!1,C=C[0]);let _=_s(C,g)||x&&Ur(C,g);!M&&Cv(t,v)&&(Array.isArray(t[v])||(t[v]=[t[v]]),_=!0);let T,b=e[w+1],A=typeof R=="boolean"||_s(C,h)||x&&Ur(C,h)||typeof C>"u"&&!O||b==="false"&&(C===null||x&&~C.indexOf(null));if(typeof C>"u"){let N=!O&&b&&!b?.startsWith("-")&&!["true","false"].includes(b);l?N?l(v,b):l(v):l!==!1&&(Ce(`unknown: ${v}`),N&&Ce(`unknown: ${b} parsed as normal opt`))}if(A){T=!R,(b==="true"||b==="false")&&(T=JSON.parse(b),b=null,R&&(T=!T),w++),x&&b&&(~C.indexOf(b)?(T=b,w++):b==="null"&&~C.indexOf(null)?(T=null,w++):!b.match(/^-{2,}[^-]/)&&!isNaN(b)&&Ur(C,m)?(T=+b,w++):!b.match(/^-[^-]/)&&Ur(C,f)&&(T=b,w++)),_?(t[v]=t[v]||[]).push(T):t[v]=T;continue}_s(C,f)&&(b===void 0?b="":b.match(/^-{1,2}[^-]+/)&&(b="",w--)),b&&b.match(/^-{2,}$/)&&(b=void 0,w--),T=b===void 0?!0:b,_?(t[v]=t[v]||[]).push(T):t[v]=T,w++;continue}r.push(v)}}s(Mv,"parse");var Rv=Symbol("singles"),U0=s((e,t)=>{let r=t[Rv];r||(r=Object.keys(t).filter(o=>o.length===1).reduce((o,i)=>(o[i]=!0,o),{}),t[Rv]=r,Ce("shorthand singles",r));let n=e.split("").filter(o=>r[o]);return n.join("")===e?n:null},"singleCharacters");function Pv(e,...t){let{abbrevHandler:r,types:n={},shorthands:o={}}=t.length?t.pop():{},i=t[0]??lc(Object.keys(o)),a=t[1]??lc(Object.keys(n));if(e=e.replace(/^-+/,""),a[e]===e)return null;if(o[e])return o[e]&&!Array.isArray(o[e])&&(o[e]=o[e].split(/\s+/)),o[e];let l=U0(e,o);return l?l.map(d=>o[d]).reduce((d,f)=>d.concat(f),[]):a[e]&&!o[e]?null:(i[e]&&(r?r(e,i[e]):r!==!1&&Ce(`abbrev: ${e} -> ${i[e]}`),e=i[e]),o[e]&&!Array.isArray(o[e])&&(o[e]=o[e].split(/\s+/)),o[e])}s(Pv,"resolveShort");Nv.exports={nopt:j0,clean:Ov,parse:Mv,validate:Bd,resolveShort:Pv,typeDefs:L0}});var Vd=V((Qt,Fv)=>{var $d=Lv(),q0=qd();Fv.exports=Qt=B0;Qt.clean=$0;Qt.typeDefs=q0;Qt.lib=$d;function B0(e,t,r=process.argv,n=2){return $d.nopt(r.slice(n),{types:e||{},shorthands:t||{},typeDefs:Qt.typeDefs,invalidHandler:Qt.invalidHandler,unknownHandler:Qt.unknownHandler,abbrevHandler:Qt.abbrevHandler})}s(B0,"nopt");function $0(e,t,r=Qt.typeDefs){return $d.clean(e,{types:t||{},typeDefs:r,invalidHandler:Qt.invalidHandler,unknownHandler:Qt.unknownHandler,abbrevHandler:Qt.abbrevHandler})}s($0,"clean")});var Hd=V((fG,Uv)=>{var jv=s(e=>{if(typeof e=="string"){if(/^0o?[0-7]+$/.test(e))return parseInt(e.replace(/^0o?/,""),8);if(/^[1-9][0-9]*$/.test(e))return parseInt(e,10);throw new Error(`invalid umask value: ${e}`)}else{if(typeof e!="number")throw new Error(`invalid umask value: ${e}`);if(e=Math.floor(e),e<0||e>511)throw new Error(`invalid umask value: ${e}`);return e}},"parse"),V0=s((e,t,r)=>{try{return e[t]=jv(r),!0}catch{return!1}},"validate");Uv.exports={parse:jv,validate:V0}});var As=V((gG,Jd)=>{var qn=Vd(),{validate:H0}=Hd(),Wd=class{static{s(this,"Umask")}},Gd=class{static{s(this,"Semver")}},W0=MA(),G0=s((e,t,r)=>{let n=W0(r);if(!n)return!1;e[t]=n},"validateSemver"),J0=qn.typeDefs.path.validate,z0=s((e,t,r)=>typeof r!="string"?!1:J0(e,t,r),"validatePath");Jd.exports={...qn.typeDefs,semver:{type:Gd,validate:G0,description:"full valid SemVer string"},Umask:{type:Wd,validate:H0,description:"octal number in range 0o000..0o777 (0..511)"},url:{...qn.typeDefs.url,description:'full url with "http://"'},path:{...qn.typeDefs.path,validate:z0,description:"valid filesystem path"},Number:{...qn.typeDefs.Number,description:"numeric value"},Boolean:{...qn.typeDefs.Boolean,description:"boolean value (true or false)"},Date:{...qn.typeDefs.Date,description:"valid Date string"}};qn.typeDefs=Jd.exports});var $v=V((yG,Bv)=>{var{URL:qv}=Ve("node:url");Bv.exports=e=>{let t=new qv(e),r=`${t.protocol}//${t.host}${t.pathname}`,n=new qv(".",r);return`//${n.host}${n.pathname}`}});var zd=V((vG,Vv)=>{var K0=/(?<!\\)(\\*)\$\{([^${}?]+)(\?)?\}/g;Vv.exports=(e,t)=>e.replace(K0,(r,n,o,i)=>{let a=i==="?"?"":`\${${o}}`,l=t[o]!==void 0?t[o]:a;return n.length%2?r.slice((n.length+1)/2):n.slice(n.length/2)+l})});var Gv=V((SG,Wv)=>{var ks=As(),Y0=zd(),{resolve:Hv}=Ve("node:path"),{parse:X0}=Hd(),Kd=s((e,t,r,n=!1)=>{if(typeof e!="string"&&!Array.isArray(e))return e;let{platform:o,types:i,home:a,env:l}=r,d=new Set([].concat(i[t])),f=d.has(ks.path.type),m=d.has(ks.Boolean.type),g=f||d.has(ks.String.type),h=d.has(ks.Umask.type),y=d.has(ks.Number.type),E=!n&&d.has(Array),w=d.has(ks.Date.type);if(Array.isArray(e))return E?e.map(v=>Kd(v,t,r,!0)):e;if(e=e.trim(),E)return Kd(e.split(`
19
+
20
+ `),t,r);if(m&&!g&&e==="")return!0;if(!g&&!f&&!y)switch(e){case"true":return!0;case"false":return!1;case"null":return null;case"undefined":return}if(e=Y0(e,l),w)return new Date(e);if(f&&((o==="win32"?/^~(\/|\\)/:/^~\//).test(e)&&a?e=Hv(a,e.slice(2)):e=Hv(e)),h)try{return X0(e)}catch{return e}return y&&!isNaN(e)&&(e=+e),e},"parseField");Wv.exports=Kd});var Yv=V((xG,Kv)=>{var Z0=s((e,t)=>!/^[/@_]/.test(e)&&typeof Yd(t)=="string"&&`npm_config_${e.replace(/-/g,"_").toLowerCase()}`,"envKey"),Yd=s(e=>Array.isArray(e)?e.map(t=>Yd(t)).join(`
21
+
22
+ `):e==null||e===!1?"":typeof e=="object"?null:String(e),"envVal"),Jv=s((e,t)=>!Array.isArray(t)||!Array.isArray(e)?e===t:Q0(e,t),"sameConfigValue"),Q0=s((e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0},"sameArrayValue"),zv=s((e,t,r)=>{let n=Yd(r),o=Z0(t,n);o&&n!==null&&(e[o]=n)},"setEnv"),eR=s(e=>{let{env:t,defaults:r,definitions:n,list:[o,i]}=e;t.INIT_CWD=process.cwd();let a=new Set(Object.keys(o)),l=new Set(Object.keys(i));for(let d in o){let{deprecated:f,envExport:m=!0}=n[d]||{};f||m===!1||(Jv(r[d],o[d])?Jv(i[d],o[d])||zv(t,d,o[d]):l.has(d)&&!a.has(d)||zv(t,d,o[d]))}t.HOME=e.home,t.npm_config_global_prefix=e.globalPrefix,t.npm_config_local_prefix=e.localPrefix,o.editor&&(t.EDITOR=o.editor),o["node-options"]&&(t.NODE_OPTIONS=o["node-options"]),t.npm_config_node_gyp=o["node-gyp"],t.npm_config_npm_version=o["npm-version"]||"unknown",t.npm_execpath=e.npmBin,t.NODE=t.npm_node_execpath=e.execPath},"setEnvs");Kv.exports=eR});var Zv=V((EG,Xv)=>{"use strict";var Xd=class extends Error{static{s(this,"ErrInvalidAuth")}constructor(t){let r="Invalid auth configuration found: ";r+=t.map(n=>{if(n.action==="delete")return`\`${n.key}\` is not allowed in ${n.where} config`;if(n.action==="rename")return`\`${n.from}\` must be renamed to \`${n.to}\` in ${n.where} config`}).join(", "),r+="\nPlease run `npm config fix` to repair your configuration.`",super(r),this.code="ERR_INVALID_AUTH",this.problems=t}};Xv.exports={ErrInvalidAuth:Xd}});var tS=V((TG,eS)=>{var tR=As(),Qv=s(e=>{if(!e||typeof e!="function"&&typeof e!="object")return e;if(Array.isArray(e))return e.map(t=>Qv(t));for(let{type:t,description:r}of Object.values(tR))if(t===e)return r||t;return e},"typeDescription");eS.exports=e=>[].concat(Qv(e)).filter(t=>t!==void 0)});var iS=V((AG,rp)=>{var{walkUp:rR}=LA(),rS=FA(),ln=Vd(),{log:pr,time:nR}=NA(),{resolve:ia,dirname:cc,join:Zd}=Ve("node:path"),{homedir:oR}=Ve("node:os"),{readFile:sR,writeFile:iR,chmod:aR,unlink:lR,stat:nS,mkdir:cR}=Ve("node:fs/promises"),uR=["npm-version","global-prefix","local-prefix"],Qd=s((...e)=>nS(ia(...e)).then(t=>t.isFile()).catch(()=>!1),"fileExists"),dR=s((...e)=>nS(ia(...e)).then(t=>t.isDirectory()).catch(()=>!1),"dirExists"),uc=s((e,t)=>Object.prototype.hasOwnProperty.call(e,t),"hasOwnProperty"),Rs=As(),go=$v(),pR=zd(),fR=Gv(),mR=Yv(),oS=new Set(["global","user","project"]),oa=new Set(["default","builtin",...oS,"env","cli"]),ep=class{static{s(this,"Config")}#r=!1;#n;#e=null;#o=[];static get typeDefs(){return Rs}constructor({definitions:t,shorthands:r,flatten:n,nerfDarts:o=[],npmPath:i,env:a=process.env,argv:l=process.argv,platform:d=process.platform,execPath:f=process.execPath,cwd:m=process.cwd(),excludeNpmCwd:g=!1,warn:h=!0}){this.nerfDarts=o,this.definitions=t;let{types:y,defaults:E,deprecated:w}=sS(t);this.deprecated=w,this.#n=n,this.types=y,this.shorthands=r,this.defaults=E,this.npmPath=i,this.npmBin=Zd(this.npmPath,"bin/npm-cli.js"),this.argv=l,this.env=a,this.execPath=f,this.platform=d,this.cwd=m,this.excludeNpmCwd=g,this.globalPrefix=null,this.localPrefix=null,this.localPackage=null,this.home=null;let v=[...oa];this.data=new Map;let O=null;for(let k of v)this.data.set(k,O=new tp(O));this.data.set=()=>{throw new Error("cannot change internal config data structure")},this.data.delete=()=>{throw new Error("cannot change internal config data structure")},this.sources=new Map([]);for(let{data:k}of this.data.values())this.list.unshift(k);this.#r=!1,this.warn=h}get list(){let t=[];for(let{data:r}of this.data.values())t.unshift(r);return t}get loaded(){return this.#r}get prefix(){return this.#t("global")?this.globalPrefix:this.localPrefix}find(t){if(!this.loaded)throw new Error("call config.load() before reading values");let r=[...this.data.entries()];for(let n=r.length-1;n>-1;n--){let[o,{data:i}]=r[n];if(uc(i,t))return o}return null}get(t,r){if(!this.loaded)throw new Error("call config.load() before reading values");return this.#t(t,r)}#t(t,r=null){if(r!==null&&!oa.has(r))throw new Error("invalid config location param: "+r);let{data:n}=this.data.get(r||"cli");return r===null||uc(n,t)?n[t]:void 0}set(t,r,n="cli"){if(!this.loaded)throw new Error("call config.load() before setting values");if(!oa.has(n))throw new Error("invalid config location param: "+n);this.#a(t);let{data:o,raw:i}=this.data.get(n);o[t]=r,["global","user","project"].includes(n)&&(i[t]=r),this.data.get(n)[Cs]=null,this.#e=null}get flat(){if(this.#e)return this.#e;let t=nR.start("config:load:flatten");this.#e={};for(let{data:r}of this.data.values())this.#n(r,this.#e);return this.#e.nodeBin=this.execPath,this.#e.npmBin=this.npmBin,t(),this.#e}delete(t,r="cli"){if(!this.loaded)throw new Error("call config.load() before deleting values");if(!oa.has(r))throw new Error("invalid config location param: "+r);let{data:n,raw:o}=this.data.get(r);delete n[t],["global","user","project"].includes(r)&&delete o[t]}async load(){if(this.loaded)throw new Error("attempting to load npm config multiple times");this.loadDefaults(),await this.loadBuiltinConfig(),this.loadCLI(),this.loadEnv(),await this.loadProjectConfig(),await this.loadUserConfig(),await this.loadGlobalConfig(),this.#r=!0,this.globalPrefix=this.get("prefix"),this.setEnvs()}loadDefaults(){this.loadGlobalPrefix(),this.loadHome();let t={...this.defaults,prefix:this.globalPrefix};try{t["npm-version"]=Ve(Zd(this.npmPath,"package.json")).version}catch{}this.#s(t,"default","default values");let{data:r}=this.data.get("default");Object.defineProperty(r,"globalconfig",{get:s(()=>ia(this.#t("prefix"),"etc/npmrc"),"get"),set(n){Object.defineProperty(r,"globalconfig",{value:n,configurable:!0,writable:!0,enumerable:!0})},configurable:!0,enumerable:!0})}loadHome(){this.home=this.env.HOME||oR()}loadGlobalPrefix(){if(this.globalPrefix)throw new Error("cannot load default global prefix more than once");this.env.PREFIX?this.globalPrefix=this.env.PREFIX:this.platform==="win32"?this.globalPrefix=cc(this.execPath):(this.globalPrefix=cc(cc(this.execPath)),this.env.DESTDIR&&(this.globalPrefix=Zd(this.env.DESTDIR,this.globalPrefix)))}loadEnv(){let t=Object.create(null);for(let[r,n]of Object.entries(this.env)){if(!/^npm_config_/i.test(r)||n==="")continue;let o=r.slice(11);o.startsWith("//")||(o=o.replace(/(?!^)_/g,"-").toLowerCase()),t[o]=n}this.#s(t,"env","environment")}loadCLI(){for(let r of Object.keys(this.shorthands))r.length>1&&this.argv.includes(`-${r}`)&&pr.warn(`-${r} is not a valid single-hyphen cli flag and will be removed in the future`);ln.invalidHandler=(r,n,o)=>this.invalidHandler(r,n,o,"command line options","cli"),ln.unknownHandler=(r,n)=>this.unknownHandler(r,n),ln.abbrevHandler=this.abbrevHandler;let t=ln(this.types,this.shorthands,this.argv);ln.invalidHandler=null,ln.unknownHandler=null,this.parsedArgv=t.argv,delete t.argv,this.#s(t,"cli","command line options")}get valid(){for(let[t,{valid:r}]of this.data.entries())if(r===!1||r===null&&!this.validate(t))return!1;return!0}validate(t){if(t){let r=this.data.get(t);return r[Cs]=!0,ln.invalidHandler=(n,o,i)=>this.invalidHandler(n,o,i,r.source,t),ln.clean(r.data,this.types,Rs),ln.invalidHandler=null,r[Cs]}else{let r=!0,n=[];for(let o of this.data.keys()){if(o==="default"||o==="builtin"||o==="cli")continue;let i=this.validate(o);if(r=r&&i,["global","user","project"].includes(o)){for(let l of["_authtoken","-authtoken"])this.get(l,o)&&n.push({action:"delete",key:l,where:o});let a=go(this.get("registry"));for(let l of["_auth","_authToken","username","_password"])this.get(l,o)&&(l==="username"&&!this.get("_password",o)?n.push({action:"delete",key:l,where:o}):l==="_password"&&!this.get("username",o)?n.push({action:"delete",key:l,where:o}):n.push({action:"rename",from:l,to:`${a}:${l}`,where:o}))}}if(n.length){let{ErrInvalidAuth:o}=Zv();throw new o(n)}return r}}repair(t){if(!t)try{this.validate()}catch(r){if(r.code!=="ERR_INVALID_AUTH")throw r;t=r.problems}finally{t||(t=[])}for(let r of t)if(r.action==="delete")this.delete(r.key,r.where);else if(r.action==="rename"){let n=this.data.get(r.where).raw?.[r.from],o=this.get(r.from,r.where);this.set(r.to,n||o,r.where),this.delete(r.from,r.where)}}isDefault(t){let[r,...n]=[...oa],o=this.data.get(r).data;return uc(o,t)&&n.every(i=>{let a=this.data.get(i).data;return!uc(a,t)})}invalidHandler(t,r,n,o,i){let a=tS();pr.warn("invalid config",t+"="+JSON.stringify(r),`set in ${o}`),this.data.get(i)[Cs]=!1,Array.isArray(n)&&(n.includes(Rs.url.type)?n=Rs.url.type:n.includes(Rs.path.type)&&(n=Rs.path.type));let l=a(n),d=l.filter(g=>g!==void 0&&g!==Array),f="Must be"+this.#l(d,l),m=d.length===1?d[0]:[...new Set(d.map(g=>typeof g=="string"?g:JSON.stringify(g)))].join(", ");pr.warn("invalid config",f,m)}abbrevHandler(t,r){pr.warn(`Expanding --${t} to --${r}. This will stop working in the next major version of npm.`)}unknownHandler(t,r){r&&this.queueWarning(`unknown:${r}`,`"${r}" is being parsed as a normal command line argument.`)}#l(t,r){let n;return t.length===1&&r.includes(Array)?n=" one or more":t.length>1&&r.includes(Array)?n=" one or more of:":t.length>1?n=" one of:":n="",n}#s(t,r,n,o=null){let i=this.data.get(r);if(i.source){let a=`double-loading "${r}" configs from ${n}, previously loaded from ${i.source}`;throw new Error(a)}if(this.sources.has(n)){let a=`double-loading config "${n}" as "${r}", previously loaded as "${this.sources.get(n)}"`;throw new Error(a)}if(i.source=n,this.sources.set(n,r),o)i.loadError=o,o.code!=="ENOENT"&&pr.verbose("config",`error loading ${r} config`,o);else{i.raw=t;e:for(let[a,l]of Object.entries(t)){let d=pR(a,this.env),f=this.parseField(l,d);if(r!=="default"&&(this.#a(d),this.definitions[a]?.exclusive)){for(let m of this.definitions[a].exclusive)if(!this.isDefault(m)){if(r==="env"){let g=this.data.get("cli").data;if(Object.hasOwn(g,m))continue e}throw new TypeError(`--${a} cannot be provided when using --${m}`)}}(r!=="default"||a==="npm-version")&&this.checkUnknown(r,a),i.data[d]=f}}}checkUnknown(t,r){if(!this.definitions[r]){if(uR.includes(r))return;let n=t!=="cli"?" See `npm help npmrc` for supported config options.":"";if(!r.includes(":")){this.queueWarning(r,`Unknown ${t} config "${t==="cli"?"--":""}${r}". This will stop working in the next major version of npm.${n}`);return}let o=r.split(":").pop();!this.definitions[o]&&!this.nerfDarts.includes(o)&&this.queueWarning(o,`Unknown ${t} config "${o}" (${r}). This will stop working in the next major version of npm.${n}`)}}#a(t){this.deprecated[t]&&pr.warn("config",t,this.deprecated[t])}parseField(t,r,n=!1){return fR(t,r,this,n)}async#i(t,r){pr.silly("config",`load:file:${t}`),await sR(t,"utf8").then(n=>{let o=rS.parse(n);return r==="project"&&o.prefix&&pr.error("config",`prefix cannot be changed from project config: ${t}.`),this.#s(o,r,t)},n=>this.#s(null,r,t,n))}loadBuiltinConfig(){return this.#i(ia(this.npmPath,"npmrc"),"builtin")}async loadProjectConfig(){if(await this.loadLocalPrefix(),this.localPackage==null&&(this.localPackage=await Qd(this.localPrefix,"package.json")),this.#t("global")===!0||this.#t("location")==="global"){this.data.get("project").source="(global mode enabled, ignored)",this.sources.set(this.data.get("project").source,"project");return}let t=ia(this.localPrefix,".npmrc");if(t!==this.#t("userconfig"))return this.#i(t,"project");this.data.get("project").source='(same as "user" config, ignored)',this.sources.set(this.data.get("project").source,"project")}async loadLocalPrefix(){let t=this.#t("prefix","cli");if(t){this.localPrefix=t;return}let r=this.#t("workspaces","cli"),n=this.#t("global")||this.#t("location")==="global";for(let o of rR(this.cwd)){if(this.excludeNpmCwd&&o===this.npmPath)break;let i=await Qd(o,"package.json");if(!this.localPrefix&&(i||await dR(o,"node_modules"))){if(this.localPrefix=o,this.localPackage=i,r===!1||n)return;continue}if(this.localPrefix&&i){let a=jA(),{content:l}=await a.normalize(o).catch(()=>({content:{}}));if(!l?.workspaces)continue;let f=await UA()({cwd:o,pkg:l});for(let m of f.values())if(m===this.localPrefix){await Qd(this.localPrefix,".npmrc")&&pr.warn("config",`ignoring workspace config at ${this.localPrefix}/.npmrc`);let{data:g}=this.data.get("default");g.workspace=[this.localPrefix],this.localPrefix=o,this.localPackage=i,pr.info("config",`found workspace root at ${this.localPrefix}`);return}}}this.localPrefix||(this.localPrefix=this.cwd)}loadUserConfig(){return this.#i(this.#t("userconfig"),"user")}loadGlobalConfig(){return this.#i(this.#t("globalconfig"),"global")}async save(t){if(!this.loaded)throw new Error("call config.load() before saving");if(!oS.has(t))throw new Error("invalid config location param: "+t);let r=this.data.get(t);if(r[sa]=null,t==="user"){let a=go(this.get("registry")),l=this.get(`${a}:email`,"user");l&&(this.delete(`${a}:email`,"user"),this.set("email",l,"user"))}let n=rS.stringify(r.raw).trim()+`
23
+ `;if(!n.trim()){await lR(r.source).catch(()=>{});return}let o=cc(r.source);await cR(o,{recursive:!0}),await iR(r.source,n,"utf8");let i=t==="user"?384:438;await aR(r.source,i)}clearCredentialsByURI(t,r="user"){let n=go(t);if(go(this.get("registry"))===n){this.delete("-authtoken",r),this.delete("_authToken",r),this.delete("_authtoken",r),this.delete("_auth",r),this.delete("_password",r),this.delete("username",r);let i=this.get(`${n}:email`,r);i&&this.set("email",i,r)}this.delete(`${n}:_authToken`,r),this.delete(`${n}:_auth`,r),this.delete(`${n}:_password`,r),this.delete(`${n}:username`,r),this.delete(`${n}:email`,r),this.delete(`${n}:certfile`,r),this.delete(`${n}:keyfile`,r)}setCredentialsByURI(t,{token:r,username:n,password:o,certfile:i,keyfile:a}){let l=go(t);if(this.delete(`${l}:always-auth`,"user"),this.delete(`${l}:email`,"user"),i&&a&&(this.set(`${l}:certfile`,i,"user"),this.set(`${l}:keyfile`,a,"user")),r)this.set(`${l}:_authToken`,r,"user"),this.delete(`${l}:_password`,"user"),this.delete(`${l}:username`,"user");else if(n||o){if(!n)throw new Error("must include username");if(!o)throw new Error("must include password");this.delete(`${l}:_authToken`,"user"),this.set(`${l}:username`,n,"user");let d=Buffer.from(o,"utf8").toString("base64");this.set(`${l}:_password`,d,"user")}else if(!i||!a)throw new Error("No credentials to set.")}getCredentialsByURI(t){let r=go(t),n=go(this.get("registry")),o={},i=this.get(`${r}:email`)||this.get("email");i&&(r===n&&this.set("email",i,"user"),o.email=i);let a=this.get(`${r}:certfile`),l=this.get(`${r}:keyfile`);a&&l&&(o.certfile=a,o.keyfile=l);let d=this.get(`${r}:_authToken`);if(d)return o.token=d,o;let f=this.get(`${r}:username`),m=this.get(`${r}:_password`);if(f&&m){o.username=f,o.password=Buffer.from(m,"base64").toString("utf8");let h=`${o.username}:${o.password}`;return o.auth=Buffer.from(h,"utf8").toString("base64"),o}let g=this.get(`${r}:_auth`);if(g){let y=Buffer.from(g,"base64").toString("utf8").split(":");return o.username=y.shift(),o.password=y.join(":"),o.auth=g,o}return o}setEnvs(){mR(this)}removeWarning(t){this.#o=this.#o.filter(r=>r.type!==t)}getUnknownPositionals(){return this.#o.filter(t=>t.type.startsWith("unknown:")).map(t=>t.type.slice(8))}removeUnknownPositional(t){this.removeWarning(`unknown:${t}`)}queueWarning(t,...r){this.warn?pr.warn(...r):this.#o.push({type:t,args:r})}logWarnings(){for(let t of this.#o)pr.warn(...t.args);this.#o=[]}},sa=Symbol("loadError"),Cs=Symbol("valid"),tp=class{static{s(this,"ConfigData")}#r;#n=null;#e=null;constructor(t){this.#r=Object.create(t&&t.data),this.#e={},this[Cs]=!0}get data(){return this.#r}get valid(){return this[Cs]}set source(t){if(this.#n)throw new Error("cannot set ConfigData source more than once");this.#n=t}get source(){return this.#n}set loadError(t){if(this[sa]||Object.keys(this.#e).length)throw new Error("cannot set ConfigData loadError after load");this[sa]=t}get loadError(){return this[sa]}set raw(t){if(Object.keys(this.#e).length||this[sa])throw new Error("cannot set ConfigData raw after load");this.#e=t}get raw(){return this.#e}},sS=s(e=>{let t={},r={},n={};for(let[o,i]of Object.entries(e))r[o]=i.default,t[o]=i.type,i.deprecated&&(n[o]=i.deprecated.trim().replace(/\n +/,`
24
+ `));return{types:t,defaults:r,deprecated:n}},"getTypesFromDefinitions");rp.exports=ep;rp.exports.getTypesFromDefinitions=sS});var dS=V((RG,uS)=>{var gR=["type","description","default","key"],hR=["default","defaultDescription","deprecated","description","exclusive","flatten","hint","key","short","type","typeDescription","usage","envExport","alias","required"],{semver:{type:yR},Umask:{type:vR},url:{type:SR},path:{type:wR}}=As(),np=class{static{s(this,"Definition")}constructor(t,r){this.key=t,this.envExport=!0,Object.assign(this,r),this.validate(),this.defaultDescription||(this.defaultDescription=cS(this.default)),this.typeDescription||(this.typeDescription=lS(this.type)),this.hint||(this.type===Number?this.hint="<number>":this.hint=`<${this.key}>`),this.usage||(this.usage=xR(this))}validate(){for(let t of gR)if(!Object.prototype.hasOwnProperty.call(this,t))throw new Error(`config lacks ${t}: ${this.key}`);if(!this.key)throw new Error(`config lacks key: ${this.key}`);for(let t of Object.keys(this))if(!hR.includes(t))throw new Error(`config defines unknown field ${t}: ${this.key}`)}describe(){let t=aa(this.description),r=this.envExport?"":`
25
+ This value is not exported to the environment for child processes.
26
+ `,n=this.deprecated?`* DEPRECATED: ${aa(this.deprecated)}
27
+ `:"",o=this.exclusive?`
28
+ This config cannot be used with: \`${this.exclusive.join("`, `")}\``:"";return bR(`#### \`${this.key}\`
29
+
30
+ * Default: ${aa(this.defaultDescription)}
31
+ * Type: ${aa(this.typeDescription)}
32
+ ${n}
33
+ ${t}
34
+ ${o}
35
+ ${r}`)}},xR=s(e=>{let t="";if(!Array.isArray(e.type))return e.short&&(t=`-${e.short}|`),e.type===Boolean&&e.default!==!1?t=`${t}--no-${e.key}`:t=`${t}--${e.key}`,e.type!==Boolean&&(t=`${t} ${e.hint}`),t;t=`--${e.key}`,e.short&&(t=`-${e.short}|--${e.key}`);let r=e.type,n=r.includes(Array),o=r.includes(Boolean);if(r=r.filter(l=>l!==null&&l!==Array&&l!==Boolean),!r.length)return t;let i;r.some(l=>typeof l!="string")?i=e.hint:i=`<${r.filter(l=>l).join("|")}>`,o&&(t=`--no-${e.key}|${t}`);let a=`${t} ${i}`;return n?`${a} [${a} ...]`:a},"describeUsage"),lS=s(e=>{if(Array.isArray(e)){let t=e.filter(a=>a!==Array).map(a=>lS(a)),r=t.length>1?[t.pop()]:[],n=t.length>1?", or ":" or ",o=[t.join(", ")].concat(r).join(n),i=e.includes(Array)?" (can be set multiple times)":"";return`${o}${i}`}switch(e){case String:return"String";case Number:return"Number";case vR:return"Octal numeric string in range 0000..0777 (0..511)";case Boolean:return"Boolean";case Date:return"Date";case wR:return"Path";case yR:return"SemVer string";case SR:return"URL";default:return cS(e)}},"describeType"),cS=s(e=>typeof e=="string"?JSON.stringify(e):String(e),"describeValue"),aa=s(e=>{let t=e.match(/\n +/);return t?e.split(t[0]).join(`
36
+ `).trim():e.trim()},"unindent"),aS=s(e=>{let t=Math.min(Math.max(20,process.stdout.columns)||80,80)-5;return aa(e).split(/[ \n]+/).reduce((r,n)=>{let o=r.split(`
37
+ `).pop(),i=o.length&&o.length+n.length>t?`
38
+ `:" ";return r+i+n})},"wrap"),bR=s(e=>{let t=!1;return e.split(`
39
+
40
+ `).map(r=>t||r.startsWith("```")?(t=!r.endsWith("```"),r):r.charAt(0)==="*"?"* "+r.slice(1).trim().split(`
41
+ * `).map(n=>aS(n).replace(/\n/g,`
42
+ `)).join(`
43
+ * `):aS(r)).join(`
44
+
45
+ `)},"wrapAll");uS.exports=np});var pS=V((DG,ER)=>{ER.exports=[{name:"Agola CI",constant:"AGOLA",env:"AGOLA_GIT_REF",pr:"AGOLA_PULL_REQUEST_ID"},{name:"Alpic",constant:"ALPIC",env:"ALPIC_HOST"},{name:"Appcircle",constant:"APPCIRCLE",env:"AC_APPCIRCLE",pr:{env:"AC_GIT_PR",ne:"false"}},{name:"AppVeyor",constant:"APPVEYOR",env:"APPVEYOR",pr:"APPVEYOR_PULL_REQUEST_NUMBER"},{name:"AWS CodeBuild",constant:"CODEBUILD",env:"CODEBUILD_BUILD_ARN",pr:{env:"CODEBUILD_WEBHOOK_EVENT",any:["PULL_REQUEST_CREATED","PULL_REQUEST_UPDATED","PULL_REQUEST_REOPENED"]}},{name:"Azure Pipelines",constant:"AZURE_PIPELINES",env:"TF_BUILD",pr:{BUILD_REASON:"PullRequest"}},{name:"Bamboo",constant:"BAMBOO",env:"bamboo_planKey"},{name:"Bitbucket Pipelines",constant:"BITBUCKET",env:"BITBUCKET_COMMIT",pr:"BITBUCKET_PR_ID"},{name:"Bitrise",constant:"BITRISE",env:"BITRISE_IO",pr:"BITRISE_PULL_REQUEST"},{name:"Buddy",constant:"BUDDY",env:"BUDDY_WORKSPACE_ID",pr:"BUDDY_EXECUTION_PULL_REQUEST_ID"},{name:"Buildkite",constant:"BUILDKITE",env:"BUILDKITE",pr:{env:"BUILDKITE_PULL_REQUEST",ne:"false"}},{name:"CircleCI",constant:"CIRCLE",env:"CIRCLECI",pr:"CIRCLE_PULL_REQUEST"},{name:"Cirrus CI",constant:"CIRRUS",env:"CIRRUS_CI",pr:"CIRRUS_PR"},{name:"Cloudflare Pages",constant:"CLOUDFLARE_PAGES",env:"CF_PAGES"},{name:"Cloudflare Workers",constant:"CLOUDFLARE_WORKERS",env:"WORKERS_CI"},{name:"Codefresh",constant:"CODEFRESH",env:"CF_BUILD_ID",pr:{any:["CF_PULL_REQUEST_NUMBER","CF_PULL_REQUEST_ID"]}},{name:"Codemagic",constant:"CODEMAGIC",env:"CM_BUILD_ID",pr:"CM_PULL_REQUEST"},{name:"Codeship",constant:"CODESHIP",env:{CI_NAME:"codeship"}},{name:"Drone",constant:"DRONE",env:"DRONE",pr:{DRONE_BUILD_EVENT:"pull_request"}},{name:"dsari",constant:"DSARI",env:"DSARI"},{name:"Earthly",constant:"EARTHLY",env:"EARTHLY_CI"},{name:"Expo Application Services",constant:"EAS",env:"EAS_BUILD"},{name:"Gerrit",constant:"GERRIT",env:"GERRIT_PROJECT"},{name:"Gitea Actions",constant:"GITEA_ACTIONS",env:"GITEA_ACTIONS"},{name:"GitHub Actions",constant:"GITHUB_ACTIONS",env:"GITHUB_ACTIONS",pr:{GITHUB_EVENT_NAME:"pull_request"}},{name:"GitLab CI",constant:"GITLAB",env:"GITLAB_CI",pr:"CI_MERGE_REQUEST_ID"},{name:"GoCD",constant:"GOCD",env:"GO_PIPELINE_LABEL"},{name:"Google Cloud Build",constant:"GOOGLE_CLOUD_BUILD",env:"BUILDER_OUTPUT"},{name:"Harness CI",constant:"HARNESS",env:"HARNESS_BUILD_ID"},{name:"Heroku",constant:"HEROKU",env:{env:"NODE",includes:"/app/.heroku/node/bin/node"}},{name:"Hudson",constant:"HUDSON",env:"HUDSON_URL"},{name:"Jenkins",constant:"JENKINS",env:["JENKINS_URL","BUILD_ID"],pr:{any:["ghprbPullId","CHANGE_ID"]}},{name:"LayerCI",constant:"LAYERCI",env:"LAYERCI",pr:"LAYERCI_PULL_REQUEST"},{name:"Magnum CI",constant:"MAGNUM",env:"MAGNUM"},{name:"Netlify CI",constant:"NETLIFY",env:"NETLIFY",pr:{env:"PULL_REQUEST",ne:"false"}},{name:"Nevercode",constant:"NEVERCODE",env:"NEVERCODE",pr:{env:"NEVERCODE_PULL_REQUEST",ne:"false"}},{name:"Prow",constant:"PROW",env:"PROW_JOB_ID"},{name:"ReleaseHub",constant:"RELEASEHUB",env:"RELEASE_BUILD_ID"},{name:"Render",constant:"RENDER",env:"RENDER",pr:{IS_PULL_REQUEST:"true"}},{name:"Sail CI",constant:"SAIL",env:"SAILCI",pr:"SAIL_PULL_REQUEST_NUMBER"},{name:"Screwdriver",constant:"SCREWDRIVER",env:"SCREWDRIVER",pr:{env:"SD_PULL_REQUEST",ne:"false"}},{name:"Semaphore",constant:"SEMAPHORE",env:"SEMAPHORE",pr:"PULL_REQUEST_NUMBER"},{name:"Sourcehut",constant:"SOURCEHUT",env:{CI_NAME:"sourcehut"}},{name:"Strider CD",constant:"STRIDER",env:"STRIDER"},{name:"TaskCluster",constant:"TASKCLUSTER",env:["TASK_ID","RUN_ID"]},{name:"TeamCity",constant:"TEAMCITY",env:"TEAMCITY_VERSION"},{name:"Travis CI",constant:"TRAVIS",env:"TRAVIS",pr:{env:"TRAVIS_PULL_REQUEST",ne:"false"}},{name:"Vela",constant:"VELA",env:"VELA",pr:{VELA_PULL_REQUEST:"1"}},{name:"Vercel",constant:"VERCEL",env:{any:["NOW_BUILDER","VERCEL"]},pr:"VERCEL_GIT_PULL_REQUEST_ID"},{name:"Visual Studio App Center",constant:"APPCENTER",env:"APPCENTER_BUILD_ID"},{name:"Woodpecker",constant:"WOODPECKER",env:{CI:"woodpecker"},pr:{CI_BUILD_EVENT:"pull_request"}},{name:"Xcode Cloud",constant:"XCODE_CLOUD",env:"CI_XCODE_PROJECT",pr:"CI_PULL_REQUEST_NUMBER"},{name:"Xcode Server",constant:"XCODE_SERVER",env:"XCS"}]});var gS=V(Ir=>{"use strict";var fS=pS(),Ye=process.env;Object.defineProperty(Ir,"_vendors",{value:fS.map(function(e){return e.constant})});Ir.name=null;Ir.isPR=null;Ir.id=null;Ye.CI!=="false"&&fS.forEach(function(e){let r=(Array.isArray(e.env)?e.env:[e.env]).every(function(n){return mS(n)});Ir[e.constant]=r,r&&(Ir.name=e.name,Ir.isPR=IR(e),Ir.id=e.constant)});Ir.isCI=!!(Ye.CI!=="false"&&(Ye.BUILD_ID||Ye.BUILD_NUMBER||Ye.CI||Ye.CI_APP_ID||Ye.CI_BUILD_ID||Ye.CI_BUILD_NUMBER||Ye.CI_NAME||Ye.CONTINUOUS_INTEGRATION||Ye.RUN_ID||Ir.name));function mS(e){return typeof e=="string"?!!Ye[e]:"env"in e?Ye[e.env]&&Ye[e.env].includes(e.includes):"any"in e?e.any.some(function(t){return!!Ye[t]}):Object.keys(e).every(function(t){return Ye[t]===e[t]})}s(mS,"checkEnv");function IR(e){switch(typeof e.pr){case"string":return!!Ye[e.pr];case"object":return"env"in e.pr?"any"in e.pr?e.pr.any.some(function(t){return Ye[e.pr.env]===t}):e.pr.env in Ye&&Ye[e.pr.env]!==e.pr.ne:"any"in e.pr?e.pr.any.some(function(t){return!!Ye[t]}):mS(e.pr);default:return null}}s(IR,"checkPR")});var SS=V((PG,vS)=>{var I=dS(),hS=gS(),TR=Ve("node:querystring"),{join:op}=Ve("node:path"),ca=process.platform==="win32",{readFileSync:_R}=Ve("node:fs"),AR=s(e=>{try{return _R(e,"utf8")}catch(t){if(t.code!=="ENOENT")throw t;return null}},"maybeReadFile"),kR=s(e=>{let t=e.include||[],r=e.omit||[],n=e.only;return/^prod(uction)?$/.test(n)||e.production?r.push("dev"):e.production===!1&&t.push("dev"),/^dev/.test(e.also)&&t.push("dev"),e.dev&&t.push("dev"),e.optional===!1?r.push("optional"):e.optional===!0&&t.push("optional"),e.omit=[...new Set(r)].filter(o=>!t.includes(o)),e.include=[...new Set(t)],e.omit.includes("dev")&&(process.env.NODE_ENV="production"),e.omit},"buildOmitList"),RR=process.env.EDITOR||process.env.VISUAL||(ca?`${process.env.SYSTEMROOT}\\notepad.exe`:"vi"),CR=ca?process.env.ComSpec||"cmd":process.env.SHELL||"sh",{networkInterfaces:DR}=Ve("node:os"),OR=s(()=>{try{return Object.values(DR()).map(e=>e.map(({address:t})=>t)).reduce((e,t)=>e.concat(t),[null])}catch{return[null]}},"getLocalAddresses"),MR=/UTF-?8$/i.test(process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG),PR=ca&&process.env.LOCALAPPDATA||"~",NR=ca?"npm-cache":".npm",LR=`${PR}/${NR}`,{semver:{type:yS},Umask:{type:FR},url:{type:la},path:{type:qr}}=As(),D=s((e,t,r)=>{let n=e.replace(/-([a-z])/g,(o,i)=>i.toUpperCase());r[n]=t[e]},"flatten"),Tr={_auth:new I("_auth",{default:null,type:[null,String],description:`
46
+ A basic-auth string to use when authenticating against the npm registry.
47
+ This will ONLY be used to authenticate against the npm registry. For other
48
+ registries you will need to scope it like "//other-registry.tld/:_auth"
49
+
50
+ Warning: This should generally not be set via a command-line option. It
51
+ is safer to use a registry-provided authentication bearer token stored in
52
+ the ~/.npmrc file by running \`npm login\`.
53
+ `,flatten:D}),access:new I("access",{default:null,defaultDescription:`
54
+ 'public' for new packages, existing packages it will not change the current level
55
+ `,type:[null,"restricted","public"],description:"\n If you do not want your scoped package to be publicly viewable (and\n installable) set `--access=restricted`.\n\n Unscoped packages cannot be set to `restricted`.\n\n Note: This defaults to not changing the current access level for existing\n packages. Specifying a value of `restricted` or `public` during\n publish will change the access for an existing package the same way that\n `npm access set status` would.\n ",flatten:D}),all:new I("all",{default:!1,type:Boolean,short:"a",description:"\n When running `npm outdated` and `npm ls`, setting `--all` will show\n all outdated or installed packages, rather than only those directly\n depended upon by the current project.\n ",flatten:D}),"allow-same-version":new I("allow-same-version",{default:!1,type:Boolean,description:`
56
+ Prevents throwing an error when \`npm version\` is used to set the new
57
+ version to the same value as the current version.
58
+ `,flatten:D}),"allow-git":new I("allow-git",{default:"all",type:["all","none","root"],description:"\n Limits the ability for npm to fetch dependencies from git references.\n That is, dependencies that point to a git repo instead of a version or semver range.\n Please note that this could leave your tree incomplete and some packages may not function as intended or designed.\n\n `all` allows any git dependencies to be fetched and installed.\n `none` prevents any git dependencies from being fetched and installed.\n `root` only allows git dependencies defined in your project's package.json to be fetched installed. Also allows git dependencies to be fetched for other commands like `npm view`\n ",flatten:D}),also:new I("also",{default:null,type:[null,"dev","development"],description:"\n When set to `dev` or `development`, this is an alias for\n `--include=dev`.\n ",deprecated:"Please use --include=dev instead.",flatten(e,t,r){Tr.omit.flatten("omit",t,r)}}),audit:new I("audit",{default:!0,type:Boolean,description:`
59
+ When "true" submit audit reports alongside the current npm command to the
60
+ default registry and all registries configured for scopes. See the
61
+ documentation for [\`npm audit\`](/commands/npm-audit) for details on what
62
+ is submitted.
63
+ `,flatten:D}),"audit-level":new I("audit-level",{default:null,type:[null,"info","low","moderate","high","critical","none"],description:`
64
+ The minimum level of vulnerability for \`npm audit\` to exit with
65
+ a non-zero exit code.
66
+ `,flatten:D}),"auth-type":new I("auth-type",{default:"web",type:["legacy","web"],description:"\n What authentication strategy to use with `login`.\n Note that if an `otp` config is given, this value will always be set to `legacy`.\n ",flatten:D}),before:new I("before",{default:null,hint:"<date>",type:[null,Date],exclusive:["min-release-age"],description:"\n If passed to `npm install`, will rebuild the npm tree such that only\n versions that were available **on or before** the given date are\n installed. If there are no versions available for the current set of\n dependencies, the command will error.\n\n If the requested version is a `dist-tag` and the given tag does not\n pass the `--before` filter, the most recent version less than or equal\n to that tag will be used. For example, `foo@latest` might install\n `foo@1.2` even though `latest` is `2.0`.\n ",flatten:D}),"bin-links":new I("bin-links",{default:!0,type:Boolean,description:`
67
+ Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package
68
+ executables.
69
+
70
+ Set to false to have it not do this. This can be used to work around the
71
+ fact that some file systems don't support symlinks, even on ostensibly
72
+ Unix systems.
73
+ `,flatten:D}),browser:new I("browser",{default:null,defaultDescription:'\n macOS: `"open"`, Windows: `"start"`, Others: `"xdg-open"`\n ',type:[null,Boolean,String],description:`
74
+ The browser that is called by npm commands to open websites.
75
+
76
+ Set to \`false\` to suppress browser behavior and instead print urls to
77
+ terminal.
78
+
79
+ Set to \`true\` to use default system URL opener.
80
+ `,flatten:D}),"bypass-2fa":new I("bypass-2fa",{default:!1,type:Boolean,description:`
81
+ When creating a Granular Access Token with \`npm token create\`,
82
+ setting this to true will allow the token to bypass two-factor
83
+ authentication. This is useful for automation and CI/CD workflows.
84
+ `,flatten:D}),ca:new I("ca",{default:null,type:[null,String,Array],description:`
85
+ The Certificate Authority signing certificate that is trusted for SSL
86
+ connections to the registry. Values should be in PEM format (Windows
87
+ calls it "Base-64 encoded X.509 (.CER)") with newlines replaced by the
88
+ string "\\n". For example:
89
+
90
+ \`\`\`ini
91
+ ca="-----BEGIN CERTIFICATE-----\\nXXXX\\nXXXX\\n-----END CERTIFICATE-----"
92
+ \`\`\`
93
+
94
+ Set to \`null\` to only allow "known" registrars, or to a specific CA
95
+ cert to trust only that specific signing authority.
96
+
97
+ Multiple CAs can be trusted by specifying an array of certificates:
98
+
99
+ \`\`\`ini
100
+ ca[]="..."
101
+ ca[]="..."
102
+ \`\`\`
103
+
104
+ See also the \`strict-ssl\` config.
105
+ `,flatten:D}),cache:new I("cache",{default:LR,defaultDescription:"\n Windows: `%LocalAppData%\\npm-cache`, Posix: `~/.npm`\n ",type:qr,description:`
106
+ The location of npm's cache directory.
107
+ `,flatten(e,t,r){r.cache=op(t.cache,"_cacache"),r.npxCache=op(t.cache,"_npx"),r.tufCache=op(t.cache,"_tuf")}}),"cache-max":new I("cache-max",{default:1/0,type:Number,description:"\n `--cache-max=0` is an alias for `--prefer-online`\n ",deprecated:"\n This option has been deprecated in favor of `--prefer-online`\n ",flatten(e,t,r){t[e]<=0&&(r.preferOnline=!0)}}),"cache-min":new I("cache-min",{default:0,type:Number,description:"\n `--cache-min=9999 (or bigger)` is an alias for `--prefer-offline`.\n ",deprecated:"\n This option has been deprecated in favor of `--prefer-offline`.\n ",flatten(e,t,r){t[e]>=9999&&(r.preferOffline=!0)}}),cafile:new I("cafile",{default:null,type:qr,description:`
108
+ A path to a file containing one or multiple Certificate Authority signing
109
+ certificates. Similar to the \`ca\` setting, but allows for multiple
110
+ CA's, as well as for the CA information to be stored in a file on disk.
111
+ `,flatten(e,t,r){if(!t.cafile)return;let n=AR(t.cafile);if(!n)return;let o="-----END CERTIFICATE-----";r.ca=n.replace(/\r\n/g,`
112
+ `).split(o).filter(i=>i.trim()).map(i=>i.trimLeft()+o)}}),call:new I("call",{default:"",type:String,short:"c",description:'\n Optional companion option for `npm exec`, `npx` that allows for\n specifying a custom command to be run along with the installed packages.\n\n ```bash\n npm exec --package yo --package generator-node --call "yo node"\n ```\n ',flatten:D}),cert:new I("cert",{default:null,type:[null,String],description:`
113
+ A client certificate to pass when accessing the registry. Values should
114
+ be in PEM format (Windows calls it "Base-64 encoded X.509 (.CER)") with
115
+ newlines replaced by the string "\\n". For example:
116
+
117
+ \`\`\`ini
118
+ cert="-----BEGIN CERTIFICATE-----\\nXXXX\\nXXXX\\n-----END CERTIFICATE-----"
119
+ \`\`\`
120
+
121
+ It is _not_ the path to a certificate file, though you can set a registry-scoped
122
+ "certfile" path like "//other-registry.tld/:certfile=/path/to/cert.pem".
123
+ `,deprecated:"\n `key` and `cert` are no longer used for most registry operations.\n Use registry scoped `keyfile` and `certfile` instead.\n Example:\n //other-registry.tld/:keyfile=/path/to/key.pem\n //other-registry.tld/:certfile=/path/to/cert.crt\n ",flatten:D}),cidr:new I("cidr",{default:null,type:[null,String,Array],description:`
124
+ This is a list of CIDR address to be used when configuring limited access
125
+ tokens with the \`npm token create\` command.
126
+ `,flatten:D}),color:new I("color",{default:!process.env.NO_COLOR||process.env.NO_COLOR==="0",usage:"--color|--no-color|--color always",defaultDescription:`
127
+ true unless the NO_COLOR environ is set to something other than '0'
128
+ `,type:["always",Boolean],description:`
129
+ If false, never shows colors. If \`"always"\` then always shows colors.
130
+ If true, then only prints color codes for tty file descriptors.
131
+ `,flatten(e,t,r){r.color=t.color?t.color==="always"?!0:!!process.stdout.isTTY:!1,r.logColor=t.color?t.color==="always"?!0:!!process.stderr.isTTY:!1}}),"commit-hooks":new I("commit-hooks",{default:!0,type:Boolean,description:"\n Run git commit hooks when using the `npm version` command.\n ",flatten:D}),cpu:new I("cpu",{default:null,type:[null,String],description:"\n Override CPU architecture of native modules to install.\n Acceptable values are same as `cpu` field of package.json,\n which comes from `process.arch`.\n ",flatten:D}),depth:new I("depth",{default:null,defaultDescription:"\n `Infinity` if `--all` is set; otherwise, `0`\n ",type:[null,Number],description:"\n The depth to go when recursing packages for `npm ls`.\n\n If not set, `npm ls` will show only the immediate dependencies of the\n root project. If `--all` is set, then npm will show all dependencies\n by default.\n ",flatten:D}),description:new I("description",{default:!0,type:Boolean,usage:"--no-description",description:"\n Show the description in `npm search`\n ",flatten(e,t,r){r.search=r.search||{limit:20},r.search[e]=t[e]}}),dev:new I("dev",{default:!1,type:Boolean,description:"\n Alias for `--include=dev`.\n ",deprecated:"Please use --include=dev instead.",flatten(e,t,r){Tr.omit.flatten("omit",t,r)}}),diff:new I("diff",{default:[],hint:"<package-spec>",type:[String,Array],description:"\n Define arguments to compare in `npm diff`.\n ",flatten:D}),"diff-ignore-all-space":new I("diff-ignore-all-space",{default:!1,type:Boolean,description:"\n Ignore whitespace when comparing lines in `npm diff`.\n ",flatten:D}),"diff-name-only":new I("diff-name-only",{default:!1,type:Boolean,description:"\n Prints only filenames when using `npm diff`.\n ",flatten:D}),"diff-no-prefix":new I("diff-no-prefix",{default:!1,type:Boolean,description:"\n Do not show any source or destination prefix in `npm diff` output.\n\n Note: this causes `npm diff` to ignore the `--diff-src-prefix` and\n `--diff-dst-prefix` configs.\n ",flatten:D}),"diff-dst-prefix":new I("diff-dst-prefix",{default:"b/",hint:"<path>",type:String,description:"\n Destination prefix to be used in `npm diff` output.\n ",flatten:D}),"diff-src-prefix":new I("diff-src-prefix",{default:"a/",hint:"<path>",type:String,description:"\n Source prefix to be used in `npm diff` output.\n ",flatten:D}),"diff-text":new I("diff-text",{default:!1,type:Boolean,description:"\n Treat all files as text in `npm diff`.\n ",flatten:D}),"diff-unified":new I("diff-unified",{default:3,type:Number,description:"\n The number of lines of context to print in `npm diff`.\n ",flatten:D}),"dry-run":new I("dry-run",{default:!1,type:Boolean,description:"\n Indicates that you don't want npm to make any changes and that it should\n only report what it would have done. This can be passed into any of the\n commands that modify your local installation, eg, `install`,\n `update`, `dedupe`, `uninstall`, as well as `pack` and\n `publish`.\n\n Note: This is NOT honored by other network related commands, eg\n `dist-tags`, `owner`, etc.\n ",flatten:D}),editor:new I("editor",{default:RR,defaultDescription:`
132
+ The EDITOR or VISUAL environment variables, or '%SYSTEMROOT%\\notepad.exe' on Windows,
133
+ or 'vi' on Unix systems
134
+ `,type:String,description:"\n The command to run for `npm edit` and `npm config edit`.\n ",flatten:D}),"engine-strict":new I("engine-strict",{default:!1,type:Boolean,description:`
135
+ If set to true, then npm will stubbornly refuse to install (or even
136
+ consider installing) any package that claims to not be compatible with
137
+ the current Node.js version.
138
+
139
+ This can be overridden by setting the \`--force\` flag.
140
+ `,flatten:D}),"expect-result-count":new I("expect-result-count",{default:null,type:[null,Number],hint:"<count>",exclusive:["expect-results"],description:`
141
+ Tells to expect a specific number of results from the command.
142
+ `}),"expect-results":new I("expect-results",{default:null,type:[null,Boolean],exclusive:["expect-result-count"],description:`
143
+ Tells npm whether or not to expect results from the command.
144
+ Can be either true (expect some results) or false (expect no results).
145
+ `}),expires:new I("expires",{default:null,type:[null,Number],description:`
146
+ When creating a Granular Access Token with \`npm token create\`,
147
+ this sets the expiration in days. If not specified, the server
148
+ will determine the default expiration.
149
+ `,flatten:D}),"fetch-retries":new I("fetch-retries",{default:2,type:Number,description:`
150
+ The "retries" config for the \`retry\` module to use when fetching
151
+ packages from the registry.
152
+
153
+ npm will retry idempotent read requests to the registry in the case
154
+ of network failures or 5xx HTTP errors.
155
+ `,flatten(e,t,r){r.retry=r.retry||{},r.retry.retries=t[e]}}),"fetch-retry-factor":new I("fetch-retry-factor",{default:10,type:Number,description:`
156
+ The "factor" config for the \`retry\` module to use when fetching
157
+ packages.
158
+ `,flatten(e,t,r){r.retry=r.retry||{},r.retry.factor=t[e]}}),"fetch-retry-maxtimeout":new I("fetch-retry-maxtimeout",{default:6e4,defaultDescription:"60000 (1 minute)",type:Number,description:`
159
+ The "maxTimeout" config for the \`retry\` module to use when fetching
160
+ packages.
161
+ `,flatten(e,t,r){r.retry=r.retry||{},r.retry.maxTimeout=t[e]}}),"fetch-retry-mintimeout":new I("fetch-retry-mintimeout",{default:1e4,defaultDescription:"10000 (10 seconds)",type:Number,description:`
162
+ The "minTimeout" config for the \`retry\` module to use when fetching
163
+ packages.
164
+ `,flatten(e,t,r){r.retry=r.retry||{},r.retry.minTimeout=t[e]}}),"fetch-timeout":new I("fetch-timeout",{default:300*1e3,defaultDescription:`${300*1e3} (5 minutes)`,type:Number,description:`
165
+ The maximum amount of time to wait for HTTP requests to complete.
166
+ `,flatten(e,t,r){r.timeout=t[e]}}),force:new I("force",{default:!1,type:Boolean,short:"f",description:`
167
+ Removes various protections against unfortunate side effects, common
168
+ mistakes, unnecessary performance degradation, and malicious input.
169
+
170
+ * Allow clobbering non-npm files in global installs.
171
+ * Allow the \`npm version\` command to work on an unclean git repository.
172
+ * Allow deleting the cache folder with \`npm cache clean\`.
173
+ * Allow installing packages that have an \`engines\` declaration
174
+ requiring a different version of npm.
175
+ * Allow installing packages that have an \`engines\` declaration
176
+ requiring a different version of \`node\`, even if \`--engine-strict\`
177
+ is enabled.
178
+ * Allow \`npm audit fix\` to install modules outside your stated
179
+ dependency range (including SemVer-major changes).
180
+ * Allow unpublishing all versions of a published package.
181
+ * Allow conflicting peerDependencies to be installed in the root project.
182
+ * Implicitly set \`--yes\` during \`npm init\`.
183
+ * Allow clobbering existing values in \`npm pkg\`
184
+ * Allow unpublishing of entire packages (not just a single version).
185
+
186
+ If you don't have a clear idea of what you want to do, it is strongly
187
+ recommended that you do not use this option!
188
+ `,flatten:D}),"foreground-scripts":new I("foreground-scripts",{default:!1,defaultDescription:"`false` unless when using `npm pack` or `npm publish` where it\n defaults to `true`",type:Boolean,description:`
189
+ Run all build scripts (ie, \`preinstall\`, \`install\`, and
190
+ \`postinstall\`) scripts for installed packages in the foreground
191
+ process, sharing standard input, output, and error with the main npm
192
+ process.
193
+
194
+ Note that this will generally make installs run slower, and be much
195
+ noisier, but can be useful for debugging.
196
+ `,flatten:D}),"format-package-lock":new I("format-package-lock",{default:!0,type:Boolean,description:"\n Format `package-lock.json` or `npm-shrinkwrap.json` as a human\n readable file.\n ",flatten:D}),fund:new I("fund",{default:!0,type:Boolean,description:'\n When "true" displays the message at the end of each `npm install`\n acknowledging the number of dependencies looking for funding.\n See [`npm fund`](/commands/npm-fund) for details.\n ',flatten:D}),git:new I("git",{default:"git",type:String,description:`
197
+ The command to use for git commands. If git is installed on the
198
+ computer, but is not in the \`PATH\`, then set this to the full path to
199
+ the git binary.
200
+ `,flatten:D}),"git-tag-version":new I("git-tag-version",{default:!0,type:Boolean,description:`
201
+ Tag the commit when using the \`npm version\` command. Setting this to
202
+ false results in no commit being made at all.
203
+ `,flatten:D}),global:new I("global",{default:!1,type:Boolean,short:"g",description:`
204
+ Operates in "global" mode, so that packages are installed into the
205
+ \`prefix\` folder instead of the current working directory. See
206
+ [folders](/configuring-npm/folders) for more on the differences in
207
+ behavior.
208
+
209
+ * packages are installed into the \`{prefix}/lib/node_modules\` folder,
210
+ instead of the current working directory.
211
+ * bin files are linked to \`{prefix}/bin\`
212
+ * man pages are linked to \`{prefix}/share/man\`
213
+ `,flatten:s((e,t,r)=>{D(e,t,r),r.global&&(r.location="global")},"flatten")}),globalconfig:new I("globalconfig",{type:qr,default:"",defaultDescription:`
214
+ The global --prefix setting plus 'etc/npmrc'. For example,
215
+ '/usr/local/etc/npmrc'
216
+ `,description:`
217
+ The config file to read for global config options.
218
+ `,flatten:D}),"global-style":new I("global-style",{default:!1,type:Boolean,description:"\n Only install direct dependencies in the top level `node_modules`,\n but hoist on deeper dependencies.\n Sets `--install-strategy=shallow`.\n ",deprecated:"\n This option has been deprecated in favor of `--install-strategy=shallow`\n ",flatten(e,t,r){t[e]&&(t["install-strategy"]="shallow",r.installStrategy="shallow")}}),heading:new I("heading",{default:"npm",type:String,description:`
219
+ The string that starts all the debugging log output.
220
+ `,flatten:D}),"https-proxy":new I("https-proxy",{default:null,type:[null,la],description:"\n A proxy to use for outgoing https requests. If the `HTTPS_PROXY` or\n `https_proxy` or `HTTP_PROXY` or `http_proxy` environment variables\n are set, proxy settings will be honored by the underlying\n `make-fetch-happen` library.\n ",flatten:D}),"if-present":new I("if-present",{default:!1,type:Boolean,envExport:!1,description:`
221
+ If true, npm will not exit with an error code when \`run\` is
222
+ invoked for a script that isn't defined in the \`scripts\` section of
223
+ \`package.json\`. This option can be used when it's desirable to
224
+ optionally run a script when it's present and fail if the script fails.
225
+ This is useful, for example, when running scripts that may only apply for
226
+ some builds in an otherwise generic CI setup.
227
+ `,flatten:D}),"ignore-scripts":new I("ignore-scripts",{default:!1,type:Boolean,description:"\n If true, npm does not run scripts specified in package.json files.\n\n Note that commands explicitly intended to run a particular script, such\n as `npm start`, `npm stop`, `npm restart`, `npm test`, and `npm\n run` will still run their intended script if `ignore-scripts` is\n set, but they will *not* run any pre- or post-scripts.\n ",flatten:D}),include:new I("include",{default:[],type:[Array,"prod","dev","optional","peer"],description:`
228
+ Option that allows for defining which types of dependencies to install.
229
+
230
+ This is the inverse of \`--omit=<type>\`.
231
+
232
+ Dependency types specified in \`--include\` will not be omitted,
233
+ regardless of the order in which omit/include are specified on the
234
+ command-line.
235
+ `,flatten(e,t,r){Tr.omit.flatten("omit",t,r)}}),"include-staged":new I("include-staged",{default:!1,type:Boolean,description:`
236
+ Allow installing "staged" published packages, as defined by [npm RFC PR
237
+ #92](https://github.com/npm/rfcs/pull/92).
238
+
239
+ This is experimental, and not implemented by the npm public registry.
240
+ `,flatten:D}),"include-workspace-root":new I("include-workspace-root",{default:!1,type:Boolean,envExport:!1,description:`
241
+ Include the workspace root when workspaces are enabled for a command.
242
+
243
+ When false, specifying individual workspaces via the \`workspace\` config,
244
+ or all workspaces via the \`workspaces\` flag, will cause npm to operate only
245
+ on the specified workspaces, and not on the root project.
246
+ `,flatten:D}),"include-attestations":new I("include-attestations",{default:!1,type:Boolean,description:`
247
+ When used with \`npm audit signatures --json\`, includes the full
248
+ sigstore attestation bundles in the JSON output for each verified
249
+ package. The bundles contain DSSE envelopes, verification material,
250
+ and transparency log entries.
251
+ `,flatten:D}),"init-author-email":new I("init-author-email",{default:"",hint:"<email>",type:String,description:`
252
+ The value \`npm init\` should use by default for the package author's
253
+ email.
254
+ `}),"init-author-name":new I("init-author-name",{default:"",hint:"<name>",type:String,description:"\n The value `npm init` should use by default for the package author's name.\n "}),"init-author-url":new I("init-author-url",{default:"",type:["",la],hint:"<url>",description:"\n The value `npm init` should use by default for the package author's homepage.\n "}),"init-license":new I("init-license",{default:"ISC",hint:"<license>",type:String,description:"\n The value `npm init` should use by default for the package license.\n "}),"init-module":new I("init-module",{default:"~/.npm-init.js",type:qr,hint:"<module>",description:`
255
+ A module that will be loaded by the \`npm init\` command. See the
256
+ documentation for the
257
+ [init-package-json](https://github.com/npm/init-package-json) module for
258
+ more information, or [npm init](/commands/npm-init).
259
+ `}),"init-type":new I("init-type",{default:"commonjs",type:String,hint:"<type>",description:"\n The value that `npm init` should use by default for the package.json type field.\n "}),"init-version":new I("init-version",{default:"1.0.0",type:yS,hint:"<version>",description:`
260
+ The value that \`npm init\` should use by default for the package
261
+ version number, if not already set in package.json.
262
+ `}),"init-private":new I("init-private",{default:!1,type:Boolean,description:"\n The value `npm init` should use by default for the package's private flag.\n ",flatten:D}),"init.author.email":new I("init.author.email",{default:"",type:String,deprecated:"\n Use `--init-author-email` instead.",description:"\n Alias for `--init-author-email`\n "}),"init.author.name":new I("init.author.name",{default:"",type:String,deprecated:"\n Use `--init-author-name` instead.\n ",description:"\n Alias for `--init-author-name`\n "}),"init.author.url":new I("init.author.url",{default:"",type:["",la],deprecated:"\n Use `--init-author-url` instead.\n ",description:"\n Alias for `--init-author-url`\n "}),"init.license":new I("init.license",{default:"ISC",type:String,deprecated:"\n Use `--init-license` instead.\n ",description:"\n Alias for `--init-license`\n "}),"init.module":new I("init.module",{default:"~/.npm-init.js",type:qr,deprecated:"\n Use `--init-module` instead.\n ",description:"\n Alias for `--init-module`\n "}),"init.version":new I("init.version",{default:"1.0.0",type:yS,deprecated:"\n Use `--init-version` instead.\n ",description:"\n Alias for `--init-version`\n "}),"install-links":new I("install-links",{default:!1,type:Boolean,description:`
263
+ When set file: protocol dependencies will be packed and installed as
264
+ regular dependencies instead of creating a symlink. This option has
265
+ no effect on workspaces.
266
+ `,flatten:D}),"install-strategy":new I("install-strategy",{default:"hoisted",type:["hoisted","nested","shallow","linked"],description:`
267
+ Sets the strategy for installing packages in node_modules.
268
+ hoisted (default): Install non-duplicated in top-level, and duplicated as
269
+ necessary within directory structure.
270
+ nested: (formerly --legacy-bundling) install in place, no hoisting.
271
+ shallow (formerly --global-style) only install direct deps at top-level.
272
+ linked: (experimental) install in node_modules/.store, link in place,
273
+ unhoisted.
274
+ `,flatten:D}),json:new I("json",{default:!1,type:Boolean,description:`
275
+ Whether or not to output JSON data, rather than the normal output.
276
+
277
+ * In \`npm pkg set\` it enables parsing set values with JSON.parse()
278
+ before saving them to your \`package.json\`.
279
+
280
+ Not supported by all npm commands.
281
+ `,flatten:D}),key:new I("key",{default:null,type:[null,String],description:`
282
+ A client key to pass when accessing the registry. Values should be in
283
+ PEM format with newlines replaced by the string "\\n". For example:
284
+
285
+ \`\`\`ini
286
+ key="-----BEGIN PRIVATE KEY-----\\nXXXX\\nXXXX\\n-----END PRIVATE KEY-----"
287
+ \`\`\`
288
+
289
+ It is _not_ the path to a key file, though you can set a registry-scoped
290
+ "keyfile" path like "//other-registry.tld/:keyfile=/path/to/key.pem".
291
+ `,deprecated:"\n `key` and `cert` are no longer used for most registry operations.\n Use registry scoped `keyfile` and `certfile` instead.\n Example:\n //other-registry.tld/:keyfile=/path/to/key.pem\n //other-registry.tld/:certfile=/path/to/cert.crt\n ",flatten:D}),"legacy-bundling":new I("legacy-bundling",{default:!1,type:Boolean,description:`
292
+ Instead of hoisting package installs in \`node_modules\`, install packages
293
+ in the same manner that they are depended on. This may cause very deep
294
+ directory structures and duplicate package installs as there is no
295
+ de-duplicating.
296
+ Sets \`--install-strategy=nested\`.
297
+ `,deprecated:"\n This option has been deprecated in favor of `--install-strategy=nested`\n ",flatten(e,t,r){t[e]&&(t["install-strategy"]="nested",r.installStrategy="nested")}}),"legacy-peer-deps":new I("legacy-peer-deps",{default:!1,type:Boolean,description:"\n Causes npm to completely ignore `peerDependencies` when building a\n package tree, as in npm versions 3 through 6.\n\n If a package cannot be installed because of overly strict\n `peerDependencies` that collide, it provides a way to move forward\n resolving the situation.\n\n This differs from `--omit=peer`, in that `--omit=peer` will avoid\n unpacking `peerDependencies` on disk, but will still design a tree such\n that `peerDependencies` _could_ be unpacked in a correct place.\n\n Use of `legacy-peer-deps` is not recommended, as it will not enforce\n the `peerDependencies` contract that meta-dependencies may rely on.\n ",flatten:D}),libc:new I("libc",{default:null,type:[null,String],description:`
298
+ Override libc of native modules to install.
299
+ Acceptable values are same as \`libc\` field of package.json
300
+ `,flatten:D}),link:new I("link",{default:!1,type:Boolean,description:`
301
+ Used with \`npm ls\`, limiting output to only those packages that are
302
+ linked.
303
+ `}),"local-address":new I("local-address",{default:null,type:OR(),typeDescription:"IP Address",description:`
304
+ The IP address of the local interface to use when making connections to
305
+ the npm registry. Must be IPv4 in versions of Node prior to 0.12.
306
+ `,flatten:D}),location:new I("location",{default:"user",short:"L",type:["global","user","project"],defaultDescription:'\n "user" unless `--global` is passed, which will also set this value to "global"\n ',description:`
307
+ When passed to \`npm config\` this refers to which config file to use.
308
+
309
+ When set to "global" mode, packages are installed into the \`prefix\` folder
310
+ instead of the current working directory. See
311
+ [folders](/configuring-npm/folders) for more on the differences in behavior.
312
+
313
+ * packages are installed into the \`{prefix}/lib/node_modules\` folder,
314
+ instead of the current working directory.
315
+ * bin files are linked to \`{prefix}/bin\`
316
+ * man pages are linked to \`{prefix}/share/man\`
317
+ `,flatten:s((e,t,r)=>{D(e,t,r),r.global&&(r.location="global"),t.location==="global"&&(r.global=!0)},"flatten")}),"lockfile-version":new I("lockfile-version",{default:null,type:[null,1,2,3,"1","2","3"],defaultDescription:`
318
+ Version 3 if no lockfile, auto-converting v1 lockfiles to v3; otherwise,
319
+ maintain current lockfile version.`,description:`
320
+ Set the lockfile format version to be used in package-lock.json and
321
+ npm-shrinkwrap-json files. Possible options are:
322
+
323
+ 1: The lockfile version used by npm versions 5 and 6. Lacks some data that
324
+ is used during the install, resulting in slower and possibly less
325
+ deterministic installs. Prevents lockfile churn when interoperating with
326
+ older npm versions.
327
+
328
+ 2: The default lockfile version used by npm version 7 and 8. Includes both
329
+ the version 1 lockfile data and version 3 lockfile data, for maximum
330
+ determinism and interoperability, at the expense of more bytes on disk.
331
+
332
+ 3: Only the new lockfile information introduced in npm version 7. Smaller
333
+ on disk than lockfile version 2, but not interoperable with older npm
334
+ versions. Ideal if all users are on npm version 7 and higher.
335
+ `,flatten:s((e,t,r)=>{r.lockfileVersion=t[e]&&parseInt(t[e],10)},"flatten")}),loglevel:new I("loglevel",{default:"notice",type:["silent","error","warn","notice","http","info","verbose","silly"],description:`
336
+ What level of logs to report. All logs are written to a debug log,
337
+ with the path to that file printed if the execution of a command fails.
338
+
339
+ Any logs of a higher level than the setting are shown. The default is
340
+ "notice".
341
+
342
+ See also the \`foreground-scripts\` config.
343
+ `,flatten(e,t,r){r.silent=t[e]==="silent"}}),"logs-dir":new I("logs-dir",{default:null,type:[null,qr],defaultDescription:"\n A directory named `_logs` inside the cache\n ",description:`
344
+ The location of npm's log directory. See [\`npm
345
+ logging\`](/using-npm/logging) for more information.
346
+ `}),"logs-max":new I("logs-max",{default:10,type:Number,description:`
347
+ The maximum number of log files to store.
348
+
349
+ If set to 0, no log files will be written for the current run.
350
+ `}),long:new I("long",{default:!1,type:Boolean,short:"l",description:"\n Show extended information in `ls`, `search`, and `help-search`.\n "}),name:new I("name",{default:null,type:[null,String],hint:"<name>",description:`
351
+ When creating a Granular Access Token with \`npm token create\`,
352
+ this sets the name/description for the token.
353
+ `,flatten:D}),maxsockets:new I("maxsockets",{default:15,type:Number,description:`
354
+ The maximum number of connections to use per origin (protocol/host/port
355
+ combination).
356
+ `,flatten(e,t,r){r.maxSockets=t[e]}}),message:new I("message",{default:"%s",type:String,short:"m",description:`
357
+ Commit message which is used by \`npm version\` when creating version commit.
358
+
359
+ Any "%s" in the message will be replaced with the version number.
360
+ `,flatten:D}),"min-release-age":new I("min-release-age",{default:null,hint:"<days>",type:[null,Number],exclusive:["before"],envExport:!1,description:`
361
+ If set, npm will build the npm tree such that only versions that were
362
+ available more than the given number of days ago will be installed. If
363
+ there are no versions available for the current set of dependencies, the
364
+ command will error.
365
+
366
+ This flag is a complement to \`before\`, which accepts an exact date
367
+ instead of a relative number of days.
368
+ `,flatten:s((e,t,r)=>{t["min-release-age"]!==null&&(r.before=new Date(Date.now()-864e5*t["min-release-age"]),t.before=r.before,delete t["min-release-age"])},"flatten")}),"node-gyp":new I("node-gyp",{default:(()=>{try{return Ve.resolve("node-gyp/bin/node-gyp.js")}catch{return""}})(),defaultDescription:`
369
+ The path to the node-gyp bin that ships with npm
370
+ `,type:qr,description:`
371
+ This is the location of the "node-gyp" bin. By default it uses one that ships with npm itself.
372
+
373
+ You can use this config to specify your own "node-gyp" to run when it is required to build a package.
374
+ `,flatten:D}),"node-options":new I("node-options",{default:null,type:[null,String],description:`
375
+ Options to pass through to Node.js via the \`NODE_OPTIONS\` environment
376
+ variable. This does not impact how npm itself is executed but it does
377
+ impact how lifecycle scripts are called.
378
+ `}),noproxy:new I("noproxy",{default:"",defaultDescription:`
379
+ The value of the NO_PROXY environment variable
380
+ `,type:[String,Array],description:`
381
+ Domain extensions that should bypass any proxies.
382
+
383
+ Also accepts a comma-delimited string.
384
+ `,flatten(e,t,r){Array.isArray(t[e])?r.noProxy=t[e].join(","):r.noProxy=t[e]}}),offline:new I("offline",{default:!1,type:Boolean,description:`
385
+ Force offline mode: no network requests will be done during install. To allow
386
+ the CLI to fill in missing cache data, see \`--prefer-offline\`.
387
+ `,flatten:D}),omit:new I("omit",{default:process.env.NODE_ENV==="production"?["dev"]:[],defaultDescription:`
388
+ 'dev' if the \`NODE_ENV\` environment variable is set to 'production';
389
+ otherwise, empty.
390
+ `,type:[Array,"dev","optional","peer"],description:"\n Dependency types to omit from the installation tree on disk.\n\n Note that these dependencies _are_ still resolved and added to the\n `package-lock.json` or `npm-shrinkwrap.json` file. They are just\n not physically installed on disk.\n\n If a package type appears in both the `--include` and `--omit`\n lists, then it will be included.\n\n If the resulting omit list includes `'dev'`, then the `NODE_ENV`\n environment variable will be set to `'production'` for all lifecycle\n scripts.\n ",flatten(e,t,r){r.omit=kR(t)}}),"omit-lockfile-registry-resolved":new I("omit-lockfile-registry-resolved",{default:!1,type:Boolean,description:`
391
+ This option causes npm to create lock files without a \`resolved\` key for
392
+ registry dependencies. Subsequent installs will need to resolve tarball
393
+ endpoints with the configured registry, likely resulting in a longer install
394
+ time.
395
+ `,flatten:D}),only:new I("only",{default:null,type:[null,"prod","production"],deprecated:"\n Use `--omit=dev` to omit dev dependencies from the install.\n ",description:"\n When set to `prod` or `production`, this is an alias for\n `--omit=dev`.\n ",flatten(e,t,r){Tr.omit.flatten("omit",t,r)}}),orgs:new I("orgs",{default:null,type:[null,String,Array],description:`
396
+ When creating a Granular Access Token with \`npm token create\`,
397
+ this limits the token access to specific organizations.
398
+ `,flatten:D}),optional:new I("optional",{default:null,type:[null,Boolean],deprecated:`
399
+ Use \`--omit=optional\` to exclude optional dependencies, or
400
+ \`--include=optional\` to include them.
401
+
402
+ Default value does install optional deps unless otherwise omitted.
403
+ `,description:`
404
+ Alias for --include=optional or --omit=optional
405
+ `,flatten(e,t,r){Tr.omit.flatten("omit",t,r)}}),os:new I("os",{default:null,type:[null,String],description:"\n Override OS of native modules to install.\n Acceptable values are same as `os` field of package.json,\n which comes from `process.platform`.\n ",flatten:D}),otp:new I("otp",{default:null,type:[null,String],description:`
406
+ This is a one-time password from a two-factor authenticator. It's needed
407
+ when publishing or changing package permissions with \`npm access\`.
408
+
409
+ If not set, and a registry response fails with a challenge for a one-time
410
+ password, npm will prompt on the command line for one.
411
+ `,flatten(e,t,r){D(e,t,r),t.otp&&(t["auth-type"]="legacy",D("auth-type",t,r))}}),package:new I("package",{default:[],hint:"<package-spec>",type:[String,Array],description:"\n The package or packages to install for [`npm exec`](/commands/npm-exec)\n ",flatten:D}),"package-lock":new I("package-lock",{default:!0,type:Boolean,description:"\n If set to false, then ignore `package-lock.json` files when installing.\n This will also prevent _writing_ `package-lock.json` if `save` is\n true.\n ",flatten:s((e,t,r)=>{D(e,t,r),r.packageLockOnly&&(r.packageLock=!0)},"flatten")}),"package-lock-only":new I("package-lock-only",{default:!1,type:Boolean,description:"\n If set to true, the current operation will only use the `package-lock.json`,\n ignoring `node_modules`.\n\n For `update` this means only the `package-lock.json` will be updated,\n instead of checking `node_modules` and downloading dependencies.\n\n For `list` this means the output will be based on the tree described by the\n `package-lock.json`, rather than the contents of `node_modules`.\n ",flatten:s((e,t,r)=>{D(e,t,r),r.packageLockOnly&&(r.packageLock=!0)},"flatten")}),"pack-destination":new I("pack-destination",{default:".",type:String,description:"\n Directory in which `npm pack` will save tarballs.\n ",flatten:D}),packages:new I("packages",{default:[],type:[null,String,Array],description:`
412
+ When creating a Granular Access Token with \`npm token create\`,
413
+ this limits the token access to specific packages.
414
+ `,flatten:D}),parseable:new I("parseable",{default:!1,type:Boolean,short:"p",description:`
415
+ Output parseable results from commands that write to standard output. For
416
+ \`npm search\`, this will be tab-separated table format.
417
+ `,flatten:D}),"prefer-dedupe":new I("prefer-dedupe",{default:!1,type:Boolean,description:`
418
+ Prefer to deduplicate packages if possible, rather than
419
+ choosing a newer version of a dependency.
420
+ `,flatten:D}),"prefer-offline":new I("prefer-offline",{default:!1,type:Boolean,description:`
421
+ If true, staleness checks for cached data will be bypassed, but missing
422
+ data will be requested from the server. To force full offline mode, use
423
+ \`--offline\`.
424
+ `,flatten:D}),"prefer-online":new I("prefer-online",{default:!1,type:Boolean,description:`
425
+ If true, staleness checks for cached data will be forced, making the CLI
426
+ look for updates immediately even for fresh package data.
427
+ `,flatten:D}),prefix:new I("prefix",{type:qr,short:"C",default:"",defaultDescription:`
428
+ In global mode, the folder where the node executable is installed.
429
+ Otherwise, the nearest parent folder containing either a package.json
430
+ file or a node_modules folder.
431
+ `,description:`
432
+ The location to install global items. If set on the command line, then
433
+ it forces non-global commands to run in the specified folder.
434
+ `}),preid:new I("preid",{default:"",hint:"prerelease-id",type:String,description:'\n The "prerelease identifier" to use as a prefix for the "prerelease" part\n of a semver. Like the `rc` in `1.2.0-rc.8`.\n ',flatten:D}),production:new I("production",{default:null,type:[null,Boolean],deprecated:"Use `--omit=dev` instead.",description:"Alias for `--omit=dev`",flatten(e,t,r){Tr.omit.flatten("omit",t,r)}}),progress:new I("progress",{default:!(hS.isCI||!process.stderr.isTTY||!process.stdout.isTTY||process.env.TERM==="dumb"),defaultDescription:"\n `true` when not in CI and both stderr and stdout are TTYs and not in a dumb terminal\n ",type:Boolean,description:"\n When set to `true`, npm will display a progress bar during time\n intensive operations, if `process.stderr` and `process.stdout` are a TTY.\n\n Set to `false` to suppress the progress bar.\n ",flatten(e,t,r){r.progress=!!t.progress&&!!process.stderr.isTTY&&!!process.stdout.isTTY&&process.env.TERM!=="dumb"}}),provenance:new I("provenance",{default:!1,type:Boolean,exclusive:["provenance-file"],description:`
435
+ When publishing from a supported cloud CI/CD system, the package will be
436
+ publicly linked to where it was built and published from.
437
+ `,flatten:D}),"provenance-file":new I("provenance-file",{default:null,type:qr,hint:"<file>",exclusive:["provenance"],description:`
438
+ When publishing, the provenance bundle at the given path will be used.
439
+ `,flatten:D}),proxy:new I("proxy",{default:null,type:[null,!1,la],description:"\n A proxy to use for outgoing http requests. If the `HTTP_PROXY` or\n `http_proxy` environment variables are set, proxy settings will be\n honored by the underlying `request` library.\n ",flatten:D}),"read-only":new I("read-only",{default:!1,type:Boolean,description:`
440
+ This is used to mark a token as unable to publish when configuring
441
+ limited access tokens with the \`npm token create\` command.
442
+ `,flatten:D}),"rebuild-bundle":new I("rebuild-bundle",{default:!0,type:Boolean,description:`
443
+ Rebuild bundled dependencies after installation.
444
+ `,flatten:D}),registry:new I("registry",{default:"https://registry.npmjs.org/",type:la,description:`
445
+ The base URL of the npm registry.
446
+ `,flatten:D}),"replace-registry-host":new I("replace-registry-host",{default:"npmjs",hint:"<npmjs|never|always> | hostname",type:["npmjs","never","always",String],description:`
447
+ Defines behavior for replacing the registry host in a lockfile with the
448
+ configured registry.
449
+
450
+ The default behavior is to replace package dist URLs from the default
451
+ registry (https://registry.npmjs.org) to the configured registry. If set to
452
+ "never", then use the registry value. If set to "always", then replace the
453
+ registry host with the configured host every time.
454
+
455
+ You may also specify a bare hostname (e.g., "registry.npmjs.org").
456
+ `,flatten:D}),save:new I("save",{default:!0,defaultDescription:"`true` unless when using `npm update` where it\n defaults to `false`",usage:"-S|--save|--no-save|--save-prod|--save-dev|--save-optional|--save-peer|--save-bundle",type:Boolean,short:"S",description:"\n Save installed packages to a `package.json` file as dependencies.\n\n When used with the `npm rm` command, removes the dependency from\n `package.json`.\n\n Will also prevent writing to `package-lock.json` if set to `false`.\n ",flatten:D}),"save-bundle":new I("save-bundle",{default:!1,type:Boolean,short:"B",description:"\n If a package would be saved at install time by the use of `--save`,\n `--save-dev`, or `--save-optional`, then also put it in the\n `bundleDependencies` list.\n\n Ignored if `--save-peer` is set, since peerDependencies cannot be bundled.\n ",flatten(e,t,r){r.saveBundle=t["save-bundle"]&&!t["save-peer"]}}),"save-dev":new I("save-dev",{default:!1,type:Boolean,short:"D",exclusive:["save-optional","save-peer","save-prod"],description:"\n Save installed packages to a package.json file as `devDependencies`.\n ",flatten(e,t,r){if(!t[e]){r.saveType==="dev"&&delete r.saveType;return}r.saveType="dev"}}),"save-exact":new I("save-exact",{default:!1,type:Boolean,short:"E",description:`
457
+ Dependencies saved to package.json will be configured with an exact
458
+ version rather than using npm's default semver range operator.
459
+ `,flatten(e,t,r){Tr["save-prefix"].flatten("save-prefix",t,r)}}),"save-optional":new I("save-optional",{default:!1,type:Boolean,short:"O",exclusive:["save-dev","save-peer","save-prod"],description:`
460
+ Save installed packages to a package.json file as
461
+ \`optionalDependencies\`.
462
+ `,flatten(e,t,r){if(!t[e]){r.saveType==="optional"?delete r.saveType:r.saveType==="peerOptional"&&(r.saveType="peer");return}r.saveType!=="peerOptional"&&(r.saveType==="peer"?r.saveType="peerOptional":r.saveType="optional")}}),"save-peer":new I("save-peer",{default:!1,type:Boolean,exclusive:["save-dev","save-optional","save-prod"],description:"\n Save installed packages to a package.json file as `peerDependencies`\n ",flatten(e,t,r){if(!t[e]){r.saveType==="peer"?delete r.saveType:r.saveType==="peerOptional"&&(r.saveType="optional");return}r.saveType!=="peerOptional"&&(r.saveType==="optional"?r.saveType="peerOptional":r.saveType="peer")}}),"save-prefix":new I("save-prefix",{default:"^",type:String,description:"\n Configure how versions of packages installed to a package.json file via\n `--save` or `--save-dev` get prefixed.\n\n For example if a package has version `1.2.3`, by default its version is\n set to `^1.2.3` which allows minor upgrades for that package, but after\n `npm config set save-prefix='~'` it would be set to `~1.2.3` which\n only allows patch upgrades.\n ",flatten(e,t,r){r.savePrefix=t["save-exact"]?"":t["save-prefix"],t["save-prefix"]=r.savePrefix}}),"save-prod":new I("save-prod",{default:!1,type:Boolean,short:"P",exclusive:["save-dev","save-optional","save-peer"],description:"\n Save installed packages into `dependencies` specifically. This is\n useful if a package already exists in `devDependencies` or\n `optionalDependencies`, but you want to move it to be a non-optional\n production dependency.\n\n This is the default behavior if `--save` is true, and neither\n `--save-dev` or `--save-optional` are true.\n ",flatten(e,t,r){if(!t[e]){r.saveType==="prod"&&delete r.saveType;return}r.saveType="prod"}}),"sbom-format":new I("sbom-format",{default:null,type:["cyclonedx","spdx"],description:`
463
+ SBOM format to use when generating SBOMs.
464
+ `,flatten:D}),"sbom-type":new I("sbom-type",{default:"library",type:["library","application","framework"],description:"\n The type of package described by the generated SBOM. For SPDX, this is the\n value for the `primaryPackagePurpose` field. For CycloneDX, this is the\n value for the `type` field.\n ",flatten:D}),scope:new I("scope",{default:"",defaultDescription:`
465
+ the scope of the current project, if any, or ""
466
+ `,type:String,hint:"<@scope>",description:`
467
+ Associate an operation with a scope for a scoped registry.
468
+
469
+ Useful when logging in to or out of a private registry:
470
+
471
+ \`\`\`
472
+ # log in, linking the scope to the custom registry
473
+ npm login --scope=@mycorp --registry=https://registry.mycorp.com
474
+
475
+ # log out, removing the link and the auth token
476
+ npm logout --scope=@mycorp
477
+ \`\`\`
478
+
479
+ This will cause \`@mycorp\` to be mapped to the registry for future
480
+ installation of packages specified according to the pattern
481
+ \`@mycorp/package\`.
482
+
483
+ This will also cause \`npm init\` to create a scoped package.
484
+
485
+ \`\`\`
486
+ # accept all defaults, and create a package named "@foo/whatever",
487
+ # instead of just named "whatever"
488
+ npm init --scope=@foo --yes
489
+ \`\`\`
490
+ `,flatten(e,t,r){let n=t[e],o=n&&!/^@/.test(n)?`@${n}`:n;r.scope=o,r.projectScope=o}}),scopes:new I("scopes",{default:null,type:[null,String,Array],description:`
491
+ When creating a Granular Access Token with \`npm token create\`,
492
+ this limits the token access to specific scopes. Provide
493
+ a scope name (with or without @ prefix).
494
+ `,flatten:D}),"packages-all":new I("packages-all",{default:!1,type:Boolean,description:`
495
+ When creating a Granular Access Token with \`npm token create\`,
496
+ grants the token access to all packages instead of limiting to
497
+ specific packages.
498
+ `,flatten:D}),"packages-and-scopes-permission":new I("packages-and-scopes-permission",{default:null,type:[null,"read-only","read-write","no-access"],description:`
499
+ When creating a Granular Access Token with \`npm token create\`,
500
+ sets the permission level for packages and scopes. Options are
501
+ "read-only", "read-write", or "no-access".
502
+ `,flatten:D}),"orgs-permission":new I("orgs-permission",{default:null,type:[null,"read-only","read-write","no-access"],description:`
503
+ When creating a Granular Access Token with \`npm token create\`,
504
+ sets the permission level for organizations. Options are
505
+ "read-only", "read-write", or "no-access".
506
+ `,flatten:D}),password:new I("password",{default:null,type:[null,String],description:`
507
+ Password for authentication. Can be provided via command line when
508
+ creating tokens, though it's generally safer to be prompted for it.
509
+ `,flatten:D}),"token-description":new I("token-description",{default:null,type:[null,String],description:"\n Description text for the token when using `npm token create`.\n ",flatten:D}),"script-shell":new I("script-shell",{default:null,defaultDescription:`
510
+ '/bin/sh' on POSIX systems, 'cmd.exe' on Windows
511
+ `,type:[null,String],description:"\n The shell to use for scripts run with the `npm exec`,\n `npm run` and `npm init <package-spec>` commands.\n ",flatten(e,t,r){r.scriptShell=t[e]||void 0}}),searchexclude:new I("searchexclude",{default:"",type:String,description:`
512
+ Space-separated options that limit the results from search.
513
+ `,flatten(e,t,r){r.search=r.search||{limit:20},r.search.exclude=t[e].toLowerCase()}}),searchlimit:new I("searchlimit",{default:20,type:Number,description:`
514
+ Number of items to limit search results to. Will not apply at all to
515
+ legacy searches.
516
+ `,flatten(e,t,r){r.search=r.search||{},r.search.limit=t[e]}}),searchopts:new I("searchopts",{default:"",type:String,description:`
517
+ Space-separated options that are always passed to search.
518
+ `,flatten(e,t,r){r.search=r.search||{limit:20},r.search.opts=TR.parse(t[e])}}),searchstaleness:new I("searchstaleness",{default:900,type:Number,description:`
519
+ The age of the cache, in seconds, before another registry request is made
520
+ if using legacy search endpoint.
521
+ `,flatten(e,t,r){r.search=r.search||{limit:20},r.search.staleness=t[e]}}),shell:new I("shell",{default:CR,defaultDescription:`
522
+ SHELL environment variable, or "bash" on Posix, or "cmd.exe" on Windows
523
+ `,type:String,description:"\n The shell to run for the `npm explore` command.\n ",flatten:D}),shrinkwrap:new I("shrinkwrap",{default:!0,type:Boolean,deprecated:`
524
+ Use the --package-lock setting instead.
525
+ `,description:`
526
+ Alias for --package-lock
527
+ `,flatten(e,t,r){t["package-lock"]=t.shrinkwrap,Tr["package-lock"].flatten("package-lock",t,r)}}),"sign-git-commit":new I("sign-git-commit",{default:!1,type:Boolean,description:`
528
+ If set to true, then the \`npm version\` command will commit the new
529
+ package version using \`-S\` to add a signature.
530
+
531
+ Note that git requires you to have set up GPG keys in your git configs
532
+ for this to work properly.
533
+ `,flatten:D}),"sign-git-tag":new I("sign-git-tag",{default:!1,type:Boolean,description:`
534
+ If set to true, then the \`npm version\` command will tag the version
535
+ using \`-s\` to add a signature.
536
+
537
+ Note that git requires you to have set up GPG keys in your git configs
538
+ for this to work properly.
539
+ `,flatten:D}),"strict-peer-deps":new I("strict-peer-deps",{default:!1,type:Boolean,description:`
540
+ If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_
541
+ conflicting \`peerDependencies\` will be treated as an install failure,
542
+ even if npm could reasonably guess the appropriate resolution based on
543
+ non-peer dependency relationships.
544
+
545
+ By default, conflicting \`peerDependencies\` deep in the dependency graph
546
+ will be resolved using the nearest non-peer dependency specification,
547
+ even if doing so will result in some packages receiving a peer dependency
548
+ outside the range set in their package's \`peerDependencies\` object.
549
+
550
+ When such an override is performed, a warning is printed, explaining the
551
+ conflict and the packages involved. If \`--strict-peer-deps\` is set,
552
+ then this warning is treated as a failure.
553
+ `,flatten:D}),"strict-ssl":new I("strict-ssl",{default:!0,type:Boolean,description:`
554
+ Whether or not to do SSL key validation when making requests to the
555
+ registry via https.
556
+
557
+ See also the \`ca\` config.
558
+ `,flatten(e,t,r){r.strictSSL=t[e]}}),tag:new I("tag",{default:"latest",type:String,description:`
559
+ If you ask npm to install a package and don't tell it a specific version,
560
+ then it will install the specified tag.
561
+
562
+ It is the tag added to the package@version specified in the
563
+ \`npm dist-tag add\` command, if no explicit tag is given.
564
+
565
+ When used by the \`npm diff\` command, this is the tag used to fetch the
566
+ tarball that will be compared with the local files by default.
567
+
568
+ If used in the \`npm publish\` command, this is the tag that will be
569
+ added to the package submitted to the registry.
570
+ `,flatten(e,t,r){r.defaultTag=t[e]}}),"tag-version-prefix":new I("tag-version-prefix",{default:"v",type:String,description:`
571
+ If set, alters the prefix used when tagging a new version when performing
572
+ a version increment using \`npm version\`. To remove the prefix
573
+ altogether, set it to the empty string: \`""\`.
574
+
575
+ Because other tools may rely on the convention that npm version tags look
576
+ like \`v1.0.0\`, _only use this property if it is absolutely necessary_.
577
+ In particular, use care when overriding this setting for public packages.
578
+ `,flatten:D}),timing:new I("timing",{default:!1,type:Boolean,description:`
579
+ If true, writes timing information to a process specific json file in
580
+ the cache or \`logs-dir\`. The file name ends with \`-timing.json\`.
581
+
582
+ You can quickly view it with this [json](https://npm.im/json) command
583
+ line: \`cat ~/.npm/_logs/*-timing.json | npm exec -- json -g\`.
584
+
585
+ Timing information will also be reported in the terminal. To suppress this
586
+ while still writing the timing file, use \`--silent\`.
587
+ `}),umask:new I("umask",{default:0,type:FR,description:`
588
+ The "umask" value to use when setting the file creation mode on files and
589
+ folders.
590
+
591
+ Folders and executables are given a mode which is \`0o777\` masked
592
+ against this value. Other files are given a mode which is \`0o666\`
593
+ masked against this value.
594
+
595
+ Note that the underlying system will _also_ apply its own umask value to
596
+ files and folders that are created, and npm does not circumvent this, but
597
+ rather adds the \`--umask\` config to it.
598
+
599
+ Thus, the effective default umask value on most POSIX systems is 0o22,
600
+ meaning that folders and executables are created with a mode of 0o755 and
601
+ other files are created with a mode of 0o644.
602
+ `,flatten:D}),unicode:new I("unicode",{default:MR,defaultDescription:"\n false on windows, true on mac/unix systems with a unicode locale, as\n defined by the `LC_ALL`, `LC_CTYPE`, or `LANG` environment variables.\n ",type:Boolean,description:`
603
+ When set to true, npm uses unicode characters in the tree output. When
604
+ false, it uses ascii characters instead of unicode glyphs.
605
+ `,flatten:D}),"update-notifier":new I("update-notifier",{default:!0,type:Boolean,description:`
606
+ Set to false to suppress the update notification when using an older
607
+ version of npm than the latest.
608
+ `}),usage:new I("usage",{default:!1,type:Boolean,short:["?","H","h"],description:`
609
+ Show short usage output about the command specified.
610
+ `}),"user-agent":new I("user-agent",{default:"npm/{npm-version} node/{node-version} {platform} {arch} workspaces/{workspaces} {ci}",type:String,description:"\n Sets the User-Agent request header. The following fields are replaced\n with their actual counterparts:\n\n * `{npm-version}` - The npm version in use\n * `{node-version}` - The Node.js version in use\n * `{platform}` - The value of `process.platform`\n * `{arch}` - The value of `process.arch`\n * `{workspaces}` - Set to `true` if the `workspaces` or `workspace`\n options are set.\n * `{ci}` - The value of the `ci-name` config, if set, prefixed with\n `ci/`, or an empty string if `ci-name` is empty.\n ",flatten(e,t,r){let n=t[e],o=hS.name?.toLowerCase().split(" ").join("-")||null,i=!1;(t.workspaces||t.workspace&&t.workspace.length)&&(i=!0),r.userAgent=n.replace(/\{node-version\}/gi,process.version).replace(/\{npm-version\}/gi,t["npm-version"]).replace(/\{platform\}/gi,process.platform).replace(/\{arch\}/gi,process.arch).replace(/\{workspaces\}/gi,i).replace(/\{ci\}/gi,o?`ci/${o}`:"").trim(),process.env.npm_config_user_agent=r.userAgent}}),userconfig:new I("userconfig",{default:"~/.npmrc",type:qr,description:"\n The location of user-level configuration settings.\n\n This may be overridden by the `npm_config_userconfig` environment\n variable or the `--userconfig` command line option, but may _not_\n be overridden by settings in the `globalconfig` file.\n "}),version:new I("version",{default:!1,type:Boolean,short:"v",description:`
611
+ If true, output the npm version and exit successfully.
612
+
613
+ Only relevant when specified explicitly on the command line.
614
+ `}),versions:new I("versions",{default:!1,type:Boolean,description:`
615
+ If true, output the npm version as well as node's \`process.versions\`
616
+ map and the version in the current working directory's \`package.json\`
617
+ file if one exists, and exit successfully.
618
+
619
+ Only relevant when specified explicitly on the command line.
620
+ `}),viewer:new I("viewer",{default:ca?"browser":"man",defaultDescription:`
621
+ "man" on Posix, "browser" on Windows
622
+ `,type:String,description:`
623
+ The program to use to view help content.
624
+
625
+ Set to \`"browser"\` to view html help content in the default web browser.
626
+ `}),which:new I("which",{default:null,hint:"<fundingSourceNumber>",type:[null,Number],description:`
627
+ If there are multiple funding sources, which 1-indexed source URL to open.
628
+ `}),workspace:new I("workspace",{default:[],type:[String,Array],hint:"<workspace-name>",short:"w",envExport:!1,description:`
629
+ Enable running a command in the context of the configured workspaces of the
630
+ current project while filtering by running only the workspaces defined by
631
+ this configuration option.
632
+
633
+ Valid values for the \`workspace\` config are either:
634
+
635
+ * Workspace names
636
+ * Path to a workspace directory
637
+ * Path to a parent workspace directory (will result in selecting all
638
+ workspaces within that folder)
639
+
640
+ When set for the \`npm init\` command, this may be set to the folder of
641
+ a workspace which does not yet exist, to create the folder and set it
642
+ up as a brand new workspace within the project.
643
+ `,flatten:s((e,t,r)=>{Tr["user-agent"].flatten("user-agent",t,r)},"flatten")}),workspaces:new I("workspaces",{default:null,type:[null,Boolean],envExport:!1,description:`
644
+ Set to true to run the command in the context of **all** configured
645
+ workspaces.
646
+
647
+ Explicitly setting this to false will cause commands like \`install\` to
648
+ ignore workspaces altogether.
649
+ When not set explicitly:
650
+
651
+ - Commands that operate on the \`node_modules\` tree (install, update,
652
+ etc.) will link workspaces into the \`node_modules\` folder.
653
+ - Commands that do other things (test, exec, publish, etc.) will operate
654
+ on the root project, _unless_ one or more workspaces are specified in
655
+ the \`workspace\` config.
656
+ `,flatten:s((e,t,r)=>{Tr["user-agent"].flatten("user-agent",t,r),r.workspacesEnabled=t[e]!==!1},"flatten")}),"workspaces-update":new I("workspaces-update",{default:!0,type:Boolean,description:`
657
+ If set to true, the npm cli will run an update after operations that may
658
+ possibly change the workspaces installed to the \`node_modules\` folder.
659
+ `,flatten:D}),yes:new I("yes",{default:null,type:[null,Boolean],short:"y",description:`
660
+ Automatically answer "yes" to any prompts that npm might print on
661
+ the command line.
662
+ `})};vS.exports=Tr});var bS=V((LG,xS)=>{var sp=SS(),jR=s((e,t={})=>{for(let[r,n]of Object.entries(e)){let o=sp[r];o&&o.flatten?o.flatten(r,e,t):(/@.*:registry$/i.test(r)||/^\/\//.test(r))&&(t[r]=n)}return t},"flatten"),wS=Object.entries(sp).reduce((e,[t,{short:r=[],default:n}])=>{for(let o of[].concat(r))e.shorthands[o]=[`--${t}`];return e.defaults[t]=n,e},{shorthands:{},defaults:{}}),UR={"enjoy-by":["--before"],d:["--loglevel","info"],dd:["--loglevel","verbose"],ddd:["--loglevel","silly"],quiet:["--loglevel","warn"],q:["--loglevel","warn"],s:["--loglevel","silent"],silent:["--loglevel","silent"],verbose:["--loglevel","verbose"],desc:["--description"],help:["--usage"],local:["--no-global"],n:["--no-yes"],no:["--no-yes"],porcelain:["--parseable"],readonly:["--read-only"],reg:["--registry"],iwr:["--include-workspace-root"],ws:["--workspaces"],...wS.shorthands},qR=["_auth","_authToken","_password","certfile","email","keyfile","username"],BR=["http_proxy","https_proxy","proxy","no_proxy"];xS.exports={defaults:wS.defaults,definitions:sp,flatten:jR,nerfDarts:qR,proxyEnv:BR,shorthands:UR}});var ba=V((Z4,aw)=>{var gD=Object.prototype.toString;aw.exports=s(function(t){if(t===void 0)return"undefined";if(t===null)return"null";var r=typeof t;if(r==="boolean")return"boolean";if(r==="string")return"string";if(r==="number")return"number";if(r==="symbol")return"symbol";if(r==="function")return wD(t)?"generatorfunction":"function";if(hD(t))return"array";if(ED(t))return"buffer";if(bD(t))return"arguments";if(vD(t))return"date";if(yD(t))return"error";if(SD(t))return"regexp";switch(iw(t)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(xD(t))return"generator";switch(r=gD.call(t),r){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return r.slice(8,-1).toLowerCase().replace(/\s/g,"")},"kindOf");function iw(e){return typeof e.constructor=="function"?e.constructor.name:null}s(iw,"ctorName");function hD(e){return Array.isArray?Array.isArray(e):e instanceof Array}s(hD,"isArray");function yD(e){return e instanceof Error||typeof e.message=="string"&&e.constructor&&typeof e.constructor.stackTraceLimit=="number"}s(yD,"isError");function vD(e){return e instanceof Date?!0:typeof e.toDateString=="function"&&typeof e.getDate=="function"&&typeof e.setDate=="function"}s(vD,"isDate");function SD(e){return e instanceof RegExp?!0:typeof e.flags=="string"&&typeof e.ignoreCase=="boolean"&&typeof e.multiline=="boolean"&&typeof e.global=="boolean"}s(SD,"isRegexp");function wD(e,t){return iw(e)==="GeneratorFunction"}s(wD,"isGeneratorFn");function xD(e){return typeof e.throw=="function"&&typeof e.return=="function"&&typeof e.next=="function"}s(xD,"isGeneratorObj");function bD(e){try{if(typeof e.length=="number"&&typeof e.callee=="function")return!0}catch(t){if(t.message.indexOf("callee")!==-1)return!0}return!1}s(bD,"isArguments");function ED(e){return e.constructor&&typeof e.constructor.isBuffer=="function"?e.constructor.isBuffer(e):!1}s(ED,"isBuffer")});var cw=V((ez,lw)=>{"use strict";lw.exports=s(function(t){return typeof t<"u"&&t!==null&&(typeof t=="object"||typeof t=="function")},"isExtendable")});var pw=V((rz,dw)=>{"use strict";var uw=cw();dw.exports=s(function(t){uw(t)||(t={});for(var r=arguments.length,n=1;n<r;n++){var o=arguments[n];uw(o)&&ID(t,o)}return t},"extend");function ID(e,t){for(var r in t)TD(t,r)&&(e[r]=t[r])}s(ID,"assign");function TD(e,t){return Object.prototype.hasOwnProperty.call(e,t)}s(TD,"hasOwn")});var gw=V((oz,mw)=>{"use strict";var _D=ba(),AD=pw();mw.exports=function(e,t){typeof t=="function"&&(t={parse:t});var r=RD(e),n={section_delimiter:"---",parse:DD},o=AD({},n,t),i=o.section_delimiter,a=r.content.split(/\r?\n/),l=null,d=fw(),f=[],m=[];function g(O){r.content=O,l=[],f=[]}s(g,"initSections");function h(O){m.length&&(d.key=CD(m[0],i),d.content=O,o.parse(d,l),l.push(d),d=fw(),f=[],m=[])}s(h,"closeSection");for(var y=0;y<a.length;y++){var E=a[y],w=m.length,v=E.trim();if(kD(v,i)){if(v.length===3&&y!==0){if(w===0||w===2){f.push(E);continue}m.push(v),d.data=f.join(`
663
+ `),f=[];continue}l===null&&g(f.join(`
664
+ `)),w===2&&h(f.join(`
665
+ `)),m.push(v);continue}f.push(E)}return l===null?g(f.join(`
666
+ `)):h(f.join(`
667
+ `)),r.sections=l,r};function kD(e,t){return!(e.slice(0,t.length)!==t||e.charAt(t.length+1)===t.slice(-1))}s(kD,"isDelimiter");function RD(e){if(_D(e)!=="object"&&(e={content:e}),typeof e.content!="string"&&!OD(e.content))throw new TypeError("expected a buffer or string");return e.content=e.content.toString(),e.sections=[],e}s(RD,"toObject");function CD(e,t){return e?e.slice(t.length).trim():""}s(CD,"getKey");function fw(){return{key:"",data:"",content:""}}s(fw,"createSection");function DD(e){return e}s(DD,"identity");function OD(e){return e&&e.constructor&&typeof e.constructor.isBuffer=="function"?e.constructor.isBuffer(e):!1}s(OD,"isBuffer")});var Co=V((iz,Ro)=>{"use strict";function hw(e){return typeof e>"u"||e===null}s(hw,"isNothing");function MD(e){return typeof e=="object"&&e!==null}s(MD,"isObject");function PD(e){return Array.isArray(e)?e:hw(e)?[]:[e]}s(PD,"toArray");function ND(e,t){var r,n,o,i;if(t)for(i=Object.keys(t),r=0,n=i.length;r<n;r+=1)o=i[r],e[o]=t[o];return e}s(ND,"extend");function LD(e,t){var r="",n;for(n=0;n<t;n+=1)r+=e;return r}s(LD,"repeat");function FD(e){return e===0&&Number.NEGATIVE_INFINITY===1/e}s(FD,"isNegativeZero");Ro.exports.isNothing=hw;Ro.exports.isObject=MD;Ro.exports.toArray=PD;Ro.exports.repeat=LD;Ro.exports.isNegativeZero=FD;Ro.exports.extend=ND});var $s=V((lz,yw)=>{"use strict";function Ea(e,t){Error.call(this),this.name="YAMLException",this.reason=e,this.mark=t,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}s(Ea,"YAMLException");Ea.prototype=Object.create(Error.prototype);Ea.prototype.constructor=Ea;Ea.prototype.toString=s(function(t){var r=this.name+": ";return r+=this.reason||"(unknown reason)",!t&&this.mark&&(r+=" "+this.mark.toString()),r},"toString");yw.exports=Ea});var ww=V((uz,Sw)=>{"use strict";var vw=Co();function Lp(e,t,r,n,o){this.name=e,this.buffer=t,this.position=r,this.line=n,this.column=o}s(Lp,"Mark");Lp.prototype.getSnippet=s(function(t,r){var n,o,i,a,l;if(!this.buffer)return null;for(t=t||4,r=r||75,n="",o=this.position;o>0&&`\0\r
668
+ \x85\u2028\u2029`.indexOf(this.buffer.charAt(o-1))===-1;)if(o-=1,this.position-o>r/2-1){n=" ... ",o+=5;break}for(i="",a=this.position;a<this.buffer.length&&`\0\r
669
+ \x85\u2028\u2029`.indexOf(this.buffer.charAt(a))===-1;)if(a+=1,a-this.position>r/2-1){i=" ... ",a-=5;break}return l=this.buffer.slice(o,a),vw.repeat(" ",t)+n+l+i+`
670
+ `+vw.repeat(" ",t+this.position-o+n.length)+"^"},"getSnippet");Lp.prototype.toString=s(function(t){var r,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),t||(r=this.getSnippet(),r&&(n+=`:
671
+ `+r)),n},"toString");Sw.exports=Lp});var ot=V((pz,bw)=>{"use strict";var xw=$s(),jD=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],UD=["scalar","sequence","mapping"];function qD(e){var t={};return e!==null&&Object.keys(e).forEach(function(r){e[r].forEach(function(n){t[String(n)]=r})}),t}s(qD,"compileStyleAliases");function BD(e,t){if(t=t||{},Object.keys(t).forEach(function(r){if(jD.indexOf(r)===-1)throw new xw('Unknown option "'+r+'" is met in definition of "'+e+'" YAML type.')}),this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(r){return r},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.defaultStyle=t.defaultStyle||null,this.styleAliases=qD(t.styleAliases||null),UD.indexOf(this.kind)===-1)throw new xw('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')}s(BD,"Type");bw.exports=BD});var Do=V((mz,Iw)=>{"use strict";var Ew=Co(),Dc=$s(),$D=ot();function Fp(e,t,r){var n=[];return e.include.forEach(function(o){r=Fp(o,t,r)}),e[t].forEach(function(o){r.forEach(function(i,a){i.tag===o.tag&&i.kind===o.kind&&n.push(a)}),r.push(o)}),r.filter(function(o,i){return n.indexOf(i)===-1})}s(Fp,"compileList");function VD(){var e={scalar:{},sequence:{},mapping:{},fallback:{}},t,r;function n(o){e[o.kind][o.tag]=e.fallback[o.tag]=o}for(s(n,"collectType"),t=0,r=arguments.length;t<r;t+=1)arguments[t].forEach(n);return e}s(VD,"compileMap");function Vs(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(t){if(t.loadKind&&t.loadKind!=="scalar")throw new Dc("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=Fp(this,"implicit",[]),this.compiledExplicit=Fp(this,"explicit",[]),this.compiledTypeMap=VD(this.compiledImplicit,this.compiledExplicit)}s(Vs,"Schema");Vs.DEFAULT=null;Vs.create=s(function(){var t,r;switch(arguments.length){case 1:t=Vs.DEFAULT,r=arguments[0];break;case 2:t=arguments[0],r=arguments[1];break;default:throw new Dc("Wrong number of arguments for Schema.create function")}if(t=Ew.toArray(t),r=Ew.toArray(r),!t.every(function(n){return n instanceof Vs}))throw new Dc("Specified list of super schemas (or a single Schema object) contains a non-Schema object.");if(!r.every(function(n){return n instanceof $D}))throw new Dc("Specified list of YAML types (or a single Type object) contains a non-Type object.");return new Vs({include:t,explicit:r})},"createSchema");Iw.exports=Vs});var _w=V((hz,Tw)=>{"use strict";var HD=ot();Tw.exports=new HD("tag:yaml.org,2002:str",{kind:"scalar",construct:s(function(e){return e!==null?e:""},"construct")})});var kw=V((vz,Aw)=>{"use strict";var WD=ot();Aw.exports=new WD("tag:yaml.org,2002:seq",{kind:"sequence",construct:s(function(e){return e!==null?e:[]},"construct")})});var Cw=V((wz,Rw)=>{"use strict";var GD=ot();Rw.exports=new GD("tag:yaml.org,2002:map",{kind:"mapping",construct:s(function(e){return e!==null?e:{}},"construct")})});var Oc=V((bz,Dw)=>{"use strict";var JD=Do();Dw.exports=new JD({explicit:[_w(),kw(),Cw()]})});var Mw=V((Ez,Ow)=>{"use strict";var zD=ot();function KD(e){if(e===null)return!0;var t=e.length;return t===1&&e==="~"||t===4&&(e==="null"||e==="Null"||e==="NULL")}s(KD,"resolveYamlNull");function YD(){return null}s(YD,"constructYamlNull");function XD(e){return e===null}s(XD,"isNull");Ow.exports=new zD("tag:yaml.org,2002:null",{kind:"scalar",resolve:KD,construct:YD,predicate:XD,represent:{canonical:s(function(){return"~"},"canonical"),lowercase:s(function(){return"null"},"lowercase"),uppercase:s(function(){return"NULL"},"uppercase"),camelcase:s(function(){return"Null"},"camelcase")},defaultStyle:"lowercase"})});var Nw=V((Tz,Pw)=>{"use strict";var ZD=ot();function QD(e){if(e===null)return!1;var t=e.length;return t===4&&(e==="true"||e==="True"||e==="TRUE")||t===5&&(e==="false"||e==="False"||e==="FALSE")}s(QD,"resolveYamlBoolean");function eO(e){return e==="true"||e==="True"||e==="TRUE"}s(eO,"constructYamlBoolean");function tO(e){return Object.prototype.toString.call(e)==="[object Boolean]"}s(tO,"isBoolean");Pw.exports=new ZD("tag:yaml.org,2002:bool",{kind:"scalar",resolve:QD,construct:eO,predicate:tO,represent:{lowercase:s(function(e){return e?"true":"false"},"lowercase"),uppercase:s(function(e){return e?"TRUE":"FALSE"},"uppercase"),camelcase:s(function(e){return e?"True":"False"},"camelcase")},defaultStyle:"lowercase"})});var Fw=V((Az,Lw)=>{"use strict";var rO=Co(),nO=ot();function oO(e){return 48<=e&&e<=57||65<=e&&e<=70||97<=e&&e<=102}s(oO,"isHexCode");function sO(e){return 48<=e&&e<=55}s(sO,"isOctCode");function iO(e){return 48<=e&&e<=57}s(iO,"isDecCode");function aO(e){if(e===null)return!1;var t=e.length,r=0,n=!1,o;if(!t)return!1;if(o=e[r],(o==="-"||o==="+")&&(o=e[++r]),o==="0"){if(r+1===t)return!0;if(o=e[++r],o==="b"){for(r++;r<t;r++)if(o=e[r],o!=="_"){if(o!=="0"&&o!=="1")return!1;n=!0}return n&&o!=="_"}if(o==="x"){for(r++;r<t;r++)if(o=e[r],o!=="_"){if(!oO(e.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}for(;r<t;r++)if(o=e[r],o!=="_"){if(!sO(e.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}if(o==="_")return!1;for(;r<t;r++)if(o=e[r],o!=="_"){if(o===":")break;if(!iO(e.charCodeAt(r)))return!1;n=!0}return!n||o==="_"?!1:o!==":"?!0:/^(:[0-5]?[0-9])+$/.test(e.slice(r))}s(aO,"resolveYamlInteger");function lO(e){var t=e,r=1,n,o,i=[];return t.indexOf("_")!==-1&&(t=t.replace(/_/g,"")),n=t[0],(n==="-"||n==="+")&&(n==="-"&&(r=-1),t=t.slice(1),n=t[0]),t==="0"?0:n==="0"?t[1]==="b"?r*parseInt(t.slice(2),2):t[1]==="x"?r*parseInt(t,16):r*parseInt(t,8):t.indexOf(":")!==-1?(t.split(":").forEach(function(a){i.unshift(parseInt(a,10))}),t=0,o=1,i.forEach(function(a){t+=a*o,o*=60}),r*t):r*parseInt(t,10)}s(lO,"constructYamlInteger");function cO(e){return Object.prototype.toString.call(e)==="[object Number]"&&e%1===0&&!rO.isNegativeZero(e)}s(cO,"isInteger");Lw.exports=new nO("tag:yaml.org,2002:int",{kind:"scalar",resolve:aO,construct:lO,predicate:cO,represent:{binary:s(function(e){return e>=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},"binary"),octal:s(function(e){return e>=0?"0"+e.toString(8):"-0"+e.toString(8).slice(1)},"octal"),decimal:s(function(e){return e.toString(10)},"decimal"),hexadecimal:s(function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)},"hexadecimal")},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}})});var qw=V((Rz,Uw)=>{"use strict";var jw=Co(),uO=ot(),dO=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function pO(e){return!(e===null||!dO.test(e)||e[e.length-1]==="_")}s(pO,"resolveYamlFloat");function fO(e){var t,r,n,o;return t=e.replace(/_/g,"").toLowerCase(),r=t[0]==="-"?-1:1,o=[],"+-".indexOf(t[0])>=0&&(t=t.slice(1)),t===".inf"?r===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:t===".nan"?NaN:t.indexOf(":")>=0?(t.split(":").forEach(function(i){o.unshift(parseFloat(i,10))}),t=0,n=1,o.forEach(function(i){t+=i*n,n*=60}),r*t):r*parseFloat(t,10)}s(fO,"constructYamlFloat");var mO=/^[-+]?[0-9]+e/;function gO(e,t){var r;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(jw.isNegativeZero(e))return"-0.0";return r=e.toString(10),mO.test(r)?r.replace("e",".e"):r}s(gO,"representYamlFloat");function hO(e){return Object.prototype.toString.call(e)==="[object Number]"&&(e%1!==0||jw.isNegativeZero(e))}s(hO,"isFloat");Uw.exports=new uO("tag:yaml.org,2002:float",{kind:"scalar",resolve:pO,construct:fO,predicate:hO,represent:gO,defaultStyle:"lowercase"})});var jp=V((Dz,Bw)=>{"use strict";var yO=Do();Bw.exports=new yO({include:[Oc()],implicit:[Mw(),Nw(),Fw(),qw()]})});var Up=V((Oz,$w)=>{"use strict";var vO=Do();$w.exports=new vO({include:[jp()]})});var Gw=V((Mz,Ww)=>{"use strict";var SO=ot(),Vw=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),Hw=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function wO(e){return e===null?!1:Vw.exec(e)!==null||Hw.exec(e)!==null}s(wO,"resolveYamlTimestamp");function xO(e){var t,r,n,o,i,a,l,d=0,f=null,m,g,h;if(t=Vw.exec(e),t===null&&(t=Hw.exec(e)),t===null)throw new Error("Date resolve error");if(r=+t[1],n=+t[2]-1,o=+t[3],!t[4])return new Date(Date.UTC(r,n,o));if(i=+t[4],a=+t[5],l=+t[6],t[7]){for(d=t[7].slice(0,3);d.length<3;)d+="0";d=+d}return t[9]&&(m=+t[10],g=+(t[11]||0),f=(m*60+g)*6e4,t[9]==="-"&&(f=-f)),h=new Date(Date.UTC(r,n,o,i,a,l,d)),f&&h.setTime(h.getTime()-f),h}s(xO,"constructYamlTimestamp");function bO(e){return e.toISOString()}s(bO,"representYamlTimestamp");Ww.exports=new SO("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:wO,construct:xO,instanceOf:Date,represent:bO})});var zw=V((Nz,Jw)=>{"use strict";var EO=ot();function IO(e){return e==="<<"||e===null}s(IO,"resolveYamlMerge");Jw.exports=new EO("tag:yaml.org,2002:merge",{kind:"scalar",resolve:IO})});var Xw=V((Fz,Yw)=>{"use strict";var Oo;try{Kw=Ve,Oo=Kw("buffer").Buffer}catch{}var Kw,TO=ot(),qp=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
672
+ \r`;function _O(e){if(e===null)return!1;var t,r,n=0,o=e.length,i=qp;for(r=0;r<o;r++)if(t=i.indexOf(e.charAt(r)),!(t>64)){if(t<0)return!1;n+=6}return n%8===0}s(_O,"resolveYamlBinary");function AO(e){var t,r,n=e.replace(/[\r\n=]/g,""),o=n.length,i=qp,a=0,l=[];for(t=0;t<o;t++)t%4===0&&t&&(l.push(a>>16&255),l.push(a>>8&255),l.push(a&255)),a=a<<6|i.indexOf(n.charAt(t));return r=o%4*6,r===0?(l.push(a>>16&255),l.push(a>>8&255),l.push(a&255)):r===18?(l.push(a>>10&255),l.push(a>>2&255)):r===12&&l.push(a>>4&255),Oo?Oo.from?Oo.from(l):new Oo(l):l}s(AO,"constructYamlBinary");function kO(e){var t="",r=0,n,o,i=e.length,a=qp;for(n=0;n<i;n++)n%3===0&&n&&(t+=a[r>>18&63],t+=a[r>>12&63],t+=a[r>>6&63],t+=a[r&63]),r=(r<<8)+e[n];return o=i%3,o===0?(t+=a[r>>18&63],t+=a[r>>12&63],t+=a[r>>6&63],t+=a[r&63]):o===2?(t+=a[r>>10&63],t+=a[r>>4&63],t+=a[r<<2&63],t+=a[64]):o===1&&(t+=a[r>>2&63],t+=a[r<<4&63],t+=a[64],t+=a[64]),t}s(kO,"representYamlBinary");function RO(e){return Oo&&Oo.isBuffer(e)}s(RO,"isBinary");Yw.exports=new TO("tag:yaml.org,2002:binary",{kind:"scalar",resolve:_O,construct:AO,predicate:RO,represent:kO})});var Qw=V((Uz,Zw)=>{"use strict";var CO=ot(),DO=Object.prototype.hasOwnProperty,OO=Object.prototype.toString;function MO(e){if(e===null)return!0;var t=[],r,n,o,i,a,l=e;for(r=0,n=l.length;r<n;r+=1){if(o=l[r],a=!1,OO.call(o)!=="[object Object]")return!1;for(i in o)if(DO.call(o,i))if(!a)a=!0;else return!1;if(!a)return!1;if(t.indexOf(i)===-1)t.push(i);else return!1}return!0}s(MO,"resolveYamlOmap");function PO(e){return e!==null?e:[]}s(PO,"constructYamlOmap");Zw.exports=new CO("tag:yaml.org,2002:omap",{kind:"sequence",resolve:MO,construct:PO})});var tx=V((Bz,ex)=>{"use strict";var NO=ot(),LO=Object.prototype.toString;function FO(e){if(e===null)return!0;var t,r,n,o,i,a=e;for(i=new Array(a.length),t=0,r=a.length;t<r;t+=1){if(n=a[t],LO.call(n)!=="[object Object]"||(o=Object.keys(n),o.length!==1))return!1;i[t]=[o[0],n[o[0]]]}return!0}s(FO,"resolveYamlPairs");function jO(e){if(e===null)return[];var t,r,n,o,i,a=e;for(i=new Array(a.length),t=0,r=a.length;t<r;t+=1)n=a[t],o=Object.keys(n),i[t]=[o[0],n[o[0]]];return i}s(jO,"constructYamlPairs");ex.exports=new NO("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:FO,construct:jO})});var nx=V((Vz,rx)=>{"use strict";var UO=ot(),qO=Object.prototype.hasOwnProperty;function BO(e){if(e===null)return!0;var t,r=e;for(t in r)if(qO.call(r,t)&&r[t]!==null)return!1;return!0}s(BO,"resolveYamlSet");function $O(e){return e!==null?e:{}}s($O,"constructYamlSet");rx.exports=new UO("tag:yaml.org,2002:set",{kind:"mapping",resolve:BO,construct:$O})});var Hs=V((Wz,ox)=>{"use strict";var VO=Do();ox.exports=new VO({include:[Up()],implicit:[Gw(),zw()],explicit:[Xw(),Qw(),tx(),nx()]})});var ix=V((Gz,sx)=>{"use strict";var HO=ot();function WO(){return!0}s(WO,"resolveJavascriptUndefined");function GO(){}s(GO,"constructJavascriptUndefined");function JO(){return""}s(JO,"representJavascriptUndefined");function zO(e){return typeof e>"u"}s(zO,"isUndefined");sx.exports=new HO("tag:yaml.org,2002:js/undefined",{kind:"scalar",resolve:WO,construct:GO,predicate:zO,represent:JO})});var lx=V((zz,ax)=>{"use strict";var KO=ot();function YO(e){if(e===null||e.length===0)return!1;var t=e,r=/\/([gim]*)$/.exec(e),n="";return!(t[0]==="/"&&(r&&(n=r[1]),n.length>3||t[t.length-n.length-1]!=="/"))}s(YO,"resolveJavascriptRegExp");function XO(e){var t=e,r=/\/([gim]*)$/.exec(e),n="";return t[0]==="/"&&(r&&(n=r[1]),t=t.slice(1,t.length-n.length-1)),new RegExp(t,n)}s(XO,"constructJavascriptRegExp");function ZO(e){var t="/"+e.source+"/";return e.global&&(t+="g"),e.multiline&&(t+="m"),e.ignoreCase&&(t+="i"),t}s(ZO,"representJavascriptRegExp");function QO(e){return Object.prototype.toString.call(e)==="[object RegExp]"}s(QO,"isRegExp");ax.exports=new KO("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve:YO,construct:XO,predicate:QO,represent:ZO})});var dx=V((Yz,ux)=>{"use strict";var Mc;try{cx=Ve,Mc=cx("esprima")}catch{typeof window<"u"&&(Mc=window.esprima)}var cx,eM=ot();function tM(e){if(e===null)return!1;try{var t="("+e+")",r=Mc.parse(t,{range:!0});return!(r.type!=="Program"||r.body.length!==1||r.body[0].type!=="ExpressionStatement"||r.body[0].expression.type!=="ArrowFunctionExpression"&&r.body[0].expression.type!=="FunctionExpression")}catch{return!1}}s(tM,"resolveJavascriptFunction");function rM(e){var t="("+e+")",r=Mc.parse(t,{range:!0}),n=[],o;if(r.type!=="Program"||r.body.length!==1||r.body[0].type!=="ExpressionStatement"||r.body[0].expression.type!=="ArrowFunctionExpression"&&r.body[0].expression.type!=="FunctionExpression")throw new Error("Failed to resolve function");return r.body[0].expression.params.forEach(function(i){n.push(i.name)}),o=r.body[0].expression.body.range,r.body[0].expression.body.type==="BlockStatement"?new Function(n,t.slice(o[0]+1,o[1]-1)):new Function(n,"return "+t.slice(o[0],o[1]))}s(rM,"constructJavascriptFunction");function nM(e){return e.toString()}s(nM,"representJavascriptFunction");function oM(e){return Object.prototype.toString.call(e)==="[object Function]"}s(oM,"isFunction");ux.exports=new eM("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:tM,construct:rM,predicate:oM,represent:nM})});var Ia=V((Zz,fx)=>{"use strict";var px=Do();fx.exports=px.DEFAULT=new px({include:[Hs()],explicit:[ix(),lx(),dx()]})});var Mx=V((Qz,Ta)=>{"use strict";var cn=Co(),wx=$s(),sM=ww(),xx=Hs(),iM=Ia(),Hn=Object.prototype.hasOwnProperty,Pc=1,bx=2,Ex=3,Nc=4,Bp=1,aM=2,mx=3,lM=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,cM=/[\x85\u2028\u2029]/,uM=/[,\[\]\{\}]/,Ix=/^(?:!|!!|![a-z\-]+!)$/i,Tx=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function gx(e){return Object.prototype.toString.call(e)}s(gx,"_class");function Vr(e){return e===10||e===13}s(Vr,"is_EOL");function Po(e){return e===9||e===32}s(Po,"is_WHITE_SPACE");function Vt(e){return e===9||e===32||e===10||e===13}s(Vt,"is_WS_OR_EOL");function Ws(e){return e===44||e===91||e===93||e===123||e===125}s(Ws,"is_FLOW_INDICATOR");function dM(e){var t;return 48<=e&&e<=57?e-48:(t=e|32,97<=t&&t<=102?t-97+10:-1)}s(dM,"fromHexCode");function pM(e){return e===120?2:e===117?4:e===85?8:0}s(pM,"escapedHexLen");function fM(e){return 48<=e&&e<=57?e-48:-1}s(fM,"fromDecimalCode");function hx(e){return e===48?"\0":e===97?"\x07":e===98?"\b":e===116||e===9?" ":e===110?`
673
+ `:e===118?"\v":e===102?"\f":e===114?"\r":e===101?"\x1B":e===32?" ":e===34?'"':e===47?"/":e===92?"\\":e===78?"\x85":e===95?"\xA0":e===76?"\u2028":e===80?"\u2029":""}s(hx,"simpleEscapeSequence");function mM(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}s(mM,"charFromCodepoint");function _x(e,t,r){t==="__proto__"?Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!0,value:r}):e[t]=r}s(_x,"setProperty");var Ax=new Array(256),kx=new Array(256);for(Mo=0;Mo<256;Mo++)Ax[Mo]=hx(Mo)?1:0,kx[Mo]=hx(Mo);var Mo;function gM(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||iM,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}s(gM,"State");function Rx(e,t){return new wx(t,new sM(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}s(Rx,"generateError");function Y(e,t){throw Rx(e,t)}s(Y,"throwError");function Lc(e,t){e.onWarning&&e.onWarning.call(null,Rx(e,t))}s(Lc,"throwWarning");var yx={YAML:s(function(t,r,n){var o,i,a;t.version!==null&&Y(t,"duplication of %YAML directive"),n.length!==1&&Y(t,"YAML directive accepts exactly one argument"),o=/^([0-9]+)\.([0-9]+)$/.exec(n[0]),o===null&&Y(t,"ill-formed argument of the YAML directive"),i=parseInt(o[1],10),a=parseInt(o[2],10),i!==1&&Y(t,"unacceptable YAML version of the document"),t.version=n[0],t.checkLineBreaks=a<2,a!==1&&a!==2&&Lc(t,"unsupported YAML version of the document")},"handleYamlDirective"),TAG:s(function(t,r,n){var o,i;n.length!==2&&Y(t,"TAG directive accepts exactly two arguments"),o=n[0],i=n[1],Ix.test(o)||Y(t,"ill-formed tag handle (first argument) of the TAG directive"),Hn.call(t.tagMap,o)&&Y(t,'there is a previously declared suffix for "'+o+'" tag handle'),Tx.test(i)||Y(t,"ill-formed tag prefix (second argument) of the TAG directive"),t.tagMap[o]=i},"handleTagDirective")};function Vn(e,t,r,n){var o,i,a,l;if(t<r){if(l=e.input.slice(t,r),n)for(o=0,i=l.length;o<i;o+=1)a=l.charCodeAt(o),a===9||32<=a&&a<=1114111||Y(e,"expected valid JSON character");else lM.test(l)&&Y(e,"the stream contains non-printable characters");e.result+=l}}s(Vn,"captureSegment");function vx(e,t,r,n){var o,i,a,l;for(cn.isObject(r)||Y(e,"cannot merge mappings; the provided source object is unacceptable"),o=Object.keys(r),a=0,l=o.length;a<l;a+=1)i=o[a],Hn.call(t,i)||(_x(t,i,r[i]),n[i]=!0)}s(vx,"mergeMappings");function Gs(e,t,r,n,o,i,a,l){var d,f;if(Array.isArray(o))for(o=Array.prototype.slice.call(o),d=0,f=o.length;d<f;d+=1)Array.isArray(o[d])&&Y(e,"nested arrays are not supported inside keys"),typeof o=="object"&&gx(o[d])==="[object Object]"&&(o[d]="[object Object]");if(typeof o=="object"&&gx(o)==="[object Object]"&&(o="[object Object]"),o=String(o),t===null&&(t={}),n==="tag:yaml.org,2002:merge")if(Array.isArray(i))for(d=0,f=i.length;d<f;d+=1)vx(e,t,i[d],r);else vx(e,t,i,r);else!e.json&&!Hn.call(r,o)&&Hn.call(t,o)&&(e.line=a||e.line,e.position=l||e.position,Y(e,"duplicated mapping key")),_x(t,o,i),delete r[o];return t}s(Gs,"storeMappingPair");function $p(e){var t;t=e.input.charCodeAt(e.position),t===10?e.position++:t===13?(e.position++,e.input.charCodeAt(e.position)===10&&e.position++):Y(e,"a line break is expected"),e.line+=1,e.lineStart=e.position}s($p,"readLineBreak");function rt(e,t,r){for(var n=0,o=e.input.charCodeAt(e.position);o!==0;){for(;Po(o);)o=e.input.charCodeAt(++e.position);if(t&&o===35)do o=e.input.charCodeAt(++e.position);while(o!==10&&o!==13&&o!==0);if(Vr(o))for($p(e),o=e.input.charCodeAt(e.position),n++,e.lineIndent=0;o===32;)e.lineIndent++,o=e.input.charCodeAt(++e.position);else break}return r!==-1&&n!==0&&e.lineIndent<r&&Lc(e,"deficient indentation"),n}s(rt,"skipSeparationSpace");function Fc(e){var t=e.position,r;return r=e.input.charCodeAt(t),!!((r===45||r===46)&&r===e.input.charCodeAt(t+1)&&r===e.input.charCodeAt(t+2)&&(t+=3,r=e.input.charCodeAt(t),r===0||Vt(r)))}s(Fc,"testDocumentSeparator");function Vp(e,t){t===1?e.result+=" ":t>1&&(e.result+=cn.repeat(`
674
+ `,t-1))}s(Vp,"writeFoldedLines");function hM(e,t,r){var n,o,i,a,l,d,f,m,g=e.kind,h=e.result,y;if(y=e.input.charCodeAt(e.position),Vt(y)||Ws(y)||y===35||y===38||y===42||y===33||y===124||y===62||y===39||y===34||y===37||y===64||y===96||(y===63||y===45)&&(o=e.input.charCodeAt(e.position+1),Vt(o)||r&&Ws(o)))return!1;for(e.kind="scalar",e.result="",i=a=e.position,l=!1;y!==0;){if(y===58){if(o=e.input.charCodeAt(e.position+1),Vt(o)||r&&Ws(o))break}else if(y===35){if(n=e.input.charCodeAt(e.position-1),Vt(n))break}else{if(e.position===e.lineStart&&Fc(e)||r&&Ws(y))break;if(Vr(y))if(d=e.line,f=e.lineStart,m=e.lineIndent,rt(e,!1,-1),e.lineIndent>=t){l=!0,y=e.input.charCodeAt(e.position);continue}else{e.position=a,e.line=d,e.lineStart=f,e.lineIndent=m;break}}l&&(Vn(e,i,a,!1),Vp(e,e.line-d),i=a=e.position,l=!1),Po(y)||(a=e.position+1),y=e.input.charCodeAt(++e.position)}return Vn(e,i,a,!1),e.result?!0:(e.kind=g,e.result=h,!1)}s(hM,"readPlainScalar");function yM(e,t){var r,n,o;if(r=e.input.charCodeAt(e.position),r!==39)return!1;for(e.kind="scalar",e.result="",e.position++,n=o=e.position;(r=e.input.charCodeAt(e.position))!==0;)if(r===39)if(Vn(e,n,e.position,!0),r=e.input.charCodeAt(++e.position),r===39)n=e.position,e.position++,o=e.position;else return!0;else Vr(r)?(Vn(e,n,o,!0),Vp(e,rt(e,!1,t)),n=o=e.position):e.position===e.lineStart&&Fc(e)?Y(e,"unexpected end of the document within a single quoted scalar"):(e.position++,o=e.position);Y(e,"unexpected end of the stream within a single quoted scalar")}s(yM,"readSingleQuotedScalar");function vM(e,t){var r,n,o,i,a,l;if(l=e.input.charCodeAt(e.position),l!==34)return!1;for(e.kind="scalar",e.result="",e.position++,r=n=e.position;(l=e.input.charCodeAt(e.position))!==0;){if(l===34)return Vn(e,r,e.position,!0),e.position++,!0;if(l===92){if(Vn(e,r,e.position,!0),l=e.input.charCodeAt(++e.position),Vr(l))rt(e,!1,t);else if(l<256&&Ax[l])e.result+=kx[l],e.position++;else if((a=pM(l))>0){for(o=a,i=0;o>0;o--)l=e.input.charCodeAt(++e.position),(a=dM(l))>=0?i=(i<<4)+a:Y(e,"expected hexadecimal character");e.result+=mM(i),e.position++}else Y(e,"unknown escape sequence");r=n=e.position}else Vr(l)?(Vn(e,r,n,!0),Vp(e,rt(e,!1,t)),r=n=e.position):e.position===e.lineStart&&Fc(e)?Y(e,"unexpected end of the document within a double quoted scalar"):(e.position++,n=e.position)}Y(e,"unexpected end of the stream within a double quoted scalar")}s(vM,"readDoubleQuotedScalar");function SM(e,t){var r=!0,n,o=e.tag,i,a=e.anchor,l,d,f,m,g,h={},y,E,w,v;if(v=e.input.charCodeAt(e.position),v===91)d=93,g=!1,i=[];else if(v===123)d=125,g=!0,i={};else return!1;for(e.anchor!==null&&(e.anchorMap[e.anchor]=i),v=e.input.charCodeAt(++e.position);v!==0;){if(rt(e,!0,t),v=e.input.charCodeAt(e.position),v===d)return e.position++,e.tag=o,e.anchor=a,e.kind=g?"mapping":"sequence",e.result=i,!0;r||Y(e,"missed comma between flow collection entries"),E=y=w=null,f=m=!1,v===63&&(l=e.input.charCodeAt(e.position+1),Vt(l)&&(f=m=!0,e.position++,rt(e,!0,t))),n=e.line,Js(e,t,Pc,!1,!0),E=e.tag,y=e.result,rt(e,!0,t),v=e.input.charCodeAt(e.position),(m||e.line===n)&&v===58&&(f=!0,v=e.input.charCodeAt(++e.position),rt(e,!0,t),Js(e,t,Pc,!1,!0),w=e.result),g?Gs(e,i,h,E,y,w):f?i.push(Gs(e,null,h,E,y,w)):i.push(y),rt(e,!0,t),v=e.input.charCodeAt(e.position),v===44?(r=!0,v=e.input.charCodeAt(++e.position)):r=!1}Y(e,"unexpected end of the stream within a flow collection")}s(SM,"readFlowCollection");function wM(e,t){var r,n,o=Bp,i=!1,a=!1,l=t,d=0,f=!1,m,g;if(g=e.input.charCodeAt(e.position),g===124)n=!1;else if(g===62)n=!0;else return!1;for(e.kind="scalar",e.result="";g!==0;)if(g=e.input.charCodeAt(++e.position),g===43||g===45)Bp===o?o=g===43?mx:aM:Y(e,"repeat of a chomping mode identifier");else if((m=fM(g))>=0)m===0?Y(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):a?Y(e,"repeat of an indentation width identifier"):(l=t+m-1,a=!0);else break;if(Po(g)){do g=e.input.charCodeAt(++e.position);while(Po(g));if(g===35)do g=e.input.charCodeAt(++e.position);while(!Vr(g)&&g!==0)}for(;g!==0;){for($p(e),e.lineIndent=0,g=e.input.charCodeAt(e.position);(!a||e.lineIndent<l)&&g===32;)e.lineIndent++,g=e.input.charCodeAt(++e.position);if(!a&&e.lineIndent>l&&(l=e.lineIndent),Vr(g)){d++;continue}if(e.lineIndent<l){o===mx?e.result+=cn.repeat(`
675
+ `,i?1+d:d):o===Bp&&i&&(e.result+=`
676
+ `);break}for(n?Po(g)?(f=!0,e.result+=cn.repeat(`
677
+ `,i?1+d:d)):f?(f=!1,e.result+=cn.repeat(`
678
+ `,d+1)):d===0?i&&(e.result+=" "):e.result+=cn.repeat(`
679
+ `,d):e.result+=cn.repeat(`
680
+ `,i?1+d:d),i=!0,a=!0,d=0,r=e.position;!Vr(g)&&g!==0;)g=e.input.charCodeAt(++e.position);Vn(e,r,e.position,!1)}return!0}s(wM,"readBlockScalar");function Sx(e,t){var r,n=e.tag,o=e.anchor,i=[],a,l=!1,d;for(e.anchor!==null&&(e.anchorMap[e.anchor]=i),d=e.input.charCodeAt(e.position);d!==0&&!(d!==45||(a=e.input.charCodeAt(e.position+1),!Vt(a)));){if(l=!0,e.position++,rt(e,!0,-1)&&e.lineIndent<=t){i.push(null),d=e.input.charCodeAt(e.position);continue}if(r=e.line,Js(e,t,Ex,!1,!0),i.push(e.result),rt(e,!0,-1),d=e.input.charCodeAt(e.position),(e.line===r||e.lineIndent>t)&&d!==0)Y(e,"bad indentation of a sequence entry");else if(e.lineIndent<t)break}return l?(e.tag=n,e.anchor=o,e.kind="sequence",e.result=i,!0):!1}s(Sx,"readBlockSequence");function xM(e,t,r){var n,o,i,a,l=e.tag,d=e.anchor,f={},m={},g=null,h=null,y=null,E=!1,w=!1,v;for(e.anchor!==null&&(e.anchorMap[e.anchor]=f),v=e.input.charCodeAt(e.position);v!==0;){if(n=e.input.charCodeAt(e.position+1),i=e.line,a=e.position,(v===63||v===58)&&Vt(n))v===63?(E&&(Gs(e,f,m,g,h,null),g=h=y=null),w=!0,E=!0,o=!0):E?(E=!1,o=!0):Y(e,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),e.position+=1,v=n;else if(Js(e,r,bx,!1,!0))if(e.line===i){for(v=e.input.charCodeAt(e.position);Po(v);)v=e.input.charCodeAt(++e.position);if(v===58)v=e.input.charCodeAt(++e.position),Vt(v)||Y(e,"a whitespace character is expected after the key-value separator within a block mapping"),E&&(Gs(e,f,m,g,h,null),g=h=y=null),w=!0,E=!1,o=!1,g=e.tag,h=e.result;else if(w)Y(e,"can not read an implicit mapping pair; a colon is missed");else return e.tag=l,e.anchor=d,!0}else if(w)Y(e,"can not read a block mapping entry; a multiline key may not be an implicit key");else return e.tag=l,e.anchor=d,!0;else break;if((e.line===i||e.lineIndent>t)&&(Js(e,t,Nc,!0,o)&&(E?h=e.result:y=e.result),E||(Gs(e,f,m,g,h,y,i,a),g=h=y=null),rt(e,!0,-1),v=e.input.charCodeAt(e.position)),e.lineIndent>t&&v!==0)Y(e,"bad indentation of a mapping entry");else if(e.lineIndent<t)break}return E&&Gs(e,f,m,g,h,null),w&&(e.tag=l,e.anchor=d,e.kind="mapping",e.result=f),w}s(xM,"readBlockMapping");function bM(e){var t,r=!1,n=!1,o,i,a;if(a=e.input.charCodeAt(e.position),a!==33)return!1;if(e.tag!==null&&Y(e,"duplication of a tag property"),a=e.input.charCodeAt(++e.position),a===60?(r=!0,a=e.input.charCodeAt(++e.position)):a===33?(n=!0,o="!!",a=e.input.charCodeAt(++e.position)):o="!",t=e.position,r){do a=e.input.charCodeAt(++e.position);while(a!==0&&a!==62);e.position<e.length?(i=e.input.slice(t,e.position),a=e.input.charCodeAt(++e.position)):Y(e,"unexpected end of the stream within a verbatim tag")}else{for(;a!==0&&!Vt(a);)a===33&&(n?Y(e,"tag suffix cannot contain exclamation marks"):(o=e.input.slice(t-1,e.position+1),Ix.test(o)||Y(e,"named tag handle cannot contain such characters"),n=!0,t=e.position+1)),a=e.input.charCodeAt(++e.position);i=e.input.slice(t,e.position),uM.test(i)&&Y(e,"tag suffix cannot contain flow indicator characters")}return i&&!Tx.test(i)&&Y(e,"tag name cannot contain such characters: "+i),r?e.tag=i:Hn.call(e.tagMap,o)?e.tag=e.tagMap[o]+i:o==="!"?e.tag="!"+i:o==="!!"?e.tag="tag:yaml.org,2002:"+i:Y(e,'undeclared tag handle "'+o+'"'),!0}s(bM,"readTagProperty");function EM(e){var t,r;if(r=e.input.charCodeAt(e.position),r!==38)return!1;for(e.anchor!==null&&Y(e,"duplication of an anchor property"),r=e.input.charCodeAt(++e.position),t=e.position;r!==0&&!Vt(r)&&!Ws(r);)r=e.input.charCodeAt(++e.position);return e.position===t&&Y(e,"name of an anchor node must contain at least one character"),e.anchor=e.input.slice(t,e.position),!0}s(EM,"readAnchorProperty");function IM(e){var t,r,n;if(n=e.input.charCodeAt(e.position),n!==42)return!1;for(n=e.input.charCodeAt(++e.position),t=e.position;n!==0&&!Vt(n)&&!Ws(n);)n=e.input.charCodeAt(++e.position);return e.position===t&&Y(e,"name of an alias node must contain at least one character"),r=e.input.slice(t,e.position),Hn.call(e.anchorMap,r)||Y(e,'unidentified alias "'+r+'"'),e.result=e.anchorMap[r],rt(e,!0,-1),!0}s(IM,"readAlias");function Js(e,t,r,n,o){var i,a,l,d=1,f=!1,m=!1,g,h,y,E,w;if(e.listener!==null&&e.listener("open",e),e.tag=null,e.anchor=null,e.kind=null,e.result=null,i=a=l=Nc===r||Ex===r,n&&rt(e,!0,-1)&&(f=!0,e.lineIndent>t?d=1:e.lineIndent===t?d=0:e.lineIndent<t&&(d=-1)),d===1)for(;bM(e)||EM(e);)rt(e,!0,-1)?(f=!0,l=i,e.lineIndent>t?d=1:e.lineIndent===t?d=0:e.lineIndent<t&&(d=-1)):l=!1;if(l&&(l=f||o),(d===1||Nc===r)&&(Pc===r||bx===r?E=t:E=t+1,w=e.position-e.lineStart,d===1?l&&(Sx(e,w)||xM(e,w,E))||SM(e,E)?m=!0:(a&&wM(e,E)||yM(e,E)||vM(e,E)?m=!0:IM(e)?(m=!0,(e.tag!==null||e.anchor!==null)&&Y(e,"alias node should not have any properties")):hM(e,E,Pc===r)&&(m=!0,e.tag===null&&(e.tag="?")),e.anchor!==null&&(e.anchorMap[e.anchor]=e.result)):d===0&&(m=l&&Sx(e,w))),e.tag!==null&&e.tag!=="!")if(e.tag==="?"){for(e.result!==null&&e.kind!=="scalar"&&Y(e,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+e.kind+'"'),g=0,h=e.implicitTypes.length;g<h;g+=1)if(y=e.implicitTypes[g],y.resolve(e.result)){e.result=y.construct(e.result),e.tag=y.tag,e.anchor!==null&&(e.anchorMap[e.anchor]=e.result);break}}else Hn.call(e.typeMap[e.kind||"fallback"],e.tag)?(y=e.typeMap[e.kind||"fallback"][e.tag],e.result!==null&&y.kind!==e.kind&&Y(e,"unacceptable node kind for !<"+e.tag+'> tag; it should be "'+y.kind+'", not "'+e.kind+'"'),y.resolve(e.result)?(e.result=y.construct(e.result),e.anchor!==null&&(e.anchorMap[e.anchor]=e.result)):Y(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):Y(e,"unknown tag !<"+e.tag+">");return e.listener!==null&&e.listener("close",e),e.tag!==null||e.anchor!==null||m}s(Js,"composeNode");function TM(e){var t=e.position,r,n,o,i=!1,a;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};(a=e.input.charCodeAt(e.position))!==0&&(rt(e,!0,-1),a=e.input.charCodeAt(e.position),!(e.lineIndent>0||a!==37));){for(i=!0,a=e.input.charCodeAt(++e.position),r=e.position;a!==0&&!Vt(a);)a=e.input.charCodeAt(++e.position);for(n=e.input.slice(r,e.position),o=[],n.length<1&&Y(e,"directive name must not be less than one character in length");a!==0;){for(;Po(a);)a=e.input.charCodeAt(++e.position);if(a===35){do a=e.input.charCodeAt(++e.position);while(a!==0&&!Vr(a));break}if(Vr(a))break;for(r=e.position;a!==0&&!Vt(a);)a=e.input.charCodeAt(++e.position);o.push(e.input.slice(r,e.position))}a!==0&&$p(e),Hn.call(yx,n)?yx[n](e,n,o):Lc(e,'unknown document directive "'+n+'"')}if(rt(e,!0,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45?(e.position+=3,rt(e,!0,-1)):i&&Y(e,"directives end mark is expected"),Js(e,e.lineIndent-1,Nc,!1,!0),rt(e,!0,-1),e.checkLineBreaks&&cM.test(e.input.slice(t,e.position))&&Lc(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&Fc(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,rt(e,!0,-1));return}if(e.position<e.length-1)Y(e,"end of the stream or a document separator is expected");else return}s(TM,"readDocument");function Cx(e,t){e=String(e),t=t||{},e.length!==0&&(e.charCodeAt(e.length-1)!==10&&e.charCodeAt(e.length-1)!==13&&(e+=`
681
+ `),e.charCodeAt(0)===65279&&(e=e.slice(1)));var r=new gM(e,t),n=e.indexOf("\0");for(n!==-1&&(r.position=n,Y(r,"null byte is not allowed in input")),r.input+="\0";r.input.charCodeAt(r.position)===32;)r.lineIndent+=1,r.position+=1;for(;r.position<r.length-1;)TM(r);return r.documents}s(Cx,"loadDocuments");function Dx(e,t,r){t!==null&&typeof t=="object"&&typeof r>"u"&&(r=t,t=null);var n=Cx(e,r);if(typeof t!="function")return n;for(var o=0,i=n.length;o<i;o+=1)t(n[o])}s(Dx,"loadAll");function Ox(e,t){var r=Cx(e,t);if(r.length!==0){if(r.length===1)return r[0];throw new wx("expected a single document in the stream, but found more")}}s(Ox,"load");function _M(e,t,r){return typeof t=="object"&&t!==null&&typeof r>"u"&&(r=t,t=null),Dx(e,t,cn.extend({schema:xx},r))}s(_M,"safeLoadAll");function AM(e,t){return Ox(e,cn.extend({schema:xx},t))}s(AM,"safeLoad");Ta.exports.loadAll=Dx;Ta.exports.load=Ox;Ta.exports.safeLoadAll=_M;Ta.exports.safeLoad=AM});var rb=V((t6,Jp)=>{"use strict";var Aa=Co(),ka=$s(),kM=Ia(),RM=Hs(),Bx=Object.prototype.toString,$x=Object.prototype.hasOwnProperty,CM=9,_a=10,DM=13,OM=32,MM=33,PM=34,Vx=35,NM=37,LM=38,FM=39,jM=42,Hx=44,UM=45,Wx=58,qM=61,BM=62,$M=63,VM=64,Gx=91,Jx=93,HM=96,zx=123,WM=124,Kx=125,It={};It[0]="\\0";It[7]="\\a";It[8]="\\b";It[9]="\\t";It[10]="\\n";It[11]="\\v";It[12]="\\f";It[13]="\\r";It[27]="\\e";It[34]='\\"';It[92]="\\\\";It[133]="\\N";It[160]="\\_";It[8232]="\\L";It[8233]="\\P";var GM=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"];function JM(e,t){var r,n,o,i,a,l,d;if(t===null)return{};for(r={},n=Object.keys(t),o=0,i=n.length;o<i;o+=1)a=n[o],l=String(t[a]),a.slice(0,2)==="!!"&&(a="tag:yaml.org,2002:"+a.slice(2)),d=e.compiledTypeMap.fallback[a],d&&$x.call(d.styleAliases,l)&&(l=d.styleAliases[l]),r[a]=l;return r}s(JM,"compileStyleMap");function Px(e){var t,r,n;if(t=e.toString(16).toUpperCase(),e<=255)r="x",n=2;else if(e<=65535)r="u",n=4;else if(e<=4294967295)r="U",n=8;else throw new ka("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+r+Aa.repeat("0",n-t.length)+t}s(Px,"encodeHex");function zM(e){this.schema=e.schema||kM,this.indent=Math.max(1,e.indent||2),this.noArrayIndent=e.noArrayIndent||!1,this.skipInvalid=e.skipInvalid||!1,this.flowLevel=Aa.isNothing(e.flowLevel)?-1:e.flowLevel,this.styleMap=JM(this.schema,e.styles||null),this.sortKeys=e.sortKeys||!1,this.lineWidth=e.lineWidth||80,this.noRefs=e.noRefs||!1,this.noCompatMode=e.noCompatMode||!1,this.condenseFlow=e.condenseFlow||!1,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}s(zM,"State");function Nx(e,t){for(var r=Aa.repeat(" ",t),n=0,o=-1,i="",a,l=e.length;n<l;)o=e.indexOf(`
682
+ `,n),o===-1?(a=e.slice(n),n=l):(a=e.slice(n,o+1),n=o+1),a.length&&a!==`
683
+ `&&(i+=r),i+=a;return i}s(Nx,"indentString");function Hp(e,t){return`
684
+ `+Aa.repeat(" ",e.indent*t)}s(Hp,"generateNextLine");function KM(e,t){var r,n,o;for(r=0,n=e.implicitTypes.length;r<n;r+=1)if(o=e.implicitTypes[r],o.resolve(t))return!0;return!1}s(KM,"testImplicitResolving");function Gp(e){return e===OM||e===CM}s(Gp,"isWhitespace");function zs(e){return 32<=e&&e<=126||161<=e&&e<=55295&&e!==8232&&e!==8233||57344<=e&&e<=65533&&e!==65279||65536<=e&&e<=1114111}s(zs,"isPrintable");function YM(e){return zs(e)&&!Gp(e)&&e!==65279&&e!==DM&&e!==_a}s(YM,"isNsChar");function Lx(e,t){return zs(e)&&e!==65279&&e!==Hx&&e!==Gx&&e!==Jx&&e!==zx&&e!==Kx&&e!==Wx&&(e!==Vx||t&&YM(t))}s(Lx,"isPlainSafe");function XM(e){return zs(e)&&e!==65279&&!Gp(e)&&e!==UM&&e!==$M&&e!==Wx&&e!==Hx&&e!==Gx&&e!==Jx&&e!==zx&&e!==Kx&&e!==Vx&&e!==LM&&e!==jM&&e!==MM&&e!==WM&&e!==qM&&e!==BM&&e!==FM&&e!==PM&&e!==NM&&e!==VM&&e!==HM}s(XM,"isPlainSafeFirst");function Yx(e){var t=/^\n* /;return t.test(e)}s(Yx,"needIndentIndicator");var Xx=1,Zx=2,Qx=3,eb=4,jc=5;function ZM(e,t,r,n,o){var i,a,l,d=!1,f=!1,m=n!==-1,g=-1,h=XM(e.charCodeAt(0))&&!Gp(e.charCodeAt(e.length-1));if(t)for(i=0;i<e.length;i++){if(a=e.charCodeAt(i),!zs(a))return jc;l=i>0?e.charCodeAt(i-1):null,h=h&&Lx(a,l)}else{for(i=0;i<e.length;i++){if(a=e.charCodeAt(i),a===_a)d=!0,m&&(f=f||i-g-1>n&&e[g+1]!==" ",g=i);else if(!zs(a))return jc;l=i>0?e.charCodeAt(i-1):null,h=h&&Lx(a,l)}f=f||m&&i-g-1>n&&e[g+1]!==" "}return!d&&!f?h&&!o(e)?Xx:Zx:r>9&&Yx(e)?jc:f?eb:Qx}s(ZM,"chooseScalarStyle");function QM(e,t,r,n){e.dump=(function(){if(t.length===0)return"''";if(!e.noCompatMode&&GM.indexOf(t)!==-1)return"'"+t+"'";var o=e.indent*Math.max(1,r),i=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-o),a=n||e.flowLevel>-1&&r>=e.flowLevel;function l(d){return KM(e,d)}switch(s(l,"testAmbiguity"),ZM(t,a,e.indent,i,l)){case Xx:return t;case Zx:return"'"+t.replace(/'/g,"''")+"'";case Qx:return"|"+Fx(t,e.indent)+jx(Nx(t,o));case eb:return">"+Fx(t,e.indent)+jx(Nx(eP(t,i),o));case jc:return'"'+tP(t,i)+'"';default:throw new ka("impossible error: invalid scalar style")}})()}s(QM,"writeScalar");function Fx(e,t){var r=Yx(e)?String(t):"",n=e[e.length-1]===`
685
+ `,o=n&&(e[e.length-2]===`
686
+ `||e===`
687
+ `),i=o?"+":n?"":"-";return r+i+`
688
+ `}s(Fx,"blockHeader");function jx(e){return e[e.length-1]===`
689
+ `?e.slice(0,-1):e}s(jx,"dropEndingNewline");function eP(e,t){for(var r=/(\n+)([^\n]*)/g,n=(function(){var f=e.indexOf(`
690
+ `);return f=f!==-1?f:e.length,r.lastIndex=f,Ux(e.slice(0,f),t)})(),o=e[0]===`
691
+ `||e[0]===" ",i,a;a=r.exec(e);){var l=a[1],d=a[2];i=d[0]===" ",n+=l+(!o&&!i&&d!==""?`
692
+ `:"")+Ux(d,t),o=i}return n}s(eP,"foldString");function Ux(e,t){if(e===""||e[0]===" ")return e;for(var r=/ [^ ]/g,n,o=0,i,a=0,l=0,d="";n=r.exec(e);)l=n.index,l-o>t&&(i=a>o?a:l,d+=`
693
+ `+e.slice(o,i),o=i+1),a=l;return d+=`
694
+ `,e.length-o>t&&a>o?d+=e.slice(o,a)+`
695
+ `+e.slice(a+1):d+=e.slice(o),d.slice(1)}s(Ux,"foldLine");function tP(e){for(var t="",r,n,o,i=0;i<e.length;i++){if(r=e.charCodeAt(i),r>=55296&&r<=56319&&(n=e.charCodeAt(i+1),n>=56320&&n<=57343)){t+=Px((r-55296)*1024+n-56320+65536),i++;continue}o=It[r],t+=!o&&zs(r)?e[i]:o||Px(r)}return t}s(tP,"escapeString");function rP(e,t,r){var n="",o=e.tag,i,a;for(i=0,a=r.length;i<a;i+=1)No(e,t,r[i],!1,!1)&&(i!==0&&(n+=","+(e.condenseFlow?"":" ")),n+=e.dump);e.tag=o,e.dump="["+n+"]"}s(rP,"writeFlowSequence");function nP(e,t,r,n){var o="",i=e.tag,a,l;for(a=0,l=r.length;a<l;a+=1)No(e,t+1,r[a],!0,!0)&&((!n||a!==0)&&(o+=Hp(e,t)),e.dump&&_a===e.dump.charCodeAt(0)?o+="-":o+="- ",o+=e.dump);e.tag=i,e.dump=o||"[]"}s(nP,"writeBlockSequence");function oP(e,t,r){var n="",o=e.tag,i=Object.keys(r),a,l,d,f,m;for(a=0,l=i.length;a<l;a+=1)m="",a!==0&&(m+=", "),e.condenseFlow&&(m+='"'),d=i[a],f=r[d],No(e,t,d,!1,!1)&&(e.dump.length>1024&&(m+="? "),m+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),No(e,t,f,!1,!1)&&(m+=e.dump,n+=m));e.tag=o,e.dump="{"+n+"}"}s(oP,"writeFlowMapping");function sP(e,t,r,n){var o="",i=e.tag,a=Object.keys(r),l,d,f,m,g,h;if(e.sortKeys===!0)a.sort();else if(typeof e.sortKeys=="function")a.sort(e.sortKeys);else if(e.sortKeys)throw new ka("sortKeys must be a boolean or a function");for(l=0,d=a.length;l<d;l+=1)h="",(!n||l!==0)&&(h+=Hp(e,t)),f=a[l],m=r[f],No(e,t+1,f,!0,!0,!0)&&(g=e.tag!==null&&e.tag!=="?"||e.dump&&e.dump.length>1024,g&&(e.dump&&_a===e.dump.charCodeAt(0)?h+="?":h+="? "),h+=e.dump,g&&(h+=Hp(e,t)),No(e,t+1,m,!0,g)&&(e.dump&&_a===e.dump.charCodeAt(0)?h+=":":h+=": ",h+=e.dump,o+=h));e.tag=i,e.dump=o||"{}"}s(sP,"writeBlockMapping");function qx(e,t,r){var n,o,i,a,l,d;for(o=r?e.explicitTypes:e.implicitTypes,i=0,a=o.length;i<a;i+=1)if(l=o[i],(l.instanceOf||l.predicate)&&(!l.instanceOf||typeof t=="object"&&t instanceof l.instanceOf)&&(!l.predicate||l.predicate(t))){if(e.tag=r?l.tag:"?",l.represent){if(d=e.styleMap[l.tag]||l.defaultStyle,Bx.call(l.represent)==="[object Function]")n=l.represent(t,d);else if($x.call(l.represent,d))n=l.represent[d](t,d);else throw new ka("!<"+l.tag+'> tag resolver accepts not "'+d+'" style');e.dump=n}return!0}return!1}s(qx,"detectType");function No(e,t,r,n,o,i){e.tag=null,e.dump=r,qx(e,r,!1)||qx(e,r,!0);var a=Bx.call(e.dump);n&&(n=e.flowLevel<0||e.flowLevel>t);var l=a==="[object Object]"||a==="[object Array]",d,f;if(l&&(d=e.duplicates.indexOf(r),f=d!==-1),(e.tag!==null&&e.tag!=="?"||f||e.indent!==2&&t>0)&&(o=!1),f&&e.usedDuplicates[d])e.dump="*ref_"+d;else{if(l&&f&&!e.usedDuplicates[d]&&(e.usedDuplicates[d]=!0),a==="[object Object]")n&&Object.keys(e.dump).length!==0?(sP(e,t,e.dump,o),f&&(e.dump="&ref_"+d+e.dump)):(oP(e,t,e.dump),f&&(e.dump="&ref_"+d+" "+e.dump));else if(a==="[object Array]"){var m=e.noArrayIndent&&t>0?t-1:t;n&&e.dump.length!==0?(nP(e,m,e.dump,o),f&&(e.dump="&ref_"+d+e.dump)):(rP(e,m,e.dump),f&&(e.dump="&ref_"+d+" "+e.dump))}else if(a==="[object String]")e.tag!=="?"&&QM(e,e.dump,t,i);else{if(e.skipInvalid)return!1;throw new ka("unacceptable kind of an object to dump "+a)}e.tag!==null&&e.tag!=="?"&&(e.dump="!<"+e.tag+"> "+e.dump)}return!0}s(No,"writeNode");function iP(e,t){var r=[],n=[],o,i;for(Wp(e,r,n),o=0,i=n.length;o<i;o+=1)t.duplicates.push(r[n[o]]);t.usedDuplicates=new Array(i)}s(iP,"getDuplicateReferences");function Wp(e,t,r){var n,o,i;if(e!==null&&typeof e=="object")if(o=t.indexOf(e),o!==-1)r.indexOf(o)===-1&&r.push(o);else if(t.push(e),Array.isArray(e))for(o=0,i=e.length;o<i;o+=1)Wp(e[o],t,r);else for(n=Object.keys(e),o=0,i=n.length;o<i;o+=1)Wp(e[n[o]],t,r)}s(Wp,"inspectNode");function tb(e,t){t=t||{};var r=new zM(t);return r.noRefs||iP(e,r),No(r,0,e,!0,!0)?r.dump+`
696
+ `:""}s(tb,"dump");function aP(e,t){return tb(e,Aa.extend({schema:RM},t))}s(aP,"safeDump");Jp.exports.dump=tb;Jp.exports.safeDump=aP});var ob=V((n6,We)=>{"use strict";var Uc=Mx(),nb=rb();function qc(e){return function(){throw new Error("Function "+e+" is deprecated and cannot be used.")}}s(qc,"deprecated");We.exports.Type=ot();We.exports.Schema=Do();We.exports.FAILSAFE_SCHEMA=Oc();We.exports.JSON_SCHEMA=jp();We.exports.CORE_SCHEMA=Up();We.exports.DEFAULT_SAFE_SCHEMA=Hs();We.exports.DEFAULT_FULL_SCHEMA=Ia();We.exports.load=Uc.load;We.exports.loadAll=Uc.loadAll;We.exports.safeLoad=Uc.safeLoad;We.exports.safeLoadAll=Uc.safeLoadAll;We.exports.dump=nb.dump;We.exports.safeDump=nb.safeDump;We.exports.YAMLException=$s();We.exports.MINIMAL_SCHEMA=Oc();We.exports.SAFE_SCHEMA=Hs();We.exports.DEFAULT_SCHEMA=Ia();We.exports.scan=qc("scan");We.exports.parse=qc("parse");We.exports.compose=qc("compose");We.exports.addConstructor=qc("addConstructor")});var ib=V((s6,sb)=>{"use strict";var lP=ob();sb.exports=lP});var zp=V((exports,module)=>{"use strict";var yaml=ib(),engines=exports=module.exports;engines.yaml={parse:yaml.safeLoad.bind(yaml),stringify:yaml.safeDump.bind(yaml)};engines.json={parse:JSON.parse.bind(JSON),stringify:s(function(e,t){let r=Object.assign({replacer:null,space:2},t);return JSON.stringify(e,r.replacer,r.space)},"stringify")};engines.javascript={parse:s(function parse(str,options,wrap){try{return wrap!==!1&&(str=`(function() {
697
+ return `+str.trim()+`;
698
+ }());`),eval(str)||{}}catch(e){if(wrap!==!1&&/(unexpected|identifier)/i.test(e.message))return parse(str,options,!1);throw new SyntaxError(e)}},"parse"),stringify:s(function(){throw new Error("stringifying JavaScript is not supported")},"stringify")}});var lb=V((a6,ab)=>{"use strict";ab.exports=function(e){return typeof e=="string"&&e.charAt(0)==="\uFEFF"?e.slice(1):e}});var Bc=V(un=>{"use strict";var cb=lb(),ub=ba();un.define=function(e,t,r){Reflect.defineProperty(e,t,{enumerable:!1,configurable:!0,writable:!0,value:r})};un.isBuffer=function(e){return ub(e)==="buffer"};un.isObject=function(e){return ub(e)==="object"};un.toBuffer=function(e){return typeof e=="string"?Buffer.from(e):e};un.toString=function(e){if(un.isBuffer(e))return cb(String(e));if(typeof e!="string")throw new TypeError("expected input to be a string or buffer");return cb(e)};un.arrayify=function(e){return e?Array.isArray(e)?e:[e]:[]};un.startsWith=function(e,t,r){return typeof r!="number"&&(r=t.length),e.slice(0,r)===t}});var Ra=V((c6,db)=>{"use strict";var cP=zp(),uP=Bc();db.exports=function(e){let t=Object.assign({},e);return t.delimiters=uP.arrayify(t.delims||t.delimiters||"---"),t.delimiters.length===1&&t.delimiters.push(t.delimiters[0]),t.language=(t.language||t.lang||"yaml").toLowerCase(),t.engines=Object.assign({},cP,t.parsers,t.engines),t}});var Kp=V((u6,pb)=>{"use strict";pb.exports=function(e,t){let r=t.engines[e]||t.engines[dP(e)];if(typeof r>"u")throw new Error('gray-matter engine "'+e+'" is not registered');return typeof r=="function"&&(r={parse:r}),r};function dP(e){switch(e.toLowerCase()){case"js":case"javascript":return"javascript";case"coffee":case"coffeescript":case"cson":return"coffee";case"yaml":case"yml":return"yaml";default:return e}}s(dP,"aliase")});var Yp=V((p6,fb)=>{"use strict";var pP=ba(),fP=Kp(),mP=Ra();fb.exports=function(e,t,r){if(t==null&&r==null)switch(pP(e)){case"object":t=e.data,r={};break;case"string":return e;default:throw new TypeError("expected file to be a string or object")}let n=e.content,o=mP(r);if(t==null){if(!o.data)return e;t=o.data}let i=e.language||o.language,a=fP(i,o);if(typeof a.stringify!="function")throw new TypeError('expected "'+i+'.stringify" to be a function');t=Object.assign({},e.data,t);let l=o.delimiters[0],d=o.delimiters[1],f=a.stringify(t,r).trim(),m="";return f!=="{}"&&(m=Ks(l)+Ks(f)+Ks(d)),typeof e.excerpt=="string"&&e.excerpt!==""&&n.indexOf(e.excerpt.trim())===-1&&(m+=Ks(e.excerpt)+Ks(d)),m+Ks(n)};function Ks(e){return e.slice(-1)!==`
699
+ `?e+`
700
+ `:e}s(Ks,"newline")});var gb=V((m6,mb)=>{"use strict";var gP=Ra();mb.exports=function(e,t){let r=gP(t);if(e.data==null&&(e.data={}),typeof r.excerpt=="function")return r.excerpt(e,r);let n=e.data.excerpt_separator||r.excerpt_separator;if(n==null&&(r.excerpt===!1||r.excerpt==null))return e;let o=typeof r.excerpt=="string"?r.excerpt:n||r.delimiters[0],i=e.content.indexOf(o);return i!==-1&&(e.excerpt=e.content.slice(0,i)),e}});var vb=V((g6,yb)=>{"use strict";var hb=ba(),hP=Yp(),Ys=Bc();yb.exports=function(e){return hb(e)!=="object"&&(e={content:e}),hb(e.data)!=="object"&&(e.data={}),e.contents&&e.content==null&&(e.content=e.contents),Ys.define(e,"orig",Ys.toBuffer(e.content)),Ys.define(e,"language",e.language||""),Ys.define(e,"matter",e.matter||""),Ys.define(e,"stringify",function(t,r){return r&&r.language&&(e.language=r.language),hP(e,t,r)}),e.content=Ys.toString(e.content),e.isEmpty=!1,e.excerpt="",e}});var wb=V((h6,Sb)=>{"use strict";var yP=Kp(),vP=Ra();Sb.exports=function(e,t,r){let n=vP(r),o=yP(e,n);if(typeof o.parse!="function")throw new TypeError('expected "'+e+'.parse" to be a function');return o.parse(t,n)}});var Ib=V((y6,Eb)=>{"use strict";var SP=Ve("fs"),wP=gw(),Xp=Ra(),xP=Yp(),xb=gb(),bP=zp(),EP=vb(),IP=wb(),bb=Bc();function Dt(e,t){if(e==="")return{data:{},content:e,excerpt:"",orig:e};let r=EP(e),n=Dt.cache[r.content];if(!t){if(n)return r=Object.assign({},n),r.orig=n.orig,r;Dt.cache[r.content]=r}return TP(r,t)}s(Dt,"matter");function TP(e,t){let r=Xp(t),n=r.delimiters[0],o=`
701
+ `+r.delimiters[1],i=e.content;r.language&&(e.language=r.language);let a=n.length;if(!bb.startsWith(i,n,a))return xb(e,r),e;if(i.charAt(a)===n.slice(-1))return e;i=i.slice(a);let l=i.length,d=Dt.language(i,r);d.name&&(e.language=d.name,i=i.slice(d.raw.length));let f=i.indexOf(o);return f===-1&&(f=l),e.matter=i.slice(0,f),e.matter.replace(/^\s*#[^\n]+/gm,"").trim()===""?(e.isEmpty=!0,e.empty=e.content,e.data={}):e.data=IP(e.language,e.matter,r),f===l?e.content="":(e.content=i.slice(f+o.length),e.content[0]==="\r"&&(e.content=e.content.slice(1)),e.content[0]===`
702
+ `&&(e.content=e.content.slice(1))),xb(e,r),(r.sections===!0||typeof r.section=="function")&&wP(e,r.section),e}s(TP,"parseMatter");Dt.engines=bP;Dt.stringify=function(e,t,r){return typeof e=="string"&&(e=Dt(e,r)),xP(e,t,r)};Dt.read=function(e,t){let r=SP.readFileSync(e,"utf8"),n=Dt(r,t);return n.path=e,n};Dt.test=function(e,t){return bb.startsWith(e,Xp(t).delimiters[0])};Dt.language=function(e,t){let n=Xp(t).delimiters[0];Dt.test(e)&&(e=e.slice(n.length));let o=e.slice(0,e.search(/\r?\n/));return{raw:o,name:o?o.trim():""}};Dt.cache={};Dt.clearCache=function(){Dt.cache={}};Eb.exports=Dt});var Fr={};H(Fr,{ID:()=>VA,WorkspaceV2:()=>Fr});var Hi={};H(Hi,{Event:()=>$A,ID:()=>BA,Workspace:()=>Hi});var Vi={};H(Vi,{ConnectionStatus:()=>Sy,Definitions:()=>qA,Failed:()=>xy,Ready:()=>wy,Status:()=>by,WorkspaceEvent:()=>Vi});var Sy=c.Struct({workspaceID:gl,status:c.Literals(["connected","connecting","disconnected","error"])}).annotate({identifier:"WorkspaceEvent.ConnectionStatus"}),wy=Pi.define({type:"workspace.ready",schema:{name:c.String}}),xy=Pi.define({type:"workspace.failed",schema:{message:c.String}}),by=Pi.define({type:"workspace.status",schema:Sy.fields}),qA=Pi.inventory(wy,xy,by);var BA=gl,$A=Vi;var VA=Hi.ID;var qt={};H(qt,{APIError:()=>KA,AbortedError:()=>GA,AgentPart:()=>Lh,AgentPartInput:()=>Zh,Assistant:()=>ey,AuthError:()=>WA,CompactionPart:()=>Fh,ContentFilterError:()=>XA,ContextOverflowError:()=>YA,Event:()=>oy,FilePart:()=>Nh,FilePartInput:()=>Xh,FilePartSource:()=>Ph,FileSource:()=>Dh,Format:()=>Th,Info:()=>ty,MessageID:()=>xh,OutputFormatJsonSchema:()=>Ih,OutputFormatText:()=>Eh,OutputLengthError:()=>HA,Part:()=>Kh,PartID:()=>bh,PatchPart:()=>Ah,ProviderQuotaError:()=>JA,Range:()=>Ch,ReasoningPart:()=>Rh,ResourceSource:()=>Mh,RetryPart:()=>Uh,SessionInfo:()=>ny,SessionV1:()=>qt,SnapshotPart:()=>_h,StepFinishPart:()=>Bh,StepStartPart:()=>qh,StructuredOutputError:()=>zA,SubtaskPart:()=>jh,SubtaskPartInput:()=>Qh,SymbolSource:()=>Oh,TextPart:()=>kh,TextPartInput:()=>Yh,ToolPart:()=>Jh,ToolState:()=>Gh,ToolStateCompleted:()=>Hh,ToolStateError:()=>Wh,ToolStatePending:()=>$h,ToolStateRunning:()=>Vh,User:()=>zh,WithParts:()=>ry});var vt=class e extends Error{static{s(this,"NamedError")}static hasName(t,r){return typeof t=="object"&&t!==null&&"name"in t&&t.name===r}static create(t,r){return e.createSchemaClass(t,c.isSchema(r)?r:c.Struct(r))}static createSchemaClass(t,r){let n=c.Struct({name:c.Literal(t),data:r}).annotate({identifier:t}),o=class extends e{constructor(a,l){super(t,l);this.data=a;this.name=t}data;static{s(this,"result")}static Schema=n;static EffectSchema=n;static tag=t;name=t;static isInstance(a){return e.hasName(a,t)}schema(){return n}toObject(){return{name:t,data:this.data}}};return Object.defineProperty(o,"name",{value:t}),o}static Unknown=e.create("UnknownError",{message:c.String,ref:c.optional(c.String)})};var HA=vt.create("MessageOutputLengthError",{}),WA=vt.create("ProviderAuthError",{providerID:c.String,message:c.String}),GA=vt.create("MessageAbortedError",{message:c.String}),JA=vt.create("ProviderQuotaError",{providerID:c.String,message:c.String,planType:c.optional(c.String),resetsAt:c.optional(c.Finite),statusCode:c.optional(zt),responseBody:c.optional(c.String)}),zA=vt.create("StructuredOutputError",{message:c.String,retries:zt}),KA=vt.create("APIError",{message:c.String,statusCode:c.optional(zt),isRetryable:c.Boolean,responseHeaders:c.optional(c.Record(c.String,c.String)),responseBody:c.optional(c.String),metadata:c.optional(c.Record(c.String,c.String))}),YA=vt.create("ContextOverflowError",{message:c.String,responseBody:c.optional(c.String)}),XA=vt.create("ContentFilterError",{message:c.String});var md={};H(md,{Action:()=>EA,Approval:()=>RA,AskInput:()=>CA,CorrectedError:()=>dd,DeniedError:()=>pd,Event:()=>OA,ID:()=>sd,NotFoundError:()=>fd,PermissionV1:()=>md,RejectedError:()=>ud,Reply:()=>AA,ReplyBody:()=>kA,ReplyInput:()=>DA,Request:()=>_A,Rule:()=>IA,Ruleset:()=>TA});var ud=class extends c.TaggedErrorClass()("PermissionRejectedError",{}){static{s(this,"RejectedError")}get message(){return"The user rejected permission to use this specific tool call."}},dd=class extends c.TaggedErrorClass()("PermissionCorrectedError",{feedback:c.String}){static{s(this,"CorrectedError")}get message(){return`The user rejected permission to use this specific tool call with the following feedback: ${this.feedback}`}},pd=class extends c.TaggedErrorClass()("PermissionDeniedError",{ruleset:c.Any}){static{s(this,"DeniedError")}get message(){return`The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules ${JSON.stringify(this.ruleset)}`}},fd=class extends c.TaggedErrorClass()("Permission.NotFoundError",{requestID:sd}){static{s(this,"NotFoundError")}};var Gi={};H(Gi,{AgentV2:()=>Gi,Color:()=>QA,ID:()=>Wi,Info:()=>_y,Service:()=>Ss,defaultID:()=>Ty,locationLayer:()=>ek,node:()=>tk});var nn={};H(nn,{Agent:()=>nn,Color:()=>Iy,ID:()=>Ey,Info:()=>ZA});var Ey=c.String.pipe(c.brand("AgentV2.ID")),Iy=c.Union([c.String.check(c.isPattern(/^#[0-9a-fA-F]{6}$/)),c.Literals(["primary","secondary","accent","success","warning","error","info"])]).annotate({identifier:"Agent.Color"}),ZA=c.Struct({id:Ey,model:hl.Ref.pipe(Je),request:Qg.Request,system:c.String.pipe(Je),description:c.String.pipe(Je),mode:c.Literals(["subagent","primary","all"]),hidden:c.Boolean,color:Iy.pipe(Je),steps:Yr.pipe(Je),permissions:eh.Ruleset}).annotate({identifier:"AgentV2.Info"}).pipe(ml(e=>({empty:s(t=>e.make({id:t,request:{headers:{},body:{}},mode:"all",hidden:!1,permissions:[]}),"empty")})));var Wi=nn.ID,Ty=Wi.make("build"),QA=nn.Color,_y=nn.Info,Ss=class extends ae.Service()("@opencode/v2/Agent"){static{s(this,"Service")}},Ay=B.effect(Ss,p.gen(function*(){let e=th.create({initial:s(()=>({agents:new Map}),"initial"),draft:s(n=>({list:s(()=>nl.fromIterable(n.agents.values()),"list"),get:s(o=>n.agents.get(o),"get"),default:s(o=>{n.default=o},"default"),update:s((o,i)=>{let a=n.agents.get(o)??_y.empty(o);n.agents.has(o)||n.agents.set(o,a),i(a),a.id=o},"update"),remove:s(o=>{n.agents.delete(o)},"remove")}),"draft")}),t=s(n=>n&&n.mode!=="subagent"&&!n.hidden?n:void 0,"selectable"),r=s(()=>{let n=e.get(),o=n.default?t(n.agents.get(n.default)):void 0;if(o)return o;let i=t(n.agents.get(Wi.make("build")));if(i)return i;for(let a of n.agents.values()){let l=t(a);if(l)return l}},"selectedDefault");return Ss.of({transform:e.transform,reload:e.reload,get:p.fn("AgentV2.get")(function*(n){return e.get().agents.get(n)}),default:p.fn("AgentV2.default")(function*(){return r()}),resolve:p.fn("AgentV2.resolve")(function*(n){return n!==void 0?e.get().agents.get(Wi.make(n)):r()}),select:p.fn("AgentV2.select")(function*(n){if(n!==void 0){let i=Wi.make(n);return{id:i,info:e.get().agents.get(i)}}let o=r();return{id:o?.id??Ty,info:o}}),all:p.fn("AgentV2.all")(function*(){return nl.fromIterable(e.get().agents.values())})})})),ek=Ay,tk=ds({service:Ss,layer:Ay,deps:[]});var ee=Ut("session",{id:z().$type().primaryKey(),project_id:z().$type().notNull().references(()=>vs.id,{onDelete:"cascade"}),workspace_id:z().$type(),parent_id:z().$type(),slug:z().notNull(),directory:vh().notNull(),path:Sh(),title:z().notNull(),version:z().notNull(),share_url:z(),summary_additions:qe(),summary_deletions:qe(),summary_files:qe(),summary_diffs:z({mode:"json"}).$type(),metadata:z({mode:"json"}).$type(),cost:ih().notNull().default(0),tokens_input:qe().notNull().default(0),tokens_output:qe().notNull().default(0),tokens_reasoning:qe().notNull().default(0),tokens_cache_read:qe().notNull().default(0),tokens_cache_write:qe().notNull().default(0),revert:z({mode:"json"}).$type(),permission:z({mode:"json"}).$type(),agent:z(),model:z({mode:"json"}).$type(),...tn,time_compacting:qe(),time_archived:qe()},e=>[dr("session_project_idx").on(e.project_id),dr("session_workspace_idx").on(e.workspace_id),dr("session_parent_idx").on(e.parent_id)]),so=Ut("message",{id:z().$type().primaryKey(),session_id:z().$type().notNull().references(()=>ee.id,{onDelete:"cascade"}),...tn,data:z({mode:"json"}).notNull().$type()},e=>[dr("message_session_time_created_id_idx").on(e.session_id,e.time_created,e.id)]),Bt=Ut("part",{id:z().$type().primaryKey(),message_id:z().$type().notNull().references(()=>so.id,{onDelete:"cascade"}),session_id:z().$type().notNull(),...tn,data:z({mode:"json"}).notNull().$type()},e=>[dr("part_message_id_id_idx").on(e.message_id,e.id),dr("part_session_idx").on(e.session_id)]),GV=Ut("todo",{session_id:z().$type().notNull().references(()=>ee.id,{onDelete:"cascade"}),content:z().notNull(),status:z().notNull(),priority:z().notNull(),position:qe().notNull(),...tn},e=>[Sl({columns:[e.session_id,e.position]}),dr("todo_session_idx").on(e.session_id)]),U=Ut("session_message",{id:z().$type().primaryKey(),session_id:z().$type().notNull().references(()=>ee.id,{onDelete:"cascade"}),type:z().$type().notNull(),seq:qe().notNull(),...tn,data:z({mode:"json"}).notNull().$type()},e=>[wl("session_message_session_seq_idx").on(e.session_id,e.seq),dr("session_message_session_type_seq_idx").on(e.session_id,e.type,e.seq),dr("session_message_session_time_created_id_idx").on(e.session_id,e.time_created,e.id),dr("session_message_time_created_idx").on(e.time_created)]),ge=Ut("session_input",{id:z().$type().primaryKey(),session_id:z().$type().notNull().references(()=>ee.id,{onDelete:"cascade"}),prompt:z({mode:"json"}).notNull().$type(),delivery:z().$type().notNull(),admitted_seq:qe().notNull(),promoted_seq:qe(),time_created:qe().notNull().$default(()=>Date.now())},e=>[dr("session_input_session_pending_delivery_seq_idx").on(e.session_id,e.promoted_seq,e.delivery,e.admitted_seq),wl("session_input_session_admitted_seq_idx").on(e.session_id,e.admitted_seq),wl("session_input_session_promoted_seq_idx").on(e.session_id,e.promoted_seq)]),Cl=Ut("session_context_epoch",{session_id:z().$type().primaryKey().references(()=>ee.id,{onDelete:"cascade"}),baseline:z().notNull(),snapshot:z({mode:"json"}).notNull().$type(),baseline_seq:qe().notNull()});var bs={};H(bs,{SessionAlreadyProjected:()=>Ql,SessionProjector:()=>bs,node:()=>Pk});var gd=Ut("workspace",{id:z().$type().primaryKey(),type:z().notNull(),name:z().notNull().default(""),branch:z(),directory:z(),extra:z({mode:"json"}),project_id:z().$type().notNull().references(()=>vs.id,{onDelete:"cascade"}),time_used:qe().notNull().$default(()=>Date.now())});var Z={};H(Z,{AgentSwitched:()=>sA,Assistant:()=>wA,AssistantContent:()=>SA,AssistantReasoning:()=>vA,AssistantText:()=>yA,AssistantTool:()=>hA,Compaction:()=>xA,ID:()=>nA,Message:()=>bA,ModelSwitched:()=>iA,SessionMessage:()=>Z,Shell:()=>uA,Synthetic:()=>lA,System:()=>cA,ToolState:()=>gA,ToolStateCompleted:()=>fA,ToolStateError:()=>mA,ToolStatePending:()=>dA,ToolStateRunning:()=>pA,UnknownError:()=>oA,User:()=>aA});var Xi={};H(Xi,{SessionMessageUpdater:()=>Xi,memory:()=>vk,update:()=>Sk});var Fy=Symbol.for("immer-nothing"),ky=Symbol.for("immer-draftable"),Ct=Symbol.for("immer-state"),rk=process.env.NODE_ENV!=="production"?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function Yt(e,...t){if(process.env.NODE_ENV!=="production"){let r=rk[e],n=io(r)?r.apply(null,t):r;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}s(Yt,"die");var Xt=Object,ws=Xt.getPrototypeOf,Pl="constructor",ql="prototype",vd="configurable",Nl="enumerable",Ol="writable",Ji="value",Ln=s(e=>!!e&&!!e[Ct],"isDraft");function sn(e){return e?jy(e)||$l(e)||!!e[ky]||!!e[Pl]?.[ky]||Vl(e)||Hl(e):!1}s(sn,"isDraftable");var nk=Xt[ql][Pl].toString(),Ry=new WeakMap;function jy(e){if(!e||!_d(e))return!1;let t=ws(e);if(t===null||t===Xt[ql])return!0;let r=Xt.hasOwnProperty.call(t,Pl)&&t[Pl];if(r===Object)return!0;if(!io(r))return!1;let n=Ry.get(r);return n===void 0&&(n=Function.toString.call(r),Ry.set(r,n)),n===nk}s(jy,"isPlainObject");function Bl(e,t,r=!0){Yi(e)===0?(r?Reflect.ownKeys(e):Xt.keys(e)).forEach(o=>{t(o,e[o],e)}):e.forEach((n,o)=>t(o,n,e))}s(Bl,"each");function Yi(e){let t=e[Ct];return t?t.type_:$l(e)?1:Vl(e)?2:Hl(e)?3:0}s(Yi,"getArchtype");var Cy=s((e,t,r=Yi(e))=>r===2?e.has(t):Xt[ql].hasOwnProperty.call(e,t),"has"),Sd=s((e,t,r=Yi(e))=>r===2?e.get(t):e[t],"get"),Ll=s((e,t,r,n=Yi(e))=>{n===2?e.set(t,r):n===3?e.add(r):e[t]=r},"set");function ok(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}s(ok,"is");var $l=Array.isArray,Vl=s(e=>e instanceof Map,"isMap"),Hl=s(e=>e instanceof Set,"isSet"),_d=s(e=>typeof e=="object","isObjectish"),io=s(e=>typeof e=="function","isFunction"),hd=s(e=>typeof e=="boolean","isBoolean");function sk(e){let t=+e;return Number.isInteger(t)&&String(t)===e}s(sk,"isArrayIndex");var on=s(e=>e.copy_||e.base_,"latest");var Ad=s(e=>e.modified_?e.copy_:e.base_,"getFinalValue");function wd(e,t){if(Vl(e))return new Map(e);if(Hl(e))return new Set(e);if($l(e))return Array[ql].slice.call(e);let r=jy(e);if(t===!0||t==="class_only"&&!r){let n=Xt.getOwnPropertyDescriptors(e);delete n[Ct];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let a=o[i],l=n[a];l[Ol]===!1&&(l[Ol]=!0,l[vd]=!0),(l.get||l.set)&&(n[a]={[vd]:!0,[Ol]:!0,[Nl]:l[Nl],[Ji]:e[a]})}return Xt.create(ws(e),n)}else{let n=ws(e);if(n!==null&&r)return{...e};let o=Xt.create(n);return Xt.assign(o,e)}}s(wd,"shallowCopy");function kd(e,t=!1){return Wl(e)||Ln(e)||!sn(e)||(Yi(e)>1&&Xt.defineProperties(e,{set:Dl,add:Dl,clear:Dl,delete:Dl}),Xt.freeze(e),t&&Bl(e,(r,n)=>{kd(n,!0)},!1)),e}s(kd,"freeze");function ik(){Yt(2)}s(ik,"dontMutateFrozenCollections");var Dl={[Ji]:ik};function Wl(e){return e===null||!_d(e)?!0:Xt.isFrozen(e)}s(Wl,"isFrozen");var Fl="MapSet",xd="Patches",Dy="ArrayMethods",Uy={};function ao(e){let t=Uy[e];return t||Yt(0,e),t}s(ao,"getPlugin");var Oy=s(e=>!!Uy[e],"isPluginLoaded");var zi,qy=s(()=>zi,"getCurrentScope"),ak=s((e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:Oy(Fl)?ao(Fl):void 0,arrayMethodsPlugin_:Oy(Dy)?ao(Dy):void 0}),"createScope");function My(e,t){t&&(e.patchPlugin_=ao(xd),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}s(My,"usePatchesInScope");function bd(e){Ed(e),e.drafts_.forEach(lk),e.drafts_=null}s(bd,"revokeScope");function Ed(e){e===zi&&(zi=e.parent_)}s(Ed,"leaveScope");var Py=s(e=>zi=ak(zi,e),"enterScope");function lk(e){let t=e[Ct];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}s(lk,"revokeDraft");function Ny(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];if(e!==void 0&&e!==r){r[Ct].modified_&&(bd(t),Yt(4)),sn(e)&&(e=Ly(t,e));let{patchPlugin_:o}=t;o&&o.generateReplacementPatches_(r[Ct].base_,e,t)}else e=Ly(t,r);return ck(t,e,!0),bd(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Fy?e:void 0}s(Ny,"processResult");function Ly(e,t){if(Wl(t))return t;let r=t[Ct];if(!r)return jl(t,e.handledSet_,e);if(!Gl(r,e))return t;if(!r.modified_)return r.base_;if(!r.finalized_){let{callbacks_:n}=r;if(n)for(;n.length>0;)n.pop()(e);Vy(r,e)}return r.copy_}s(Ly,"finalize");function ck(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&kd(t,r)}s(ck,"maybeFreeze");function By(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}s(By,"markStateFinalized");var Gl=s((e,t)=>e.scope_===t,"isSameScope"),uk=[];function $y(e,t,r,n){let o=on(e),i=e.type_;if(n!==void 0&&Sd(o,n,i)===t){Ll(o,n,r,i);return}if(!e.draftLocations_){let l=e.draftLocations_=new Map;Bl(o,(d,f)=>{if(Ln(f)){let m=l.get(f)||[];m.push(d),l.set(f,m)}})}let a=e.draftLocations_.get(t)??uk;for(let l of a)Ll(o,l,r,i)}s($y,"updateDraftInParent");function dk(e,t,r){e.callbacks_.push(s(function(o){let i=t;if(!i||!Gl(i,o))return;o.mapSetPlugin_?.fixSetContents(i);let a=Ad(i);$y(e,i.draft_??i,a,r),Vy(i,o)},"childCleanup"))}s(dk,"registerChildFinalizationCallback");function Vy(e,t){if(e.modified_&&!e.finalized_&&(e.type_===3||e.type_===1&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){let{patchPlugin_:n}=t;if(n){let o=n.getPath(e);o&&n.generatePatches_(e,o,t)}By(e)}}s(Vy,"generatePatchesAndFinalize");function pk(e,t,r){let{scope_:n}=e;if(Ln(r)){let o=r[Ct];Gl(o,n)&&o.callbacks_.push(s(function(){Ml(e);let a=Ad(o);$y(e,r,a,t)},"crossReferenceCleanup"))}else sn(r)&&e.callbacks_.push(s(function(){let i=on(e);e.type_===3?i.has(r)&&jl(r,n.handledSet_,n):Sd(i,t,e.type_)===r&&n.drafts_.length>1&&(e.assigned_.get(t)??!1)===!0&&e.copy_&&jl(Sd(e.copy_,t,e.type_),n.handledSet_,n)},"nestedDraftCleanup"))}s(pk,"handleCrossReference");function jl(e,t,r){return!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1||Ln(e)||t.has(e)||!sn(e)||Wl(e)||(t.add(e),Bl(e,(n,o)=>{if(Ln(o)){let i=o[Ct];if(Gl(i,r)){let a=Ad(i);Ll(e,n,a,e.type_),By(i)}}else sn(o)&&jl(o,t,r)})),e}s(jl,"handleValue");function fk(e,t){let r=$l(e),n={type_:r?1:0,scope_:t?t.scope_:qy(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0},o=n,i=Ul;r&&(o=[n],i=Ki);let{revoke:a,proxy:l}=Proxy.revocable(o,i);return n.draft_=l,n.revoke_=a,[l,n]}s(fk,"createProxyProxy");var Ul={get(e,t){if(t===Ct)return e;let r=e.scope_.arrayMethodsPlugin_,n=e.type_===1&&typeof t=="string";if(n&&r?.isArrayOperationMethod(t))return r.createMethodInterceptor(e,t);let o=on(e);if(!Cy(o,t,e.type_))return mk(e,o,t);let i=o[t];if(e.finalized_||!sn(i)||n&&e.operationMethod&&r?.isMutatingArrayMethod(e.operationMethod)&&sk(t))return i;if(i===yd(e.base_,t)){Ml(e);let a=e.type_===1?+t:t,l=Td(e.scope_,i,e,a);return e.copy_[a]=l}return i},has(e,t){return t in on(e)},ownKeys(e){return Reflect.ownKeys(on(e))},set(e,t,r){let n=Hy(on(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=yd(on(e),t),i=o?.[Ct];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_.set(t,!1),!0;if(ok(r,o)&&(r!==void 0||Cy(e.base_,t,e.type_)))return!0;Ml(e),Id(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_.set(t,!0),pk(e,t,r)),!0},deleteProperty(e,t){return Ml(e),yd(e.base_,t)!==void 0||t in e.base_?(e.assigned_.set(t,!1),Id(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=on(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{[Ol]:!0,[vd]:e.type_!==1||t!=="length",[Nl]:n[Nl],[Ji]:r[t]}},defineProperty(){Yt(11)},getPrototypeOf(e){return ws(e.base_)},setPrototypeOf(){Yt(12)}},Ki={};for(let e in Ul){let t=Ul[e];Ki[e]=function(){let r=arguments;return r[0]=r[0][0],t.apply(this,r)}}Ki.deleteProperty=function(e,t){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(t))&&Yt(13),Ki.set.call(this,e,t,void 0)};Ki.set=function(e,t,r){return process.env.NODE_ENV!=="production"&&t!=="length"&&isNaN(parseInt(t))&&Yt(14),Ul.set.call(this,e[0],t,r,e[0])};function yd(e,t){let r=e[Ct];return(r?on(r):e)[t]}s(yd,"peek");function mk(e,t,r){let n=Hy(t,r);return n?Ji in n?n[Ji]:n.get?.call(e.draft_):void 0}s(mk,"readPropFromProto");function Hy(e,t){if(!(t in e))return;let r=ws(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=ws(r)}}s(Hy,"getDescriptorFromProto");function Id(e){e.modified_||(e.modified_=!0,e.parent_&&Id(e.parent_))}s(Id,"markChanged");function Ml(e){e.copy_||(e.assigned_=new Map,e.copy_=wd(e.base_,e.scope_.immer_.useStrictShallowCopy_))}s(Ml,"prepareCopy");var gk=class{static{s(this,"Immer2")}constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(t,r,n)=>{if(io(t)&&!io(r)){let i=r;r=t;let a=this;return s(function(d=i,...f){return a.produce(d,m=>r.call(this,m,...f))},"curriedProduce")}io(r)||Yt(6),n!==void 0&&!io(n)&&Yt(7);let o;if(sn(t)){let i=Py(this),a=Td(i,t,void 0),l=!0;try{o=r(a),l=!1}finally{l?bd(i):Ed(i)}return My(i,n),Ny(o,i)}else if(!t||!_d(t)){if(o=r(t),o===void 0&&(o=t),o===Fy&&(o=void 0),this.autoFreeze_&&kd(o,!0),n){let i=[],a=[];ao(xd).generateReplacementPatches_(t,o,{patches_:i,inversePatches_:a}),n(i,a)}return o}else Yt(1,t)},this.produceWithPatches=(t,r)=>{if(io(t))return(a,...l)=>this.produceWithPatches(a,d=>t(d,...l));let n,o;return[this.produce(t,r,(a,l)=>{n=a,o=l}),n,o]},hd(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),hd(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),hd(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){sn(e)||Yt(8),Ln(e)&&(e=hk(e));let t=Py(this),r=Td(t,e,void 0);return r[Ct].isManual_=!0,Ed(t),r}finishDraft(e,t){let r=e&&e[Ct];(!r||!r.isManual_)&&Yt(9);let{scope_:n}=r;return My(n,t),Ny(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=ao(xd).applyPatches_;return Ln(e)?n(e,t):this.produce(e,o=>n(o,t))}};function Td(e,t,r,n){let[o,i]=Vl(t)?ao(Fl).proxyMap_(t,r):Hl(t)?ao(Fl).proxySet_(t,r):fk(t,r);return(r?.scope_??qy()).drafts_.push(o),i.callbacks_=r?.callbacks_??[],i.key_=n,r&&n!==void 0?dk(r,i,n):i.callbacks_.push(s(function(d){d.mapSetPlugin_?.fixSetContents(i);let{patchPlugin_:f}=d;i.modified_&&f&&f.generatePatches_(i,[],d)},"rootDraftCleanup")),o}s(Td,"createProxy");function hk(e){return Ln(e)||Yt(10,e),Wy(e)}s(hk,"current");function Wy(e){if(!sn(e)||Wl(e))return e;let t=e[Ct],r,n=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=wd(e,t.scope_.immer_.useStrictShallowCopy_),n=t.scope_.immer_.shouldUseStrictIteration()}else r=wd(e,!0);return Bl(r,(o,i)=>{Ll(r,o,Wy(i))},n),t&&(t.finalized_=!1),r}s(Wy,"currentImpl");var yk=new gk,lo=yk.produce;var co=s(e=>e,"castDraft");function vk(e){let t=s(o=>e.messages.findLastIndex(i=>i.id===o),"assistantIndex"),r=s(()=>e.messages.findLastIndex(o=>o.type==="assistant"),"latestAssistantIndex"),n=s(o=>e.messages.findLastIndex(i=>i.type==="shell"&&i.callID===o),"activeShellIndex");return{getCurrentAssistant(){return p.sync(()=>{let o=r();if(o<0)return;let i=e.messages[o];return i?.type==="assistant"&&!i.time.completed?i:void 0})},getAssistant(o){return p.sync(()=>{let i=t(o);if(i<0)return;let a=e.messages[i];return a?.type==="assistant"?a:void 0})},getCurrentShell(o){return p.sync(()=>{let i=n(o);if(i<0)return;let a=e.messages[i];return a?.type==="shell"?a:void 0})},updateAssistant(o){return p.sync(()=>{let i=t(o.id);i<0||e.messages[i]?.type!=="assistant"||(e.messages[i]=o)})},updateShell(o){return p.sync(()=>{let i=n(o.callID);i<0||e.messages[i]?.type!=="shell"||(e.messages[i]=o)})},appendMessage(o){return p.sync(()=>{e.messages.push(o)})}}}s(vk,"memory");function Sk(e,t){let r=s((a,l)=>a?.content.findLast(d=>d.type==="tool"&&(l===void 0||d.id===l)),"latestTool"),n=s((a,l)=>a?.content.findLast(d=>d.type==="text"&&d.id===l),"latestText"),o=s((a,l)=>a?.content.findLast(d=>d.type==="reasoning"&&d.id===l),"latestReasoning"),i=s((a,l)=>p.gen(function*(){let d=yield*e.getAssistant(a);d&&(yield*e.updateAssistant(lo(d,l)))}),"updateOwnedAssistant");return p.gen(function*(){yield*oe.All.match(t,{"session.next.agent.switched":s(a=>e.appendMessage(Z.AgentSwitched.make({id:a.data.messageID,type:"agent-switched",metadata:a.metadata,agent:a.data.agent,time:{created:a.data.timestamp}})),"session.next.agent.switched"),"session.next.model.switched":s(a=>e.appendMessage(Z.ModelSwitched.make({id:a.data.messageID,type:"model-switched",metadata:a.metadata,model:a.data.model,time:{created:a.data.timestamp}})),"session.next.model.switched"),"session.next.moved":s(()=>p.void,"session.next.moved"),"session.next.prompted":s(a=>e.appendMessage(Z.User.make({id:a.data.messageID,type:"user",metadata:a.metadata,text:a.data.prompt.text,files:a.data.prompt.files,agents:a.data.prompt.agents,time:{created:a.data.timestamp}})),"session.next.prompted"),"session.next.prompt.admitted":s(()=>p.void,"session.next.prompt.admitted"),"session.next.context.updated":s(a=>e.appendMessage(Z.System.make({id:a.data.messageID,type:"system",text:a.data.text,time:{created:a.data.timestamp}})),"session.next.context.updated"),"session.next.synthetic":s(a=>e.appendMessage(Z.Synthetic.make({sessionID:a.data.sessionID,text:a.data.text,id:a.data.messageID,type:"synthetic",time:{created:a.data.timestamp}})),"session.next.synthetic"),"session.next.shell.started":s(a=>e.appendMessage(Z.Shell.make({id:a.data.messageID,type:"shell",metadata:a.metadata,callID:a.data.callID,command:a.data.command,output:"",time:{created:a.data.timestamp}})),"session.next.shell.started"),"session.next.shell.ended":s(a=>p.gen(function*(){let l=yield*e.getCurrentShell(a.data.callID);l&&(yield*e.updateShell(lo(l,d=>{d.output=a.data.output,d.time.completed=a.data.timestamp})))}),"session.next.shell.ended"),"session.next.step.started":s(a=>p.gen(function*(){let l=yield*e.getCurrentAssistant();l&&(yield*e.updateAssistant(lo(l,d=>{d.time.completed=a.data.timestamp}))),yield*e.appendMessage(Z.Assistant.make({id:a.data.assistantMessageID,type:"assistant",agent:a.data.agent,model:a.data.model,time:{created:a.data.timestamp},content:[],snapshot:a.data.snapshot?{start:a.data.snapshot}:void 0}))}),"session.next.step.started"),"session.next.step.ended":s(a=>i(a.data.assistantMessageID,l=>{l.time.completed=a.data.timestamp,l.finish=a.data.finish,l.cost=a.data.cost,l.tokens=a.data.tokens,(a.data.snapshot||a.data.files)&&(l.snapshot={...l.snapshot,end:a.data.snapshot,files:a.data.files?Array.from(a.data.files):void 0})}),"session.next.step.ended"),"session.next.step.failed":s(a=>i(a.data.assistantMessageID,l=>{l.time.completed=a.data.timestamp,l.finish="error",l.error=a.data.error}),"session.next.step.failed"),"session.next.text.started":s(a=>i(a.data.assistantMessageID,l=>{l.content.push(co(Z.AssistantText.make({type:"text",id:a.data.textID,text:""})))}),"session.next.text.started"),"session.next.text.delta":s(a=>i(a.data.assistantMessageID,l=>{let d=n(l,a.data.textID);d&&(d.text+=a.data.delta)}),"session.next.text.delta"),"session.next.text.ended":s(a=>i(a.data.assistantMessageID,l=>{let d=n(l,a.data.textID);d&&(d.text=a.data.text)}),"session.next.text.ended"),"session.next.tool.input.started":s(a=>i(a.data.assistantMessageID,l=>{l.content.push(co(Z.AssistantTool.make({type:"tool",id:a.data.callID,name:a.data.name,time:{created:a.data.timestamp},state:Z.ToolStatePending.make({status:"pending",input:""})})))}),"session.next.tool.input.started"),"session.next.tool.input.delta":s(()=>p.void,"session.next.tool.input.delta"),"session.next.tool.input.ended":s(a=>i(a.data.assistantMessageID,l=>{let d=r(l,a.data.callID);d&&d.state.status==="pending"&&(d.state.input=a.data.text)}),"session.next.tool.input.ended"),"session.next.tool.called":s(a=>i(a.data.assistantMessageID,l=>{let d=r(l,a.data.callID);d&&(d.provider=a.data.provider,d.time.ran=a.data.timestamp,d.state=co(Z.ToolStateRunning.make({status:"running",input:a.data.input,structured:{},content:[]})))}),"session.next.tool.called"),"session.next.tool.progress":s(a=>i(a.data.assistantMessageID,l=>{let d=r(l,a.data.callID);d&&d.state.status==="running"&&(d.state.structured=a.data.structured,d.state.content=[...a.data.content])}),"session.next.tool.progress"),"session.next.tool.success":s(a=>i(a.data.assistantMessageID,l=>{let d=r(l,a.data.callID);d&&d.state.status==="running"&&(d.provider={executed:a.data.provider.executed||d.provider?.executed===!0,metadata:d.provider?.metadata,resultMetadata:a.data.provider.metadata},d.time.completed=a.data.timestamp,d.state=co(Z.ToolStateCompleted.make({status:"completed",input:d.state.input,structured:a.data.structured,content:[...a.data.content],outputPaths:a.data.outputPaths?[...a.data.outputPaths]:[],result:a.data.result})))}),"session.next.tool.success"),"session.next.tool.failed":s(a=>i(a.data.assistantMessageID,l=>{let d=r(l,a.data.callID);d&&(d.state.status==="pending"||d.state.status==="running")&&(d.provider={executed:a.data.provider.executed||d.provider?.executed===!0,metadata:d.provider?.metadata,resultMetadata:a.data.provider.metadata},d.time.completed=a.data.timestamp,d.state=co(Z.ToolStateError.make({status:"error",error:a.data.error,input:typeof d.state.input=="string"?{}:d.state.input,structured:d.state.status==="running"?d.state.structured:{},content:d.state.status==="running"?d.state.content:[],result:a.data.result})))}),"session.next.tool.failed"),"session.next.reasoning.started":s(a=>i(a.data.assistantMessageID,l=>{l.content.push(co(Z.AssistantReasoning.make({type:"reasoning",id:a.data.reasoningID,text:"",providerMetadata:a.data.providerMetadata,time:{created:a.data.timestamp}})))}),"session.next.reasoning.started"),"session.next.reasoning.delta":s(a=>i(a.data.assistantMessageID,l=>{let d=o(l,a.data.reasoningID);d&&(d.text+=a.data.delta)}),"session.next.reasoning.delta"),"session.next.reasoning.ended":s(a=>i(a.data.assistantMessageID,l=>{let d=o(l,a.data.reasoningID);d&&(d.text=a.data.text,d.time={created:d.time?.created??a.data.timestamp,completed:a.data.timestamp},a.data.providerMetadata!==void 0&&(d.providerMetadata=a.data.providerMetadata))}),"session.next.reasoning.ended"),"session.next.retried":s(()=>p.void,"session.next.retried"),"session.next.compaction.started":s(()=>p.void,"session.next.compaction.started"),"session.next.compaction.delta":s(()=>p.void,"session.next.compaction.delta"),"session.next.compaction.ended":s(a=>e.appendMessage(Z.Compaction.make({id:a.data.messageID,type:"compaction",metadata:a.metadata,reason:a.data.reason,summary:a.data.text,recent:a.data.recent,time:{created:a.data.timestamp}})),"session.next.compaction.ended"),"session.next.revert.staged":s(()=>p.void,"session.next.revert.staged"),"session.next.revert.cleared":s(()=>p.void,"session.next.revert.cleared"),"session.next.revert.committed":s(()=>p.void,"session.next.revert.committed")})})}s(Sk,"update");var jr={};H(jr,{Admitted:()=>Zi,Delivery:()=>Jl,LifecycleConflict:()=>Fn,SessionInput:()=>jr,admit:()=>bk,equivalent:()=>Xy,find:()=>Qi,hasPending:()=>Tk,projectAdmitted:()=>Ek,projectPrompted:()=>Ik,promoteNextQueued:()=>kk,promoteSteers:()=>Ak});var Rd={};H(Rd,{Admitted:()=>Zi,Delivery:()=>Jl,SessionInput:()=>Rd});var Jl=wh.Delivery,Zi=c.Struct({admittedSeq:zt,id:hh.ID,sessionID:yl,prompt:Dn,delivery:Jl,timeCreated:ps,promotedSeq:zt.pipe(Je)}).annotate({identifier:"SessionInput.Admitted"});var Pe={};H(Pe,{ID:()=>Gy,Info:()=>Jy,SessionSchema:()=>Pe});var xs={};H(xs,{Event:()=>wk,ID:()=>zl,Info:()=>xk,ListAnchor:()=>Kl,Session:()=>xs});var zl=yl,wk=oe,xk=c.Struct({id:zl,parentID:zl.pipe(Je),projectID:yh.ID,agent:nn.ID.pipe(Je),model:hl.Ref.pipe(Je),cost:c.Finite,tokens:c.Struct({input:c.Finite,output:c.Finite,reasoning:c.Finite,cache:c.Struct({read:c.Finite,write:c.Finite})}),time:c.Struct({created:ps,updated:ps,archived:ps.pipe(Je)}),title:c.String,location:Zg.Ref,subpath:_n.pipe(Je),revert:_l.State.pipe(Je)}).annotate({identifier:"SessionV2.Info"}),Kl=c.Struct({id:zl,time:c.Finite,direction:c.Literals(["previous","next"])}).annotate({identifier:"Session.ListAnchor"});var Gy=xs.ID,Jy=xs.Info;var Ky=c.decodeUnknownSync(Dn),Yl=c.encodeSync(Dn),Yy=s(e=>Zi.make({admittedSeq:e.admitted_seq,id:Z.ID.make(e.id),sessionID:Pe.ID.make(e.session_id),prompt:Ky(e.prompt),delivery:e.delivery,timeCreated:be.makeUnsafe(e.time_created),...e.promoted_seq===null?{}:{promotedSeq:e.promoted_seq}}),"fromRow"),Qi=p.fn("SessionInput.find")(function*(e,t){let r=yield*e.select().from(ge).where(F(ge.id,t)).get().pipe(p.orDie);return r===void 0?void 0:Yy(r)}),Fn=class extends c.TaggedErrorClass()("SessionInput.LifecycleConflict",{id:Z.ID}){static{s(this,"LifecycleConflict")}},bk=p.fn("SessionInput.admit")(function*(e,t,r){let n=yield*Qi(e,r.id);if(n!==void 0)return n;let o=yield*be.now;return yield*t.publish(oe.PromptAdmitted,{messageID:r.id,sessionID:r.sessionID,timestamp:o,prompt:r.prompt,delivery:r.delivery}).pipe(p.flatMap(i=>i.durable===void 0?p.die("Prompt admission event is missing aggregate sequence"):p.succeed(Zi.make({admittedSeq:i.durable.seq,id:r.id,sessionID:r.sessionID,prompt:r.prompt,delivery:r.delivery,timeCreated:o}))),p.catchDefect(i=>Qi(e,r.id).pipe(p.flatMap(a=>a?p.succeed(a):p.die(i)))))}),Ek=p.fn("SessionInput.projectAdmitted")(function*(e,t){if((yield*e.select({id:U.id}).from(U).where(F(U.id,t.id)).get().pipe(p.orDie))!==void 0)return yield*p.die(new Fn({id:t.id}));if(!(yield*e.insert(ge).values({id:t.id,session_id:t.sessionID,admitted_seq:t.admittedSeq,prompt:Yl(t.prompt),delivery:t.delivery,time_created:be.toEpochMillis(t.timeCreated)}).onConflictDoNothing().returning({id:ge.id}).get().pipe(p.orDie)))return yield*p.die(new Fn({id:t.id}))}),Ik=p.fn("SessionInput.projectPrompted")(function*(e,t){let r=yield*e.update(ge).set({promoted_seq:t.promotedSeq}).where(ye(F(ge.id,t.id),F(ge.session_id,t.sessionID),Ni(ge.promoted_seq))).returning().get().pipe(p.orDie);if(r){let o=Yy(r);return zy(o,t)?void 0:yield*p.die(new Fn({id:t.id}))}let n=yield*Qi(e,t.id);if(n)return!zy(n,t)||n.promotedSeq!==t.promotedSeq?yield*p.die(new Fn({id:t.id})):void 0;yield*e.insert(ge).values({id:t.id,session_id:t.sessionID,prompt:Yl(t.prompt),delivery:t.delivery,admitted_seq:t.promotedSeq,promoted_seq:t.promotedSeq,time_created:be.toEpochMillis(t.timeCreated)}).run().pipe(p.orDie)}),Tk=p.fn("SessionInput.hasPending")(function*(e,t,r){return(yield*e.select({id:ge.id}).from(ge).where(ye(F(ge.session_id,t),Ni(ge.promoted_seq),F(ge.delivery,r))).limit(1).get().pipe(p.orDie))!==void 0}),Xy=s((e,t)=>e.delivery===t.delivery&&_k(e,t),"equivalent"),_k=s((e,t)=>e.sessionID===t.sessionID&&JSON.stringify(Yl(e.prompt))===JSON.stringify(Yl(t.prompt)),"matchesPrompt"),zy=s((e,t)=>Xy(e,t)&&be.toEpochMillis(e.timeCreated)===be.toEpochMillis(t.timeCreated),"matchesProjection"),Zy=p.fn("SessionInput.publish")(function*(e,t,r,n){for(let o of n){let i=Z.ID.make(o.id);yield*t.publish(oe.Prompted,{sessionID:r,timestamp:be.makeUnsafe(o.time_created),messageID:i,prompt:Ky(o.prompt),delivery:o.delivery}).pipe(p.catchDefect(a=>a instanceof Fn?Qi(e,i).pipe(p.flatMap(l=>l?.promotedSeq===void 0?p.die(a):p.void)):p.die(a)))}return n.length}),Ak=p.fn("SessionInput.promoteSteers")(function*(e,t,r,n){let o=yield*e.select().from(ge).where(ye(F(ge.session_id,r),Ni(ge.promoted_seq),F(ge.delivery,"steer"),oh(ge.admitted_seq,n))).orderBy(br(ge.admitted_seq)).all().pipe(p.orDie);return yield*Zy(e,t,r,o)}),kk=p.fn("SessionInput.promoteNextQueued")(function*(e,t,r){let n=yield*e.select().from(ge).where(ye(F(ge.session_id,r),Ni(ge.promoted_seq),F(ge.delivery,"queue"))).orderBy(br(ge.admitted_seq)).limit(1).get().pipe(p.orDie);return n===void 0?!1:yield*Zy(e,t,r,[n]).pipe(p.as(!0))});var Rk=c.decodeUnknownSync(Z.Message),ev=c.encodeSync(Z.Message),Ql=class extends Error{static{s(this,"SessionAlreadyProjected")}};function Xl(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="step-finish"&&!(!("cost"in t)||!("tokens"in t)))return{cost:t.cost,tokens:t.tokens}}s(Xl,"usage");function Qy(e){return{id:e.id,project_id:e.projectID,workspace_id:e.workspaceID??null,parent_id:e.parentID,slug:e.slug,directory:e.directory,path:e.path,title:e.title,agent:e.agent,model:e.model,version:e.version,share_url:e.share?.url,summary_additions:e.summary?.additions,summary_deletions:e.summary?.deletions,summary_files:e.summary?.files,summary_diffs:e.summary?.diffs?[...e.summary.diffs]:void 0,metadata:e.metadata,cost:e.cost??0,tokens_input:(e.tokens??{input:0}).input,tokens_output:(e.tokens??{output:0}).output,tokens_reasoning:(e.tokens??{reasoning:0}).reasoning,tokens_cache_read:(e.tokens??{cache:{read:0}}).cache.read,tokens_cache_write:(e.tokens??{cache:{write:0}}).cache.write,revert:e.revert?{...e.revert,messageID:Z.ID.make(e.revert.messageID)}:null,permission:e.permission?[...e.permission]:void 0,time_created:e.time.created,time_updated:e.time.updated,time_compacting:e.time.compacting,time_archived:e.time.archived}}s(Qy,"sessionRow");function Ck(e){let{id:t,sessionID:r,...n}=e;return n}s(Ck,"messageData");function Dk(e){let{id:t,messageID:r,sessionID:n,...o}=e;return o}s(Dk,"partData");function Zl(e,t,r,n=1){return e.update(ee).set({cost:An`${ee.cost} + ${r.cost*n}`,tokens_input:An`${ee.tokens_input} + ${r.tokens.input*n}`,tokens_output:An`${ee.tokens_output} + ${r.tokens.output*n}`,tokens_reasoning:An`${ee.tokens_reasoning} + ${r.tokens.reasoning*n}`,tokens_cache_read:An`${ee.tokens_cache_read} + ${r.tokens.cache.read*n}`,tokens_cache_write:An`${ee.tokens_cache_write} + ${r.tokens.cache.write*n}`,time_updated:An`${ee.time_updated}`}).where(F(ee.id,t)).run().pipe(p.orDie)}s(Zl,"applyUsage");function Ke(e,t){return p.gen(function*(){let r=s(a=>Rk({...a.data,id:a.id,type:a.type}),"decodeRow"),n=s(a=>{if(t.durable===void 0)return p.die("Durable Session event is missing aggregate sequence");let l=ev(a),{id:d,type:f,...m}=l;return e.update(U).set({type:f,time_created:be.toEpochMillis(a.time.created),data:m}).where(ye(F(U.id,Z.ID.make(d)),F(U.session_id,t.data.sessionID))).run().pipe(p.orDie)},"updateMessage"),i={getCurrentAssistant(){return p.gen(function*(){let a=yield*e.select().from(U).where(ye(F(U.session_id,t.data.sessionID),F(U.type,"assistant"))).orderBy(Xr(U.seq)).limit(1).get().pipe(p.orDie);if(!a)return;let l=r(a);return l.type==="assistant"&&!l.time.completed?l:void 0})},getAssistant(a){return p.gen(function*(){let l=yield*e.select().from(U).where(ye(F(U.id,a),F(U.session_id,t.data.sessionID),F(U.type,"assistant"))).get().pipe(p.orDie);if(!l)return;let d=r(l);return d.type==="assistant"?d:void 0})},getCurrentShell(a){return p.gen(function*(){return(yield*e.select().from(U).where(ye(F(U.session_id,t.data.sessionID),F(U.type,"shell"))).orderBy(Xr(U.seq)).all().pipe(p.orDie)).map(r).find(d=>d.type==="shell"&&d.callID===a)})},updateAssistant:n,updateShell:n,appendMessage:s(a=>Ok(e,t,a),"appendMessage")};yield*Xi.update(i,t)})}s(Ke,"run");function Ok(e,t,r){if(t.durable===void 0)return p.die("Durable Session event is missing aggregate sequence");let n=ev(r),{id:o,type:i,...a}=n;return e.insert(U).values({id:Z.ID.make(o),session_id:t.data.sessionID,type:i,seq:t.durable.seq,time_created:be.toEpochMillis(r.time.created),data:a}).run().pipe(p.orDie)}s(Ok,"insertMessage");var Mk=B.effectDiscard(p.gen(function*(){let e=yield*ut.Service,{db:t}=yield*Rt.Service;yield*e.project(qt.Event.Created,r=>p.gen(function*(){if(!(yield*t.insert(ee).values(Qy(r.data.info)).onConflictDoNothing().returning({sessionID:ee.id}).get().pipe(p.orDie)))return yield*p.die(new Ql);r.data.info.workspaceID&&(yield*t.update(gd).set({time_used:Date.now()}).where(F(gd.id,r.data.info.workspaceID)).run().pipe(p.orDie))})),yield*e.project(qt.Event.Updated,r=>t.update(ee).set(Qy(r.data.info)).where(F(ee.id,r.data.sessionID)).run().pipe(p.orDie)),yield*e.project(oe.Moved,r=>p.gen(function*(){yield*t.update(ee).set({directory:r.data.location.directory,path:r.data.subdirectory,workspace_id:r.data.location.workspaceID?Fr.ID.make(r.data.location.workspaceID):null,time_updated:be.toEpochMillis(r.data.timestamp)}).where(F(ee.id,r.data.sessionID)).run().pipe(p.orDie)})),yield*e.project(qt.Event.Deleted,r=>t.delete(ee).where(F(ee.id,r.data.sessionID)).run().pipe(p.orDie)),yield*e.project(qt.Event.MessageUpdated,r=>p.gen(function*(){let n=r.data.info.time.created,o=r.data.info.id,i=r.data.info.sessionID,a=Ck(r.data.info);yield*t.insert(so).values({id:o,session_id:i,time_created:n,data:a}).onConflictDoUpdate({target:so.id,set:{data:a}}).run().pipe(p.orDie)})),yield*e.project(qt.Event.MessageRemoved,r=>p.gen(function*(){let n=yield*t.select().from(Bt).where(ye(F(Bt.message_id,r.data.messageID),F(Bt.session_id,r.data.sessionID))).all().pipe(p.orDie);for(let o of n){let i=Xl(o.data);i&&(yield*Zl(t,r.data.sessionID,i,-1))}yield*t.delete(so).where(ye(F(so.id,r.data.messageID),F(so.session_id,r.data.sessionID))).run().pipe(p.orDie)})),yield*e.project(qt.Event.PartRemoved,r=>p.gen(function*(){let n=yield*t.select().from(Bt).where(ye(F(Bt.id,r.data.partID),F(Bt.session_id,r.data.sessionID))).get().pipe(p.orDie),o=n&&Xl(n.data);o&&(yield*Zl(t,r.data.sessionID,o,-1)),yield*t.delete(Bt).where(ye(F(Bt.id,r.data.partID),F(Bt.session_id,r.data.sessionID))).run().pipe(p.orDie)})),yield*e.project(qt.Event.PartUpdated,r=>p.gen(function*(){let n=r.data.part.id,o=r.data.part.messageID,i=r.data.part.sessionID,a=Dk(r.data.part),l=yield*t.select().from(Bt).where(F(Bt.id,n)).get().pipe(p.orDie);yield*t.insert(Bt).values({id:n,message_id:o,session_id:i,time_created:r.data.time,data:a}).onConflictDoUpdate({target:Bt.id,set:{data:a}}).run().pipe(p.orDie);let d=l&&Xl(l.data),f=Xl(r.data.part);d&&(yield*Zl(t,l.session_id,d,-1)),f&&(yield*Zl(t,i,f))})),yield*e.project(oe.AgentSwitched,r=>t.update(ee).set({agent:r.data.agent,time_updated:be.toEpochMillis(r.data.timestamp)}).where(F(ee.id,r.data.sessionID)).run().pipe(p.orDie,p.andThen(Ke(t,r)))),yield*e.project(oe.ModelSwitched,r=>p.gen(function*(){yield*t.update(ee).set({model:r.data.model,time_updated:be.toEpochMillis(r.data.timestamp)}).where(F(ee.id,r.data.sessionID)).run().pipe(p.orDie),yield*Ke(t,r)})),yield*e.project(oe.Prompted,r=>p.gen(function*(){if(r.durable===void 0)return yield*p.die("Durable Session event is missing aggregate sequence");yield*jr.projectPrompted(t,{id:r.data.messageID,sessionID:r.data.sessionID,prompt:r.data.prompt,delivery:r.data.delivery,timeCreated:r.data.timestamp,promotedSeq:r.durable.seq}),yield*Ke(t,r)})),yield*e.project(oe.PromptAdmitted,r=>p.gen(function*(){if(r.durable===void 0)return yield*p.die("Durable Session event is missing aggregate sequence");yield*jr.projectAdmitted(t,{admittedSeq:r.durable.seq,id:r.data.messageID,sessionID:r.data.sessionID,prompt:r.data.prompt,delivery:r.data.delivery,timeCreated:r.data.timestamp})})),yield*e.project(oe.ContextUpdated,r=>Ke(t,r)),yield*e.project(oe.Synthetic,r=>Ke(t,r)),yield*e.project(oe.Shell.Started,r=>Ke(t,r)),yield*e.project(oe.Shell.Ended,r=>Ke(t,r)),yield*e.project(oe.Step.Started,r=>Ke(t,r)),yield*e.project(oe.Step.Ended,r=>Ke(t,r)),yield*e.project(oe.Step.Failed,r=>Ke(t,r)),yield*e.project(oe.Text.Started,r=>Ke(t,r)),yield*e.project(oe.Text.Ended,r=>Ke(t,r)),yield*e.project(oe.Tool.Input.Started,r=>Ke(t,r)),yield*e.project(oe.Tool.Input.Ended,r=>Ke(t,r)),yield*e.project(oe.Tool.Called,r=>Ke(t,r)),yield*e.project(oe.Tool.Progress,r=>Ke(t,r)),yield*e.project(oe.Tool.Success,r=>Ke(t,r)),yield*e.project(oe.Tool.Failed,r=>Ke(t,r)),yield*e.project(oe.Reasoning.Started,r=>Ke(t,r)),yield*e.project(oe.Reasoning.Ended,r=>Ke(t,r)),yield*e.project(oe.Compaction.Ended,r=>Ke(t,r)),yield*e.project(oe.RevertEvent.Staged,r=>t.update(ee).set({revert:{...r.data.revert,files:r.data.revert.files?[...r.data.revert.files]:void 0},time_updated:be.toEpochMillis(r.data.timestamp)}).where(F(ee.id,r.data.sessionID)).run().pipe(p.orDie,p.asVoid)),yield*e.project(oe.RevertEvent.Cleared,r=>t.update(ee).set({revert:null,time_updated:be.toEpochMillis(r.data.timestamp)}).where(F(ee.id,r.data.sessionID)).run().pipe(p.orDie,p.asVoid)),yield*e.project(oe.RevertEvent.Committed,r=>p.gen(function*(){let n=yield*t.select({seq:U.seq}).from(U).where(ye(F(U.session_id,r.data.sessionID),F(U.id,r.data.messageID))).get().pipe(p.orDie);if(!n)return yield*p.die(`Revert boundary message not found: ${r.data.messageID}`);yield*t.delete(U).where(ye(F(U.session_id,r.data.sessionID),Kt(U.seq,n.seq))).run().pipe(p.orDie),yield*t.delete(ge).where(ye(F(ge.session_id,r.data.sessionID),kn(Kt(ge.admitted_seq,n.seq),Kt(ge.promoted_seq,n.seq)))).run().pipe(p.orDie),yield*t.update(ee).set({revert:null,time_updated:be.toEpochMillis(r.data.timestamp)}).where(F(ee.id,r.data.sessionID)).run().pipe(p.orDie)}))})),Pk=Pr({name:"session-projector",layer:Mk,deps:[ut.node,Rt.node]});var Cd;(n=>{let e=["brave","calm","clever","cosmic","crisp","curious","eager","gentle","glowing","happy","hidden","jolly","kind","lucky","mighty","misty","neon","nimble","playful","proud","quick","quiet","shiny","silent","stellar","sunny","swift","tidy","witty"],t=["cabin","cactus","canyon","circuit","comet","eagle","engine","falcon","forest","garden","harbor","island","knight","lagoon","meadow","moon","mountain","nebula","orchid","otter","panda","pixel","planet","river","rocket","sailor","squid","star","tiger","wizard","wolf"];function r(){return[e[Math.floor(Math.random()*e.length)],t[Math.floor(Math.random()*t.length)]].join("-")}n.create=r,s(r,"create")})(Cd||={});var tv=B.makeMemoMapUnsafe();var na={};H(na,{Observability:()=>na,layer:()=>wv,node:()=>E0});var nc={};H(nc,{layer:()=>hv,layerFromConfig:()=>p0,make:()=>gv});var Nk=Hg(Kr).pipe(Dg({decode:Ag(e=>e.map(t=>t.toLowerCase().trim()).filter(t=>t!=="")),encode:_g()})),rv=pl(Kr,Kr),nv=s(e=>In(rv,`OTEL_EXPORTER_OTLP_${e}_HEADERS`).pipe(Gu(()=>In(rv,"OTEL_EXPORTER_OTLP_HEADERS")),as(void 0)),"headers"),ov=s(e=>zu(`OTEL_EXPORTER_OTLP_${e}_ENDPOINT`).pipe(Gu(()=>zu("OTEL_EXPORTER_OTLP_ENDPOINT").pipe(Vg(t=>{let r=t.pathname.endsWith("/")?"":"/";return t.pathname+=`${r}v1/${e.toLowerCase()}`,t}))),as(void 0)),"endpoint"),sv=s(e=>In(Nk,`OTEL_${e}_EXPORTER`).pipe(as([])),"exporters");var Fk=ag.pipe(ig,sg(e=>{if(Ng(e)&&e.reason._tag==="StatusCodeError"&&e.reason.response.status===429){let t=Bm(e.reason.response.headers["retry-after"]).pipe($m(og),Um(()=>5));return Bu(os(t))}return Bu(os(1))})),iv=is(function*(e){let t=yield*hg(),r=ol(t,sl),n=ol(t,Qm),o=bg(t),i=Km(Jm(e.exportInterval),zm),a,l=qg(ol(t,jg)).pipe(Ug(yg($g,!1)),Bg({schedule:Fk,times:3})),d=Mg({"user-agent":`effect-opentelemetry-${e.label}/0.0.0`});e.headers&&(d=Pg(Og(e.headers),d));let f=Lg(e.url,{headers:d}),m=[],g=lg(()=>{if(a!==void 0&&r.currentTimeMillisUnsafe()<a)return il;a!==void 0&&(a=void 0);let h=m;if(e.maxBatchSize!=="disabled"){if(m.length===0)return il;m=[]}return l.execute(Fg(f,e.body(h))).pipe(dg,wg(!1))}).pipe(pg(h=>a!==void 0?il:(a=r.currentTimeMillisUnsafe()+6e4,m=[],Eg("Disabling exporter for 60 seconds",h))),Ig({package:"@effect/opentelemetry",module:e.label}));return yield*eg(n,g.pipe(fg,vg,mg(e.shutdownTimeout))),yield*gg(i).pipe(ug(g),Sg,xg(n)),{push(h){a===void 0&&(m.push(h),e.maxBatchSize!=="disabled"&&m.length>=e.maxBatchSize&&kg(o(g),n))}}});var jk=s(e=>{let t=e.attributes?Dd(Object.entries(e.attributes)):[];return t.push({key:"service.name",value:{stringValue:e.serviceName}}),e.serviceVersion&&t.push({key:"service.version",value:{stringValue:e.serviceVersion}}),{attributes:t,droppedAttributesCount:0}},"make"),lv=is(function*(e){let t=yield*In(cl(pl(Kr,Kr)),"OTEL_RESOURCE_ATTRIBUTES"),r=(yield*In(cl(Kr),"OTEL_SERVICE_NAME"))??t?.["service.name"]??e?.attributes?.["service.name"]??e?.serviceName??(yield*Wg("OTEL_SERVICE_NAME")),n=(yield*In(cl(Kr),"OTEL_SERVICE_VERSION"))??t?.["service.version"]??e?.attributes?.["service.version"]??e?.serviceVersion,o={...e?.attributes,...t};return delete o["service.name"],delete o["service.version"],jk({serviceName:r,serviceVersion:n,attributes:o})},al),cv=s(e=>{let t=e.attributes.find(r=>r.key==="service.name");if(!t||!t.value.stringValue)throw new Error("Resource does not contain a service name");return t.value.stringValue},"serviceNameUnsafe"),Dd=s(e=>{let t=[];for(let[r,n]of e)t.push({key:r,value:ec(n)});return t},"entriesToAttributes"),ec=s(e=>{if(Array.isArray(e))return{arrayValue:{values:e.map(ec)}};switch(typeof e){case"string":return{stringValue:e};case"bigint":return{intValue:Number(e)};case"number":return Number.isInteger(e)?{intValue:e}:{doubleValue:e};case"boolean":return{boolValue:e};default:return{stringValue:Fm(e)}}},"unknownToAttributeValue");var rc={};H(rc,{OtlpSerialization:()=>fo,layerJson:()=>u0,layerProtobuf:()=>d0});var ea={Varint:0,Fixed64:1,LengthDelimited:2,Fixed32:5},ta=s((e,t)=>e<<3|t,"encodeTag"),uo=s(e=>{let t=[],r=typeof e=="bigint"?e:BigInt(e);for(;r>BigInt(127);)t.push(Number(r&BigInt(127))|128),r>>=BigInt(7);return t.push(Number(r)),new Uint8Array(t)},"encodeVarint");var Uk=s(e=>{let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!0),t},"encodeFixed64"),qk=s(e=>{let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),t},"encodeFixed32"),Bk=s(e=>{let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),t},"encodeDouble"),$k=s(e=>new TextEncoder().encode(e),"encodeString"),Vk=s(e=>{let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.slice(r,r+2),16);return t},"encodeHexBytes"),_e=s((...e)=>{let t=e.reduce((o,i)=>o+i.length,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r},"concat"),dt=s((e,t)=>_e(uo(ta(e,ea.Varint)),uo(t)),"varintField");var Od=s((e,t)=>dt(e,t?1:0),"boolField"),Zt=s((e,t)=>_e(uo(ta(e,ea.Fixed64)),Uk(t)),"fixed64Field"),tc=s((e,t)=>_e(uo(ta(e,ea.Fixed32)),qk(t)),"fixed32Field"),po=s((e,t)=>_e(uo(ta(e,ea.Fixed64)),Bk(t)),"doubleField"),ra=s((e,t)=>_e(uo(ta(e,ea.LengthDelimited)),uo(t.length),t),"lengthDelimitedField"),jn=s((e,t)=>ra(e,$k(t)),"stringField"),Un=s((e,t)=>ra(e,Vk(t)),"bytesFieldFromHex"),bt=s((e,t)=>ra(e,t),"messageField"),je=s((e,t,r)=>_e(...t.map(n=>bt(e,r(n)))),"repeatedField");var $t=s((e,t)=>t!==void 0&&t!==""?jn(e,t):new Uint8Array(0),"optionalStringField");var Md=s(e=>e.stringValue!==void 0&&e.stringValue!==null?jn(1,e.stringValue):e.boolValue!==void 0&&e.boolValue!==null?Od(2,e.boolValue):e.intValue!==void 0&&e.intValue!==null?dt(3,BigInt(e.intValue)):e.doubleValue!==void 0&&e.doubleValue!==null?po(4,e.doubleValue):e.arrayValue!==void 0?bt(5,Wk(e.arrayValue)):e.kvlistValue!==void 0?bt(6,Gk(e.kvlistValue)):e.bytesValue!==void 0?ra(7,e.bytesValue):new Uint8Array(0),"encodeAnyValue"),Wk=s(e=>je(1,e.values,Md),"encodeArrayValue"),Gk=s(e=>je(1,e.values,an),"encodeKeyValueList"),an=s(e=>_e(jn(1,e.key),bt(2,Md(e.value))),"encodeKeyValue"),Pd=s(e=>_e(jn(1,e.name),$t(2,e.version),e.attributes?je(3,e.attributes,an):new Uint8Array(0),e.droppedAttributesCount?dt(4,e.droppedAttributesCount):new Uint8Array(0)),"encodeInstrumentationScope"),Nd=s(e=>_e(je(1,e.attributes,an),e.droppedAttributesCount>0?dt(2,e.droppedAttributesCount):new Uint8Array(0)),"encodeResource");var Jk=s(e=>_e($t(2,e.message),dt(3,e.code)),"encodeStatus"),zk=s(e=>_e(Zt(1,BigInt(e.timeUnixNano)),jn(2,e.name),je(3,e.attributes,an),e.droppedAttributesCount>0?dt(4,e.droppedAttributesCount):new Uint8Array(0)),"encodeEvent"),Kk=s(e=>_e(Un(1,e.traceId),Un(2,e.spanId),$t(3,e.traceState),je(4,e.attributes,an),e.droppedAttributesCount>0?dt(5,e.droppedAttributesCount):new Uint8Array(0),e.flags!==void 0?tc(6,e.flags):new Uint8Array(0)),"encodeLink"),Yk=s(e=>_e(Un(1,e.traceId),Un(2,e.spanId),$t(3,e.traceState),e.parentSpanId!==void 0?Un(4,e.parentSpanId):new Uint8Array(0),jn(5,e.name),dt(6,e.kind),Zt(7,BigInt(e.startTimeUnixNano)),Zt(8,BigInt(e.endTimeUnixNano)),je(9,e.attributes,an),e.droppedAttributesCount>0?dt(10,e.droppedAttributesCount):new Uint8Array(0),je(11,e.events,zk),e.droppedEventsCount>0?dt(12,e.droppedEventsCount):new Uint8Array(0),je(13,e.links,Kk),e.droppedLinksCount>0?dt(14,e.droppedLinksCount):new Uint8Array(0),bt(15,Jk(e.status)),e.flags!==void 0?tc(16,e.flags):new Uint8Array(0)),"encodeSpan"),Xk=s(e=>_e(bt(1,Pd(e.scope)),je(2,e.spans,Yk),$t(3,e.schemaUrl)),"encodeScopeSpans"),Zk=s(e=>_e(bt(1,Nd(e.resource)),je(2,e.scopeSpans,Xk),$t(3,e.schemaUrl)),"encodeResourceSpans"),dv=s(e=>je(1,e.resourceSpans,Zk),"encodeTracesData");var pv=s(e=>_e(Zt(2,BigInt(e.startTimeUnixNano)),Zt(3,BigInt(e.timeUnixNano)),e.asDouble!==void 0?po(4,e.asDouble):new Uint8Array(0),e.asInt!==void 0?Zt(6,BigInt(e.asInt)):new Uint8Array(0),je(7,e.attributes,an),e.flags!==void 0?dt(8,e.flags):new Uint8Array(0)),"encodeNumberDataPoint"),Qk=s(e=>{let t=_e(...e.bucketCounts.map(n=>Zt(6,BigInt(n)))),r=_e(...e.explicitBounds.map(n=>po(7,n)));return _e(Zt(2,BigInt(e.startTimeUnixNano)),Zt(3,BigInt(e.timeUnixNano)),Zt(4,BigInt(e.count)),e.sum!==void 0?po(5,e.sum):new Uint8Array(0),t,r,je(9,e.attributes,an),e.flags!==void 0?dt(10,e.flags):new Uint8Array(0),e.min!==void 0?po(11,e.min):new Uint8Array(0),e.max!==void 0?po(12,e.max):new Uint8Array(0))},"encodeHistogramDataPoint"),e0=s(e=>je(1,e.dataPoints,pv),"encodeGauge"),t0=s(e=>_e(je(1,e.dataPoints,pv),dt(2,e.aggregationTemporality),Od(3,e.isMonotonic)),"encodeSum"),r0=s(e=>_e(je(1,e.dataPoints,Qk),dt(2,e.aggregationTemporality)),"encodeHistogram"),n0=s(e=>_e(jn(1,e.name),$t(2,e.description),$t(3,e.unit),e.gauge!==void 0?bt(5,e0(e.gauge)):new Uint8Array(0),e.sum!==void 0?bt(7,t0(e.sum)):new Uint8Array(0),e.histogram!==void 0?bt(9,r0(e.histogram)):new Uint8Array(0)),"encodeMetric"),o0=s(e=>_e(bt(1,Pd(e.scope)),je(2,e.metrics,n0),$t(3,e.schemaUrl)),"encodeScopeMetrics"),s0=s(e=>_e(bt(1,Nd(e.resource)),je(2,e.scopeMetrics,o0),$t(3,e.schemaUrl)),"encodeResourceMetrics"),fv=s(e=>je(1,e.resourceMetrics,s0),"encodeMetricsData");var i0=s(e=>_e(Zt(1,BigInt(e.timeUnixNano)),e.severityNumber!==void 0?dt(2,e.severityNumber):new Uint8Array(0),$t(3,e.severityText),e.body!==void 0?bt(5,Md(e.body)):new Uint8Array(0),je(6,e.attributes,an),e.droppedAttributesCount!==void 0&&e.droppedAttributesCount>0?dt(7,e.droppedAttributesCount):new Uint8Array(0),e.flags!==void 0?tc(8,e.flags):new Uint8Array(0),e.traceId!==void 0&&e.traceId!==""?Un(9,e.traceId):new Uint8Array(0),e.spanId!==void 0&&e.spanId!==""?Un(10,e.spanId):new Uint8Array(0),e.observedTimeUnixNano!==void 0?Zt(11,BigInt(e.observedTimeUnixNano)):new Uint8Array(0)),"encodeLogRecord"),a0=s(e=>_e(bt(1,Pd(e.scope)),je(2,e.logRecords,i0),$t(3,e.schemaUrl)),"encodeScopeLogs"),l0=s(e=>_e(bt(1,Nd(e.resource)),je(2,e.scopeLogs,a0),$t(3,e.schemaUrl)),"encodeResourceLogs"),mv=s(e=>je(1,e.resourceLogs,l0),"encodeLogsData");var fo=class extends Gm()("effect/observability/OtlpSerialization"){static{s(this,"OtlpSerialization")}},u0=qu(fo,{traces:s(e=>dl(e),"traces"),metrics:s(e=>dl(e),"metrics"),logs:s(e=>dl(e),"logs")}),d0=qu(fo,{traces:s(e=>ul(dv(e),"application/x-protobuf"),"traces"),metrics:s(e=>ul(fv(e),"application/x-protobuf"),"metrics"),logs:s(e=>ul(mv(e),"application/x-protobuf"),"logs")});var gv=is(function*(e){let t=yield*fo,r=yield*lv(e.resource),n={name:cv(r)},o=yield*iv({label:"OtlpLogger",url:e.url,headers:e.headers,maxBatchSize:e.maxBatchSize??1e3,exportInterval:e.exportInterval??os(1),body:s(a=>t.logs({resourceLogs:[{resource:r,scopeLogs:[{scope:n,logRecords:a}]}]}),"body"),shutdownTimeout:e.shutdownTimeout??os(3)}),i={excludeLogSpans:e.excludeLogSpans??!1,clock:yield*sl};return Kg(a=>{o.push(f0(a,i))})}),hv=s(e=>Yg([gv(e)],{mergeWithExisting:e.mergeWithExisting??!0}),"layer"),p0=s(e=>cg(function*(){let{disabled:t,endpoint:r,exporters:n}=yield*Ju({disabled:Gg("OTEL_SDK_DISABLED").pipe(as(!1)),endpoint:ov("LOGS"),exporters:sv("LOGS")});if(t||!r||!n.includes("otlp"))return tg;let{baseTimeout:o,logsTimeout:i,exportTimeout:a,scheduleDelay:l,maxBatchSize:d}=yield*Ju({baseTimeout:ls(cs("OTEL_EXPORTER_OTLP_TIMEOUT")),logsTimeout:ls(cs("OTEL_EXPORTER_OTLP_LOGS_TIMEOUT")),exportTimeout:ls(cs("OTEL_BLRP_EXPORT_TIMEOUT")),scheduleDelay:ls(cs("OTEL_BLRP_SCHEDULE_DELAY")),maxBatchSize:ls(cs("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE"))}),f=qm([i,o,a]).pipe(ju(g=>Uu(g))),m=ju(l,g=>Uu(g));return hv({url:r.toString(),resource:e?.resource,headers:e?.headers??(yield*nv("LOGS")),exportInterval:rl(m),maxBatchSize:rl(d),shutdownTimeout:rl(f),excludeLogSpans:e?.excludeLogSpans,mergeWithExisting:e?.mergeWithExisting})}).pipe(al,rg),"layerFromConfig"),f0=s((e,t)=>{let n=t.clock.currentTimeNanosUnsafe().toString(),o=e.date.getTime(),i=Dd(Object.entries(e.fiber.getRef(Ym)));if(i.push({key:"fiberId",value:{intValue:e.fiber.id}}),!t.excludeLogSpans)for(let[d,f]of e.fiber.getRef(Xm))i.push({key:`logSpan.${d}`,value:{stringValue:`${o-f}ms`}});e.cause.reasons.length>0&&i.push({key:"log.error",value:{stringValue:ng(e.cause)}});let a=Wm(e.message),l={severityNumber:m0(e.logLevel),severityText:e.logLevel,timeUnixNano:n,observedTimeUnixNano:n,attributes:i,body:ec(a.length===1?a[0]:a),droppedAttributesCount:0};return e.fiber.currentSpan&&(l.traceId=e.fiber.currentSpan.traceId,l.spanId=e.fiber.currentSpan.spanId),l},"makeLogRecord"),m0=s(e=>{switch(e){case"Trace":return mo.SEVERITY_NUMBER_TRACE;case"Debug":return mo.SEVERITY_NUMBER_DEBUG;case"Info":return mo.SEVERITY_NUMBER_INFO;case"Warn":return mo.SEVERITY_NUMBER_WARN;case"Error":return mo.SEVERITY_NUMBER_ERROR;case"Fatal":return mo.SEVERITY_NUMBER_FATAL;default:return mo.SEVERITY_NUMBER_UNSPECIFIED}},"logLevelToSeverityNumber"),mo={SEVERITY_NUMBER_UNSPECIFIED:0,SEVERITY_NUMBER_TRACE:1,SEVERITY_NUMBER_TRACE2:2,SEVERITY_NUMBER_TRACE3:3,SEVERITY_NUMBER_TRACE4:4,SEVERITY_NUMBER_DEBUG:5,SEVERITY_NUMBER_DEBUG2:6,SEVERITY_NUMBER_DEBUG3:7,SEVERITY_NUMBER_DEBUG4:8,SEVERITY_NUMBER_INFO:9,SEVERITY_NUMBER_INFO2:10,SEVERITY_NUMBER_INFO3:11,SEVERITY_NUMBER_INFO4:12,SEVERITY_NUMBER_WARN:13,SEVERITY_NUMBER_WARN2:14,SEVERITY_NUMBER_WARN3:15,SEVERITY_NUMBER_WARN4:16,SEVERITY_NUMBER_ERROR:17,SEVERITY_NUMBER_ERROR2:18,SEVERITY_NUMBER_ERROR3:19,SEVERITY_NUMBER_ERROR4:20,SEVERITY_NUMBER_FATAL:21,SEVERITY_NUMBER_FATAL2:22,SEVERITY_NUMBER_FATAL3:23,SEVERITY_NUMBER_FATAL4:24};var Is={};H(Is,{Logging:()=>Is,fileLogger:()=>Ld,loggers:()=>S0,minimumLogLevel:()=>v0});import g0 from"path";var Es=crypto.randomUUID().slice(0,8);function yv(e=Es){return Tn.map(Tn.formatStructured,t=>{let r=Array.isArray(t.message)?t.message:[t.message];return[["timestamp",t.timestamp],["level",t.level],["run",e],...r.flatMap(n=>vv(n)?oc(n):[["message",n]]),...t.cause===void 0?[]:[["cause",t.cause]],...oc(t.spans),...oc(t.annotations)].map(([n,o])=>`${n}=${h0(o)}`).join(" ")})}s(yv,"formatter");function oc(e,t="",r=new WeakSet){if(r.has(e))return[[t,"[Circular]"]];r.add(e);let n=Object.entries(e);return n.length===0&&t?[[t,e]]:n.flatMap(([o,i])=>{let a=t?`${t}.${o}`:o;return vv(i)?oc(i,a,r):[[a,i]]})}s(oc,"flatten");function vv(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}s(vv,"plain");function h0(e){let t=typeof e=="string"?e:jm.format(e);return/^[^\s="\\]+$/.test(t)?t:JSON.stringify(t)}s(h0,"format");function Ld(e=g0.join(Fe.Path.log,"opencode.log"),t=Es){return Tn.toFile(yv(t),e,{flag:"a"})}s(Ld,"fileLogger");var y0=Tn.make(e=>process.stderr.write(yv().log(e)+`
703
+ `));function v0(){let e=process.env.OPENCODE_LOG_LEVEL?.toUpperCase(),t={DEBUG:"Debug",INFO:"Info",WARN:"Warn",ERROR:"Error"};return e&&e in t?t[e]:t.INFO}s(v0,"minimumLogLevel");function S0(){return process.env.OPENCODE_PRINT_LOGS==="1"?[Ld(),y0]:[Ld()]}s(S0,"loggers");var Ts={};H(Ts,{Otlp:()=>Ts,loggers:()=>x0,resource:()=>Fd,tracingLayer:()=>b0});var sc=Ee.OTEL_EXPORTER_OTLP_ENDPOINT,Sv=Ee.OTEL_EXPORTER_OTLP_HEADERS?Ee.OTEL_EXPORTER_OTLP_HEADERS.split(",").reduce((e,t)=>{let[r,...n]=t.split("=");return e[r]=n.join("="),e},{}):void 0;function w0(){let e=process.env.OTEL_RESOURCE_ATTRIBUTES;if(!e)return{};try{return Object.fromEntries(e.split(",").map(t=>{let r=t.indexOf("=");if(r<1)throw new Error("Invalid OTEL_RESOURCE_ATTRIBUTES entry");return[decodeURIComponent(t.slice(0,r)),decodeURIComponent(t.slice(r+1))]}))}catch{return{}}}s(w0,"resourceAttributes");function Fd(){return{serviceName:"opencode",serviceVersion:ms,attributes:{...w0(),"deployment.environment.name":ah,"opencode.client":Ee.OPENCODE_CLIENT,"opencode.run":Es,"service.instance.id":Es}}}s(Fd,"resource");function x0(){return sc?[nc.make({url:`${sc}/v1/logs`,resource:Fd(),headers:Sv})]:[]}s(x0,"loggers");async function b0(){if(!sc)return B.empty;let e=await import("./NodeSdk-AGMQWBHH.js"),t=await import("./esm-XWJSHYHG.js"),r=await import("./esm-NN5W7YCL.js"),{AsyncLocalStorageContextManager:n}=await import("./src-JODD73WX.js"),{context:o}=await import("./src-SMM4U63G.js"),i=new n;return i.enable(),o.setGlobalContextManager(i),e.layer(()=>({resource:Fd(),spanProcessor:new r.BatchSpanProcessor(new t.OTLPTraceExporter({url:`${sc}/v1/traces`,headers:Sv}))}))}s(b0,"tracingLayer");var wv=B.unwrap(p.gen(function*(){let e=Tn.layer([...Is.loggers(),...Ts.loggers()],{mergeWithExisting:!1}).pipe(B.provide(Jg.layer),B.provide(rc.layerJson),B.provide(zg.layer),B.orDie,B.merge(B.succeed(Zm.MinimumLogLevel,Is.minimumLogLevel())));return B.merge(e,yield*p.promise(Ts.tracingLayer))})),E0=Ue.make({name:"observability",layer:wv,deps:[]});var $n={};H($n,{InstallFailedError:()=>da,Npm:()=>$n,Service:()=>ho,add:()=>YR,install:()=>KR,node:()=>kS,sanitize:()=>AS,which:()=>XR});var _S=wr(py(),1);import er from"path";import{realpathSync as WR}from"fs";import{createRequire as GR}from"module";import{pathToFileURL as JR}from"url";import ic from"path";import I0 from"os";import{randomUUID as T0}from"crypto";var ac;(S=>{class e extends c.TaggedErrorClass()("LockTimeoutError",{key:c.String}){static{s(this,"LockTimeoutError")}}S.LockTimeoutError=e;class t extends c.TaggedErrorClass()("LockCompromisedError",{detail:c.String}){static{s(this,"LockCompromisedError")}}S.LockCompromisedError=t;class r extends c.TaggedErrorClass()("ReleaseError",{detail:c.String,cause:c.optional(c.Defect())}){static{s(this,"ReleaseError")}get message(){return this.detail}}class n extends c.TaggedErrorClass()("NotAcquired",{}){static{s(this,"NotAcquired")}}let o=6e4,i=5*6e4,a=100,l=2e3,d=Math.max(100,Math.floor(o/3)),f=xr.exponential(a,1.7).pipe(xr.either(xr.spaced(l)),xr.jittered,xr.while(R=>R.elapsed<i)),m=c.fromJsonString(c.Struct({token:c.String,pid:c.Number,hostname:c.String,createdAt:c.String})),g=c.decodeUnknownSync(m),h=c.encodeSync(m);class y extends ae.Service()("EffectFlock"){static{s(this,"Service")}}S.Service=y;function E(){return performance.timeOrigin+performance.now()}s(E,"wall");let w=s(R=>P.getOrElse(R.mtime,()=>new Date(0)).getTime(),"mtimeMs"),v=s(R=>R.reason._tag==="NotFound"||R.reason._tag==="Unknown","isPathGone"),O=B.effect(y,p.gen(function*(){let R=yield*Fe.Service,M=yield*Ie.Service,C=ic.join(R.state,"locks"),x=I0.hostname(),_=new Set,T=s(q=>M.stat(q).pipe(p.catchIf(v,()=>p.void),p.orDie),"safeStat"),b=s(q=>M.remove(q,{recursive:!0}).pipe(p.ignore),"forceRemove"),A=s(q=>M.makeDirectory(q,{mode:448}).pipe(p.as(!0),p.catchIf(fe=>fe.reason._tag==="AlreadyExists",()=>p.succeed(!1)),p.orDie),"atomicMkdir"),N=s((q,fe,pe,L)=>M.writeFileString(q,fe,{flag:"wx"}).pipe(p.catch(()=>p.gen(function*(){return yield*b(pe),yield*new t({detail:L})}))),"exclusiveWrite"),J=p.fnUntraced(function*(q){let fe=yield*T(q);return fe&&E()-w(fe)>o&&(yield*b(q)),!1}),ne=p.fnUntraced(function*(q){_.has(q)||(yield*M.makeDirectory(q,{recursive:!0}).pipe(p.orDie),_.add(q))}),de=p.fnUntraced(function*(q,fe,pe){let L=E(),$=yield*T(fe);if($)return L-w($)>o;let ue=yield*T(pe);if(ue)return L-w(ue)>o;let Q=yield*T(q);return Q?L-w(Q)>o:!1}),he=s((q,fe)=>p.gen(function*(){let pe=T0(),L=ic.join(q,"meta.json"),$=ic.join(q,"heartbeat");if(!(yield*A(q))){if(!(yield*de(q,$,L)))return yield*new n;let Se=q+".breaker";if(!(yield*M.makeDirectory(Se,{mode:448}).pipe(p.as(!0),p.catchIf(mt=>mt.reason._tag==="AlreadyExists",()=>J(Se)),p.catchIf(v,()=>p.succeed(!1)),p.orDie)))return yield*new n;if(!(yield*p.gen(function*(){return(yield*de(q,$,L))?(yield*b(q),yield*A(q)):!1}).pipe(p.ensuring(b(Se)))))return yield*new n}yield*N($,"",q,"heartbeat already existed");let Q=h({token:pe,pid:process.pid,hostname:x,createdAt:new Date().toISOString()});return yield*N(L,Q,q,"meta.json already existed"),{token:pe,metaPath:L,heartbeatPath:$,lockDir:q}}).pipe(p.withSpan("EffectFlock.tryAcquire",{attributes:{key:fe}})),"tryAcquireLockDir"),Ae=s((q,fe)=>he(q,fe).pipe(p.retry({while:s(pe=>pe._tag==="NotAcquired","while"),schedule:f}),p.catchTag("NotAcquired",()=>p.fail(new e({key:fe})))),"acquireHandle"),it=s(q=>p.gen(function*(){let fe=yield*M.readFileString(q.metaPath).pipe(p.catch(L=>v(L)?p.die(new r({detail:"metadata missing"})):p.die(L)));if((yield*p.try({try:s(()=>g(fe),"try"),catch:s(L=>new r({detail:"metadata invalid",cause:L}),"catch")}).pipe(p.orDie)).token!==q.token)return yield*p.die(new r({detail:"token mismatch"}));yield*b(q.lockDir)}),"release"),ft=p.fn("EffectFlock.acquire")(function*(q,fe){let pe=fe??C;yield*ne(pe);let L=ic.join(pe,xl.fast(q)+".lock"),$=yield*p.acquireRelease(Ae(L,q),ue=>it(ue));yield*M.utimes($.heartbeatPath,new Date,new Date).pipe(p.ignore,p.repeat(xr.spaced(d)),p.forkScoped)}),Ze=Lm.dual(q=>p.isEffect(q[0]),(q,fe,pe)=>p.scoped(p.gen(function*(){return yield*ft(fe,pe),yield*q})));return y.of({acquire:ft,withLock:Ze})}));S.node=Pr({service:y,layer:O,deps:[Fe.node,Ie.node]})})(ac||={});function xv(e,t){let r,n=s(()=>r??=Xg.make(B.provideMerge(t,na.layer),{memoMap:tv}),"getRuntime");return{runSync:s(o=>n().runSync(e.use(o)),"runSync"),runPromiseExit:s((o,i)=>n().runPromiseExit(e.use(o),i),"runPromiseExit"),runPromise:s((o,i)=>n().runPromise(e.use(o),i),"runPromise"),runFork:s(o=>n().runFork(e.use(o)),"runFork"),runCallback:s(o=>n().runCallback(e.use(o)),"runCallback")}}s(xv,"makeRuntime");var ua={};H(ua,{NpmConfig:()=>ua,load:()=>IS,registry:()=>HR});var ES=wr(iS(),1),Bn=wr(bS(),1);import{fileURLToPath as $R}from"url";var VR=$R(new URL("..",import.meta.url)),IS=s(e=>p.tryPromise({try:s(async()=>{let t=new ES.default({npmPath:VR,cwd:e,env:{...process.env},argv:[process.execPath,process.execPath],execPath:process.execPath,platform:process.platform,definitions:Bn.definitions,flatten:Bn.flatten,nerfDarts:Bn.nerfDarts,shorthands:Bn.shorthands,warn:!1});return await t.load(),t.flat},"try"),catch:s(t=>t,"catch")}).pipe(p.orElseSucceed(()=>({}))),"load"),HR=s(e=>IS(e).pipe(p.map(t=>{let r=typeof t.registry=="string"?t.registry:"https://registry.npmjs.org";return r.endsWith("/")?r.slice(0,-1):r})),"registry");var da=class extends c.TaggedErrorClass()("NpmInstallFailedError",{add:c.Array(c.String).pipe(c.optional),dir:c.String,cause:c.optional(c.Defect())}){static{s(this,"InstallFailedError")}},ho=class extends ae.Service()("@opencode/Npm"){static{s(this,"Service")}},TS=process.platform==="win32"?new Set(["<",">",":",'"',"|","?","*"]):void 0;function AS(e){return TS?Array.from(e,t=>TS.has(t)||t.charCodeAt(0)<32?"_":t).join(""):e}s(AS,"sanitize");var ip=s((e,t)=>{let r;try{r=typeof Bun<"u"?import.meta.resolve(e,t):JR(GR(er.join(t,"package.json")).resolve(e)).href}catch{r=void 0}return{directory:t,entrypoint:r}},"resolveEntryPoint"),zR=B.effect(ho,p.gen(function*(){let e=yield*Ie.Service,t=yield*Fe.Service,r=yield*Rg.FileSystem,n=yield*ac.Service,o=(()=>{try{return WR(t.cache)}catch{return t.cache}})(),i=s(m=>er.join(o,"packages",AS(m)),"directory"),a=s(m=>p.gen(function*(){yield*n.acquire(`npm-install:${m.dir}`);let{Arborist:g}=yield*p.promise(()=>import("./lib-7VH6D2QJ.js")),h=m.add??[],y=yield*ua.load(m.dir),E=new g({...y,path:m.dir,binLinks:!0,progress:!1,savePrefix:"",ignoreScripts:!0});return yield*p.tryPromise({try:s(()=>E.reify({...y,add:h,save:!0,saveType:"prod"}),"try"),catch:s(w=>new da({cause:w,add:h,dir:m.dir}),"catch")})}).pipe(p.withSpan("Npm.reify",{attributes:m})),"reify"),l=p.fn("Npm.add")(function*(m){let g=i(m),h=(()=>{try{return(0,_S.default)(m).name??m}catch{return m}})();if(yield*e.existsSafe(er.join(g,"node_modules",h)))return ip(h,er.join(g,"node_modules",h));let E=(yield*a({dir:g,add:[m]})).edgesOut.values().next().value?.to;if(!E){let w=ip(h,er.join(g,"node_modules",h));return w.entrypoint?w:yield*new da({add:[m],dir:g})}return ip(E.name,E.path)},p.scoped),d=p.fn("Npm.install")(function*(m,g){if(!(yield*e.access(m,{writable:!0}).pipe(p.as(!0),p.orElseSucceed(()=>!1))))return;let y=g?.add.map(E=>[E.name,E.version].filter(Boolean).join("@"))??[];(yield*p.gen(function*(){return(yield*e.existsSafe(er.join(m,"node_modules")))?!1:(yield*a({add:y,dir:m}),!0)}).pipe(p.withSpan("Npm.checkNodeModules")))||(yield*p.gen(function*(){let E=yield*e.readJson(er.join(m,"package.json")).pipe(p.orElseSucceed(()=>({}))),w=yield*e.readJson(er.join(m,"package-lock.json")).pipe(p.orElseSucceed(()=>({}))),v=E,O=w,k=new Set([...Object.keys(v?.dependencies||{}),...Object.keys(v?.devDependencies||{}),...Object.keys(v?.peerDependencies||{}),...Object.keys(v?.optionalDependencies||{}),...(g?.add||[]).map(M=>M.name)]),S=O?.packages?.[""]||{},R=new Set([...Object.keys(S?.dependencies||{}),...Object.keys(S?.devDependencies||{}),...Object.keys(S?.peerDependencies||{}),...Object.keys(S?.optionalDependencies||{})]);for(let M of k)if(!R.has(M)){yield*a({dir:m,add:y});return}}).pipe(p.withSpan("Npm.checkDirty")))},p.scoped),f=p.fn("Npm.which")(function*(m,g){let h=i(m),y=er.join(h,"node_modules",".bin"),E=p.fnUntraced(function*(){let w=yield*r.readDirectory(y).pipe(p.catch(()=>p.succeed([])));if(w.length===0)return P.none();if(g)return w.includes(g)?P.some(g):P.none();if(w.length===1)return P.some(w[0]);let v=yield*e.readJson(er.join(h,"node_modules",m,"package.json")).pipe(p.option);if(P.isSome(v)){let O=v.value;if(O?.bin){let k=m.startsWith("@")?m.split("/")[1]:m,S=O.bin;if(typeof S=="string")return P.some(k);let R=Object.keys(S);return R.length===1?P.some(R[0]):S[k]?P.some(k):P.some(R[0])}}return P.some(w[0])});return P.getOrUndefined(yield*p.gen(function*(){let w=yield*E();if(P.isSome(w))return P.some(er.join(y,w.value));yield*r.remove(er.join(h,"package-lock.json")).pipe(p.orElseSucceed(()=>{})),yield*l(m);let v=yield*E();return P.isNone(v)?P.none():P.some(er.join(y,v.value))}).pipe(p.scoped,p.orElseSucceed(()=>P.none())))});return ho.of({add:l,install:d,which:f})})),kS=Pr({service:ho,layer:zR,deps:[Ie.node,Fe.node,gh,ac.node]}),{runPromise:ap}=xv(ho,Ue.compile(kS));async function KR(...e){return ap(t=>t.install(...e))}s(KR,"install");async function YR(...e){return ap(t=>t.add(...e))}s(YR,"add");async function XR(...e){return ap(t=>t.which(...e))}s(XR,"which");var js={};H(js,{AccessToken:()=>fa,Account:()=>js,AccountID:()=>pa,AccountRepoError:()=>Ms,AccountServiceError:()=>Br,AccountTransportError:()=>vo,DeviceCode:()=>Ls,Info:()=>Ds,Login:()=>Ps,Org:()=>Os,OrgID:()=>pc,PollDenied:()=>Eo,PollError:()=>Io,PollExpired:()=>bo,PollPending:()=>wo,PollResult:()=>LS,PollSlow:()=>xo,PollSuccess:()=>So,RefreshToken:()=>Ns,Service:()=>_o,UserCode:()=>ma,node:()=>dC,use:()=>cC});var dc=s(e=>e.pipe(Mr.retryTransient({retryOn:"errors-and-responses",times:2,schedule:xr.exponential(200).pipe(xr.jittered)})),"withTransientReadRetry");var Fs={};H(Fs,{AccountRepo:()=>Fs,Service:()=>To,node:()=>oC,use:()=>rC});var ZR=c.String.pipe(c.brand("AccountID")),NS=c.String.pipe(c.brand("OrgID")),i3=c.String.pipe(c.brand("AccessToken")),a3=c.String.pipe(c.brand("RefreshToken")),QR=c.String.pipe(c.brand("DeviceCode")),eC=c.String.pipe(c.brand("UserCode")),RS=class extends c.Class("Account")({id:ZR,email:c.String,url:c.String,active_org_id:c.NullOr(NS)}){static{s(this,"Info")}},CS=class extends c.Class("Org")({id:NS,name:c.String}){static{s(this,"Org")}},DS=class extends c.TaggedErrorClass()("AccountRepoError",{message:c.String,cause:c.optional(c.Defect())}){static{s(this,"AccountRepoError")}},OS=class extends c.TaggedErrorClass()("AccountServiceError",{message:c.String,cause:c.optional(c.Defect())}){static{s(this,"AccountServiceError")}},MS=class e extends c.TaggedErrorClass()("AccountTransportError",{method:c.String,url:c.String,description:c.optional(c.String),cause:c.optional(c.Defect())}){static{s(this,"AccountTransportError")}static fromHttpClientError(t){return new e({method:t.request.method,url:t.request.url,description:t.description,cause:t.cause})}get message(){return[`Could not reach ${this.method} ${this.url}.`,"This failed before the server returned an HTTP response.",this.description,"Check your network, proxy, or VPN configuration and try again."].filter(Boolean).join(`
704
+ `)}},PS=class extends c.Class("Login")({code:QR,user:eC,url:c.String,server:c.String,expiry:c.Duration,interval:c.Duration}){static{s(this,"Login")}},lp=class extends c.TaggedClass()("PollSuccess",{email:c.String}){static{s(this,"PollSuccess")}},cp=class extends c.TaggedClass()("PollPending",{}){static{s(this,"PollPending")}},up=class extends c.TaggedClass()("PollSlow",{}){static{s(this,"PollSlow")}},dp=class extends c.TaggedClass()("PollExpired",{}){static{s(this,"PollExpired")}},pp=class extends c.TaggedClass()("PollDenied",{}){static{s(this,"PollDenied")}},fp=class extends c.TaggedClass()("PollError",{cause:c.Defect()}){static{s(this,"PollError")}},l3=c.Union([lp,cp,up,dp,pp,fp]);var tr=Ut("account",{id:z().$type().primaryKey(),email:z().notNull(),url:z().notNull(),access_token:z().$type().notNull(),refresh_token:z().$type().notNull(),token_expiry:qe(),...tn}),yo=Ut("account_state",{id:qe().primaryKey(),active_account_id:z().$type().references(()=>tr.id,{onDelete:"set null"}),active_org_id:z().$type()}),m3=Ut("control_account",{email:z().notNull(),url:z().notNull(),access_token:z().$type().notNull(),refresh_token:z().$type().notNull(),token_expiry:qe(),active:qe({mode:"boolean"}).notNull().$default(()=>!1),...tn},e=>[Sl({columns:[e.email,e.url]})]);var pa=c.String.pipe(c.brand("AccountID")),pc=c.String.pipe(c.brand("OrgID")),fa=c.String.pipe(c.brand("AccessToken")),Ns=c.String.pipe(c.brand("RefreshToken")),Ls=c.String.pipe(c.brand("DeviceCode")),ma=c.String.pipe(c.brand("UserCode")),Ds=class extends c.Class("Account")({id:pa,email:c.String,url:c.String,active_org_id:c.NullOr(pc)}){static{s(this,"Info")}},Os=class extends c.Class("Org")({id:pc,name:c.String}){static{s(this,"Org")}},Ms=class extends c.TaggedErrorClass()("AccountRepoError",{message:c.String,cause:c.optional(c.Defect())}){static{s(this,"AccountRepoError")}},Br=class extends c.TaggedErrorClass()("AccountServiceError",{message:c.String,cause:c.optional(c.Defect())}){static{s(this,"AccountServiceError")}},vo=class e extends c.TaggedErrorClass()("AccountTransportError",{method:c.String,url:c.String,description:c.optional(c.String),cause:c.optional(c.Defect())}){static{s(this,"AccountTransportError")}static fromHttpClientError(t){return new e({method:t.request.method,url:t.request.url,description:t.description,cause:t.cause})}get message(){return[`Could not reach ${this.method} ${this.url}.`,"This failed before the server returned an HTTP response.",this.description,"Check your network, proxy, or VPN configuration and try again."].filter(Boolean).join(`
705
+ `)}},Ps=class extends c.Class("Login")({code:Ls,user:ma,url:c.String,server:c.String,expiry:c.Duration,interval:c.Duration}){static{s(this,"Login")}},So=class extends c.TaggedClass()("PollSuccess",{email:c.String}){static{s(this,"PollSuccess")}},wo=class extends c.TaggedClass()("PollPending",{}){static{s(this,"PollPending")}},xo=class extends c.TaggedClass()("PollSlow",{}){static{s(this,"PollSlow")}},bo=class extends c.TaggedClass()("PollExpired",{}){static{s(this,"PollExpired")}},Eo=class extends c.TaggedClass()("PollDenied",{}){static{s(this,"PollDenied")}},Io=class extends c.TaggedClass()("PollError",{cause:c.Defect()}){static{s(this,"PollError")}},LS=c.Union([So,wo,xo,bo,Eo,Io]);var fc=s(e=>{let t=new URL(e);t.search="",t.hash="";let r=t.pathname.replace(/\/+$/,"");return r.length===0?t.origin:`${t.origin}${r}`},"normalizeServerUrl");var FS=1,To=class extends ae.Service()("@opencode/AccountRepo"){static{s(this,"Service")}},rC=Rn(To),nC=B.effect(To,p.gen(function*(){let{db:e}=yield*Rt.Service,t=c.decodeUnknownSync(Ds),r=s(h=>h.pipe(p.mapError(y=>new Ms({message:"Database operation failed",cause:y}))),"query"),n=p.fnUntraced(function*(){let h=yield*e.select().from(yo).where(F(yo.id,FS)).get();if(!h?.active_account_id)return;let y=yield*e.select().from(tr).where(F(tr.id,h.active_account_id)).get();if(y)return{...y,active_org_id:h.active_org_id??null}}),o=s((h,y)=>{let E=P.getOrNull(y);return e.insert(yo).values({id:FS,active_account_id:h,active_org_id:E}).onConflictDoUpdate({target:yo.id,set:{active_account_id:h,active_org_id:E}}).run()},"state"),i=p.fn("AccountRepo.active")(()=>r(n()).pipe(p.map(h=>h?P.some(t(h)):P.none()))),a=p.fn("AccountRepo.list")(()=>r(e.select().from(tr).all().pipe(p.map(h=>h.map(y=>t({...y,active_org_id:null})))))),l=p.fn("AccountRepo.remove")(h=>r(e.transaction(y=>p.gen(function*(){yield*y.update(yo).set({active_account_id:null,active_org_id:null}).where(F(yo.active_account_id,h)).run(),yield*y.delete(tr).where(F(tr.id,h)).run()}))).pipe(p.asVoid)),d=p.fn("AccountRepo.use")((h,y)=>r(o(h,y)).pipe(p.asVoid)),f=p.fn("AccountRepo.getRow")(h=>r(e.select().from(tr).where(F(tr.id,h)).get()).pipe(p.map(P.fromNullishOr))),m=p.fn("AccountRepo.persistToken")(h=>r(e.update(tr).set({access_token:h.accessToken,refresh_token:h.refreshToken,token_expiry:P.getOrNull(h.expiry)}).where(F(tr.id,h.accountID)).run()).pipe(p.asVoid)),g=p.fn("AccountRepo.persistAccount")(h=>r(e.transaction(y=>p.gen(function*(){let E=fc(h.url);yield*y.insert(tr).values({id:h.id,email:h.email,url:E,access_token:h.accessToken,refresh_token:h.refreshToken,token_expiry:h.expiry}).onConflictDoUpdate({target:tr.id,set:{email:h.email,url:E,access_token:h.accessToken,refresh_token:h.refreshToken,token_expiry:h.expiry}}).run(),yield*o(h.id,h.orgID)}))).pipe(p.asVoid));return To.of({active:i,list:a,remove:l,use:d,getRow:f,persistToken:m,persistAccount:g})})),oC=Ue.make({service:To,layer:nC,deps:[Rt.node]});var gp=class extends c.Class("RemoteConfig")({config:c.Record(c.String,c.Json)}){static{s(this,"RemoteConfig")}},mc=c.Number.pipe(c.decodeTo(c.Duration,{decode:ll.transform(e=>ur.seconds(e)),encode:ll.transform(e=>ur.toSeconds(e))})),hp=class extends c.Class("TokenRefresh")({access_token:fa,refresh_token:Ns,expires_in:mc}){static{s(this,"TokenRefresh")}},yp=class extends c.Class("DeviceAuth")({device_code:Ls,user_code:ma,verification_uri_complete:c.String,expires_in:mc,interval:mc}){static{s(this,"DeviceAuth")}},vp=class extends c.Class("DeviceTokenSuccess")({access_token:fa,refresh_token:Ns,token_type:c.Literal("Bearer"),expires_in:mc}){static{s(this,"DeviceTokenSuccess")}},gc=class extends c.Class("DeviceTokenError")({error:c.String,error_description:c.String}){static{s(this,"DeviceTokenError")}toPollResult(){return this.error==="authorization_pending"?new wo:this.error==="slow_down"?new xo:this.error==="expired_token"?new bo:this.error==="access_denied"?new Eo:new Io({cause:this.error})}},sC=c.Union([vp,gc]),Sp=class extends c.Class("User")({id:pa,email:c.String}){static{s(this,"User")}},hc=class extends c.Class("ClientId")({client_id:c.String}){static{s(this,"ClientId")}},yc=class extends c.Class("DeviceTokenRequest")({grant_type:c.String,device_code:Ls,client_id:c.String}){static{s(this,"DeviceTokenRequest")}},vc=class extends c.Class("TokenRefreshRequest")({grant_type:c.String,refresh_token:Ns,client_id:c.String}){static{s(this,"TokenRefreshRequest")}},mp="opencode-cli",iC=ur.minutes(5),aC=ur.toMillis(iC),jS=s((e,t)=>e!=null&&e>t+aC,"isTokenFresh"),_r=s((e="Account service operation failed")=>t=>t.pipe(p.mapError(r=>lC(r,e))),"mapAccountServiceError"),lC=s((e,t)=>e instanceof Br||e instanceof vo?e:Hu.isHttpClientError(e)?e.reason._tag==="TransportError"?vo.fromHttpClientError(e.reason):new Br({message:t,cause:e}):new Br({message:t,cause:e}),"accountErrorFromCause"),_o=class extends ae.Service()("@opencode/Account"){static{s(this,"Service")}},cC=Rn(_o),uC=B.effect(_o,p.gen(function*(){let e=yield*Fs.Service,t=yield*Mr.HttpClient,r=dc(t),n=Mr.filterStatusOk(t),o=Mr.filterStatusOk(r),i=s(x=>r.execute(x).pipe(_r("HTTP request failed")),"executeRead"),a=s(x=>o.execute(x).pipe(_r("HTTP request failed")),"executeReadOk"),l=s(x=>x.pipe(p.flatMap(_=>n.execute(_)),_r("HTTP request failed")),"executeEffectOk"),d=s(x=>x.pipe(p.flatMap(_=>t.execute(_)),_r("HTTP request failed")),"executeEffect"),f=p.fnUntraced(function*(x){let _=yield*Oi.currentTimeMillis,T=yield*l(Le.post(`${x.url}/auth/device/token`).pipe(Le.acceptJson,Le.schemaBodyJson(vc)(new vc({grant_type:"refresh_token",refresh_token:x.refresh_token,client_id:mp})))),b=yield*En.schemaBodyJson(hp)(T).pipe(_r("Failed to decode response")),A=P.some(_+ur.toMillis(b.expires_in));return yield*e.persistToken({accountID:x.id,accessToken:b.access_token,refreshToken:b.refresh_token,expiry:A}),b.access_token}),m=yield*Ku.make({capacity:Number.POSITIVE_INFINITY,timeToLive:ur.zero,lookup:p.fnUntraced(function*(x){let _=yield*e.getRow(x);if(P.isNone(_))return yield*p.fail(new Br({message:"Account not found during token refresh"}));let T=_.value,b=yield*Oi.currentTimeMillis;return jS(T.token_expiry,b)?T.access_token:yield*f(T)})}),g=p.fnUntraced(function*(x){let _=yield*Oi.currentTimeMillis;return jS(x.token_expiry,_)?x.access_token:yield*Ku.get(m,x.id)}),h=p.fnUntraced(function*(x){let _=yield*e.getRow(x);if(P.isNone(_))return P.none();let T=_.value,b=yield*g(T);return P.some({account:T,accessToken:b})}),y=p.fnUntraced(function*(x,_){let T=yield*a(Le.get(`${x}/api/orgs`).pipe(Le.acceptJson,Le.bearerToken(_)));return yield*En.schemaBodyJson(c.Array(Os))(T).pipe(_r("Failed to decode response"))}),E=p.fnUntraced(function*(x,_){let T=yield*a(Le.get(`${x}/api/user`).pipe(Le.acceptJson,Le.bearerToken(_)));return yield*En.schemaBodyJson(Sp)(T).pipe(_r("Failed to decode response"))}),w=p.fn("Account.token")(x=>h(x).pipe(p.map(P.map(_=>_.accessToken)))),v=p.fn("Account.activeOrg")(function*(){let x=yield*e.active();if(P.isNone(x))return P.none();let _=x.value;if(!_.active_org_id)return P.none();let b=(yield*k(_.id)).find(A=>A.id===_.active_org_id);return b?P.some({account:_,org:b}):P.none()}),O=p.fn("Account.orgsByAccount")(function*(){let x=yield*e.list();return yield*p.forEach(x,_=>k(_.id).pipe(p.catch(()=>p.succeed([])),p.map(T=>({account:_,orgs:T}))),{concurrency:3})}),k=p.fn("Account.orgs")(function*(x){let _=yield*h(x);if(P.isNone(_))return[];let{account:T,accessToken:b}=_.value;return yield*y(T.url,b)}),S=p.fn("Account.remove")(function*(x){let _=yield*e.active();if(yield*e.remove(x),P.isNone(_)||_.value.id!==x)return;let T=(yield*O()).flatMap(b=>b.orgs.map(A=>({accountID:b.account.id,orgID:A.id})))[0];T&&(yield*e.use(T.accountID,P.some(T.orgID)))}),R=p.fn("Account.config")(function*(x,_){let T=yield*h(x);if(P.isNone(T))return P.none();let{account:b,accessToken:A}=T.value,N=yield*i(Le.get(`${b.url}/api/config`).pipe(Le.acceptJson,Le.bearerToken(A),Le.setHeaders({"x-org-id":_})));if(N.status===404)return P.none();let J=yield*En.filterStatusOk(N).pipe(_r()),ne=yield*En.schemaBodyJson(gp)(J).pipe(_r("Failed to decode response"));return P.some(ne.config)}),M=p.fn("Account.login")(function*(x){let _=fc(x),T=yield*l(Le.post(`${_}/auth/device/code`).pipe(Le.acceptJson,Le.schemaBodyJson(hc)(new hc({client_id:mp})))),b=yield*En.schemaBodyJson(yp)(T).pipe(_r("Failed to decode response")),A=yield*p.try({try:s(()=>{let N=new URL(b.verification_uri_complete,`${_}/`);if(N.protocol!=="http:"&&N.protocol!=="https:")throw new Error("expected HTTP(S)");return N.href},"try"),catch:s(N=>new Br({message:"Invalid device verification URL",cause:N}),"catch")});return new Ps({code:b.device_code,user:b.user_code,url:A,server:_,expiry:b.expires_in,interval:b.interval})}),C=p.fn("Account.poll")(function*(x){let _=yield*d(Le.post(`${x.server}/auth/device/token`).pipe(Le.acceptJson,Le.schemaBodyJson(yc)(new yc({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:x.code,client_id:mp})))),T=yield*En.schemaBodyJson(sC)(_).pipe(_r("Failed to decode response"));if(T instanceof gc)return T.toPollResult();let b=T.access_token,A=E(x.server,b),N=y(x.server,b),[J,ne]=yield*p.all([A,N],{concurrency:2}),de=ne.length>0?P.some(ne[0].id):P.none(),Ae=(yield*Oi.currentTimeMillis)+ur.toMillis(T.expires_in),it=T.refresh_token;return yield*e.persistAccount({id:J.id,email:J.email,url:x.server,accessToken:b,refreshToken:it,expiry:Ae,orgID:de}),new So({email:J.email})});return _o.of({active:e.active,activeOrg:v,list:e.list,orgsByAccount:O,remove:S,use:e.use,orgs:k,config:R,token:w,login:M,poll:C})})),dC=Ue.make({service:_o,layer:uC,deps:[Fs.node,Tl]});var qs={};H(qs,{Api:()=>xc,Auth:()=>qs,AuthError:()=>Ec,Info:()=>US,OAUTH_DUMMY_KEY:()=>fC,Oauth:()=>wc,Service:()=>Us,WellKnown:()=>bc,node:()=>gC});import pC from"path";var fC="opencode-oauth-dummy-key",Sc=pC.join(Fe.Path.globalData,"auth.json"),wp=s(e=>t=>new Ec({message:e,cause:t}),"fail"),wc=class extends c.Class("OAuth")({type:c.Literal("oauth"),refresh:c.String,access:c.String,expires:zt,accountId:c.optional(c.String),enterpriseUrl:c.optional(c.String)}){static{s(this,"Oauth")}},xc=class extends c.Class("ApiAuth")({type:c.Literal("api"),key:c.String,metadata:c.optional(c.Record(c.String,c.String))}){static{s(this,"Api")}},bc=class extends c.Class("WellKnownAuth")({type:c.Literal("wellknown"),key:c.String,token:c.String}){static{s(this,"WellKnown")}},US=c.Union([wc,xc,bc]).annotate({discriminator:"type",identifier:"Auth"}),Ec=class extends c.TaggedErrorClass()("AuthError",{message:c.String,cause:c.optional(c.Defect())}){static{s(this,"AuthError")}},Us=class extends ae.Service()("@opencode/Auth"){static{s(this,"Service")}},mC=B.effect(Us,p.gen(function*(){let e=yield*Ie.Service,t=c.decodeUnknownOption(US),r=p.fn("Auth.all")(function*(){if(process.env.OPENCODE_AUTH_CONTENT)try{return JSON.parse(process.env.OPENCODE_AUTH_CONTENT)}catch{}let l=yield*e.readJson(Sc).pipe(p.orElseSucceed(()=>({})));return Hm.filterMap(l,d=>Vm.fromOption(t(d),()=>{}))}),n=p.fn("Auth.rawAll")(function*(){return yield*e.readJson(Sc).pipe(p.catchIf(l=>l?.reason?._tag==="NotFound"||l?.cause?.reason?._tag==="NotFound",()=>p.succeed({})),p.mapError(wp("Refusing to write auth data: existing auth.json could not be read")))}),o=p.fn("Auth.get")(function*(l){return(yield*r())[l]}),i=p.fn("Auth.set")(function*(l,d){let f=l.replace(/\/+$/,""),m=yield*n();f!==l&&delete m[l],delete m[f+"/"],yield*e.writeJson(Sc,{...m,[f]:d},384).pipe(p.mapError(wp("Failed to write auth data")))}),a=p.fn("Auth.remove")(function*(l){let d=l.replace(/\/+$/,""),f=yield*n();delete f[l],delete f[d],yield*e.writeJson(Sc,f,384).pipe(p.mapError(wp("Failed to write auth data")))});return Us.of({get:o,all:r,set:i,remove:a})})),gC=Ue.make({service:Us,layer:mC,deps:[Ie.node]});var Et={};H(Et,{InstanceState:()=>Et,context:()=>Ep,directory:()=>Tc,get:()=>Ip,has:()=>bC,invalidate:()=>EC,make:()=>SC,use:()=>wC,useEffect:()=>xC,workspaceID:()=>vC});var ga=ae.Reference("~opencode/InstanceRef",{defaultValue:s(()=>{},"defaultValue")}),ha=ae.Reference("~opencode/WorkspaceRef",{defaultValue:s(()=>{},"defaultValue")});var xp=new Set;function qS(e){return xp.add(e),()=>{xp.delete(e)}}s(qS,"registerDisposer");async function oJ(e){await Promise.allSettled([...xp].map(t=>t(e)))}s(oJ,"disposeInstance");var Ao={};H(Ao,{LocalContext:()=>Ao,NotFound:()=>Ic,create:()=>yC});import{AsyncLocalStorage as hC}from"async_hooks";var Ic=class extends Error{constructor(r){super(`No context found for ${r}`);this.name=r}name;static{s(this,"NotFound")}};function yC(e){let t=new hC;return{use(){let r=t.getStore();if(!r)throw new Ic(e);return r},provide(r,n){return t.run(r,n)}}}s(yC,"create");var bp=Ao.create("instance"),BS={async provide(e){return bp.provide({workspaceID:e.workspaceID},()=>e.fn())},restore(e,t){return bp.provide({workspaceID:e},t)},get workspaceID(){try{return bp.use().workspaceID}catch{return}}};var $S="~opencode/InstanceState",Ep=p.gen(function*(){let e=yield*ga;return e||(yield*p.die(new Error("InstanceRef not provided")))}),vC=p.gen(function*(){return(yield*ha)??BS.workspaceID}),Tc=p.map(Ep,e=>e.directory),SC=s(e=>p.gen(function*(){let t=yield*us.make({capacity:Number.POSITIVE_INFINITY,lookup:s(()=>p.gen(function*(){return yield*e(yield*Ep)}),"lookup")}),r=qS(n=>p.runPromise(us.invalidate(t,n)));return yield*p.addFinalizer(()=>p.sync(r)),{[$S]:$S,cache:t}}),"make"),Ip=s(e=>p.gen(function*(){return yield*us.get(e.cache,yield*Tc)}),"get"),wC=s((e,t)=>p.map(Ip(e),t),"use"),xC=s((e,t)=>p.flatMap(Ip(e),t),"useEffect"),bC=s(e=>p.gen(function*(){return yield*us.has(e.cache,yield*Tc)}),"has"),EC=s(e=>p.gen(function*(){return yield*us.invalidate(e.cache,yield*Tc)}),"invalidate");function He(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}s(He,"isRecord");function ya(e){if(e instanceof Error)return e.stack??`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{let t=JSON.stringify(e,null,2);if(t==="{}"){let r=String(e);if(r&&r!=="[object Object]")return r;let n=e.constructor?.name,o=n&&n!=="Object"?n:"Error",i=Object.getOwnPropertyNames(e);return i.length===0?`${o} (no message)`:`${o} { ${i.join(", ")} }`}return t}catch{return"Unexpected error (unserializable)"}return String(e)}s(ya,"errorFormat");function va(e){if(e instanceof Error){if(e.message)return e.message;if(e.name)return e.name}if(He(e)&&typeof e.message=="string"&&e.message)return e.message;if(He(e)&&He(e.data)&&typeof e.data.message=="string"&&e.data.message)return e.data.message;let t=String(e);if(t&&t!=="[object Object]")return t;let r=ya(e);return r||"unknown error"}s(va,"errorMessage");function wJ(e){if(e instanceof Error)return{type:e.name,message:va(e),stack:e.stack,cause:e.cause===void 0?void 0:ya(e.cause),formatted:ya(e)};if(!He(e))return{type:typeof e,message:va(e),formatted:ya(e)};let t=Object.getOwnPropertyNames(e).reduce((r,n)=>{let o=e[n];return o===void 0?r:typeof o=="string"||typeof o=="number"||typeof o=="boolean"?(r[n]=o,r):(r[n]=o instanceof Error?o.message:String(o),r)},{});return typeof t.message!="string"&&(t.message=va(e)),typeof t.type!="string"&&(t.type=e.constructor?.name),t.formatted=ya(e),t}s(wJ,"errorData");var wf={};H(wf,{Config:()=>wf,Service:()=>Bo,node:()=>sL,use:()=>rL});import nr from"path";import{pathToFileURL as ZN}from"url";import QN from"os";function VS(e,t,r){let n=s(o=>e(o,...t),"t");return r===void 0?n:Object.assign(n,{lazy:r,lazyArgs:t})}s(VS,"u");function fr(e,t,r){let n=e.length-t.length;if(n===0)return e(...t);if(n===1)return VS(e,t,r);throw new Error("Wrong number of arguments")}s(fr,"u");var _c={done:!1,hasNext:!1};function Ac(e,...t){let r=e,n=t.map(i=>"lazy"in i?IC(i):void 0),o=0;for(;o<t.length;){if(n[o]===void 0||!TC(r)){let d=t[o];r=d(r),o+=1;continue}let i=[];for(let d=o;d<t.length;d++){let f=n[d];if(f===void 0||(i.push(f),f.isSingle))break}let a=[];for(let d of r)if(HS(d,a,i))break;let{isSingle:l}=i.at(-1);r=l?a[0]:a,o+=i.length}return r}s(Ac,"C");function HS(e,t,r){if(r.length===0)return t.push(e),!1;let n=e,o=_c,i=!1;for(let[a,l]of r.entries()){let{index:d,items:f}=l;if(f.push(n),o=l(n,d,f),l.index+=1,o.hasNext){if(o.hasMany??!1){for(let m of o.next)if(HS(m,t,r.slice(a+1)))return!0;return i}n=o.next}if(!o.hasNext)break;o.done&&(i=!0)}return o.hasNext&&t.push(n),i}s(HS,"f");function IC(e){let{lazy:t,lazyArgs:r}=e,n=t(...r);return Object.assign(n,{isSingle:t.single??!1,index:0,items:[]})}s(IC,"y");function TC(e){return typeof e=="string"||typeof e=="object"&&e!==null&&Symbol.iterator in e}s(TC,"B");function WS(e,t){let r=t.length-e.length;if(r===1){let[n,...o]=t;return Ac(n,{lazy:e,lazyArgs:o})}if(r===0){let n={lazy:e,lazyArgs:t};return Object.assign(o=>Ac(o,n),n)}throw new Error("Wrong number of arguments")}s(WS,"y");function Tp(...e){return WS(_C,e)}s(Tp,"i");function _C(){let e=new Set;return t=>e.has(t)?_c:(e.add(t),{done:!1,hasNext:!0,next:t})}s(_C,"a");function AC(...e){return fr(Object.values,e)}s(AC,"r");function _p(...e){return fr(kC,e)}s(_p,"i");var kC=s((e,t)=>e.length>=t,"n");var JS={asc:s((e,t)=>e>t,"asc"),desc:s((e,t)=>e<t,"desc")};function zS(e,t){let[r,...n]=t;if(!RC(r)){let i=Ap(...n);return e(r,i)}let o=Ap(r,...n);return i=>e(i,o)}s(zS,"s");function Ap(e,t,...r){let n=typeof e=="function"?e:e[0],o=typeof e=="function"?"asc":e[1],{[o]:i}=JS,a=t===void 0?void 0:Ap(t,...r);return(l,d)=>{let f=n(l),m=n(d);return i(f,m)?1:i(m,f)?-1:a?.(l,d)??0}}s(Ap,"u");function RC(e){if(GS(e))return!0;if(typeof e!="object"||!Array.isArray(e))return!1;let[t,r,...n]=e;return GS(t)&&typeof r=="string"&&r in JS&&n.length===0}s(RC,"m");var GS=s(e=>typeof e=="function"&&e.length===1,"d");function CC(...e){return zS(DC,e)}s(CC,"a");var DC=s((e,t)=>[...e].sort(t),"n");function OC(...e){return fr(MC,e)}s(OC,"d");function MC(e,t){let r={};for(let[n,o]of Object.entries(e))t(o,n,e)&&(r[n]=o);return r}s(MC,"u");function kp(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}s(kp,"r");function mr(...e){return fr(KS,e)}s(mr,"D");function KS(e,t){let r={...e,...t};for(let n in t){if(!(n in e))continue;let{[n]:o}=e;if(!kp(o))continue;let{[n]:i}=t;kp(i)&&(r[n]=KS(o,i))}return r}s(KS,"s");function PC(...e){return fr(NC,e)}s(PC,"y");function NC(e,t){if(!_p(t,1))return{...e};if(!_p(t,2)){let{[t[0]]:n,...o}=e;return o}let r={...e};for(let n of t)delete r[n];return r}s(NC,"f");function LC(...e){return fr(FC,e)}s(LC,"i");function FC(e,t){let r={};for(let[n,o]of Object.entries(e)){let i=t(o,n,e);r[n]=i}return r}s(FC,"o");import oE from"fs/promises";var Bs={};H(Bs,{Env:()=>Bs,Service:()=>ko,node:()=>qC,use:()=>jC});var ko=class extends ae.Service()("@opencode/Env"){static{s(this,"Service")}},jC=Rn(ko),UC=B.effect(ko,p.gen(function*(){let e=yield*Et.make(p.fn("Env.state")(()=>p.succeed({...process.env}))),t=p.fn("Env.get")(i=>Et.use(e,a=>a[i])),r=p.fn("Env.all")(()=>Et.get(e)),n=p.fn("Env.set")(function*(i,a){let l=yield*Et.get(e);l[i]=a}),o=p.fn("Env.remove")(function*(i){let a=yield*Et.get(e);delete a[i]});return ko.of({get:t,all:r,set:n,remove:o})})),qC=Ue.make({service:ko,layer:UC,deps:[]});import{existsSync as Xc}from"fs";var M4=Ao.create("instance");function YS(e,t){return Ie.contains(t.directory,e)?!0:t.worktree==="/"?!1:Ie.contains(t.worktree,e)}s(YS,"containsPath");var Dp={};H(Dp,{ConfigErrorV1:()=>Dp,DirectoryTypoError:()=>$C,FrontmatterError:()=>kc,InvalidError:()=>$r,JsonError:()=>Rp,RemoteAuthError:()=>Cp});var BC=c.StructWithRest(c.Struct({message:c.String,path:c.Array(c.String)}),[c.Record(c.String,c.Unknown)]),Rp=vt.create("ConfigJsonError",{path:c.String,message:c.optional(c.String)}),$r=vt.create("ConfigInvalidError",{path:c.String,issues:c.optional(c.Array(BC)),message:c.optional(c.String)}),kc=vt.create("ConfigFrontmatterError",{path:c.String,message:c.String}),$C=vt.create("ConfigDirectoryTypoError",{path:c.String,dir:c.String,suggestion:c.String}),Cp=vt.create("ConfigRemoteAuthError",{url:c.String,remote:c.String});var Fo={};H(Fo,{ConfigAgent:()=>Fo,load:()=>MP,loadAlchemy:()=>PP,loadMode:()=>NP});import ef from"path";import{readFile as OP}from"fs/promises";import XS from"path";function VC(e,t){let r=e.replaceAll("\\","/");for(let n of t)if(r.startsWith(n))return r.slice(n.length)}s(VC,"stripPrefix");function Sa(e,t){let r=VC(e,t)??XS.basename(e),n=XS.extname(r);return n.length?r.slice(0,-n.length):r}s(Sa,"configEntryNameFromPath");var Ca={};H(Ca,{ConfigMarkdown:()=>Ca,FILE_REGEX:()=>Ab,SHELL_REGEX:()=>kb,fallbackSanitization:()=>RP,files:()=>AP,parse:()=>Xs,parseText:()=>Qp,shell:()=>kP});var St={};H(St,{Filesystem:()=>St,contains:()=>dD,exists:()=>Mp,findUp:()=>pD,globUp:()=>mD,isDir:()=>XC,mimeType:()=>iD,normalizePath:()=>wa,normalizePathPattern:()=>aD,overlaps:()=>uD,readArrayBuffer:()=>nD,readBytes:()=>rD,readJson:()=>tD,readText:()=>eD,resolve:()=>lD,resolveFilePath:()=>cD,size:()=>QC,stat:()=>ow,statAsync:()=>ZC,up:()=>fD,windowsPath:()=>Np,write:()=>sw,writeJson:()=>oD,writeStream:()=>sD});import{chmod as HC,mkdir as QS,readFile as Cc,stat as WC,writeFile as Rc}from"fs/promises";import{createWriteStream as GC,existsSync as ew,statSync as tw}from"fs";import{realpathSync as rw}from"fs";import{dirname as xa,isAbsolute as JC,join as Op,resolve as nw,win32 as ZS}from"path";import{Readable as zC}from"stream";import{pipeline as KC}from"stream/promises";import{fileURLToPath as YC}from"url";async function Mp(e){return ew(e)}s(Mp,"exists");async function XC(e){try{return tw(e).isDirectory()}catch{return!1}}s(XC,"isDir");function ow(e){return tw(e,{throwIfNoEntry:!1})??void 0}s(ow,"stat");async function ZC(e){return WC(e).catch(t=>{if(!Pp(t))throw t})}s(ZC,"statAsync");async function QC(e){let t=ow(e)?.size??0;return typeof t=="bigint"?Number(t):t}s(QC,"size");async function eD(e){return Cc(e,"utf-8")}s(eD,"readText");async function tD(e){return JSON.parse(await Cc(e,"utf-8"))}s(tD,"readJson");async function rD(e){return Cc(e)}s(rD,"readBytes");async function nD(e){let t=await Cc(e);return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}s(nD,"readArrayBuffer");function Pp(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}s(Pp,"isEnoent");async function sw(e,t,r){Li.assert(e,"write");try{r?await Rc(e,t,{mode:r}):await Rc(e,t)}catch(n){if(Pp(n)){await QS(xa(e),{recursive:!0}),r?await Rc(e,t,{mode:r}):await Rc(e,t);return}throw n}}s(sw,"write");async function oD(e,t,r){return sw(e,JSON.stringify(t,null,2),r)}s(oD,"writeJson");async function sD(e,t,r){Li.assert(e,"write");let n=xa(e);ew(n)||await QS(n,{recursive:!0});let o=t instanceof ReadableStream?zC.fromWeb(t):t,i=GC(e);await KC(o,i),r&&await HC(e,r)}s(sD,"writeStream");async function iD(e){let{lookup:t}=await import("./mime-types-GSWEOYZ5.js");return t(e)||"application/octet-stream"}s(iD,"mimeType");function wa(e){if(process.platform!=="win32")return e;let t=ZS.normalize(ZS.resolve(Np(e)));try{return rw.native(t)}catch{return t}}s(wa,"normalizePath");function aD(e){if(process.platform!=="win32"||e==="*")return e;let t=e.match(/^(.*)[\\/]\*$/);if(!t)return wa(e);let r=/^[A-Za-z]:$/.test(t[1])?t[1]+"\\":t[1];return Op(wa(r),"*")}s(aD,"normalizePathPattern");function lD(e){let t=nw(Np(e));try{return wa(rw(t))}catch(r){if(Pp(r))return wa(t);throw r}}s(lD,"resolve");function cD(e,t){let r=t.startsWith("file://")?YC(t):t;return JC(r)?r:nw(e,r)}s(cD,"resolveFilePath");function Np(e){return process.platform!=="win32"?e:e.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(t,r)=>`${r.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:\/|$)/,(t,r)=>`${r.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,(t,r)=>`${r.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/,(t,r)=>`${r.toUpperCase()}:/`)}s(Np,"windowsPath");function uD(e,t){return Ie.overlaps(e,t)}s(uD,"overlaps");function dD(e,t){return Ie.contains(e,t)}s(dD,"contains");async function pD(e,t,r,n){let o=[t],i=t;for(;r!==i;){let d=xa(i);if(d===i)break;o.push(d),i=d}let a=Array.isArray(e)?e:[e],l=[];for(let d of n?.rootFirst?o.toReversed():o)for(let f of a){let m=Op(d,f);await Mp(m)&&l.push(m)}return l}s(pD,"findUp");async function*fD(e){let{targets:t,start:r,stop:n}=e,o=r;for(;;){for(let a of t){let l=Op(o,a);await Mp(l)&&(yield l)}if(n===o)break;let i=xa(o);if(i===o)break;o=i}}s(fD,"up");async function mD(e,t,r){let n=t,o=[];for(;;){try{let a=await Zr.scan(e,{cwd:n,absolute:!0,include:"file",dot:!0});o.push(...a)}catch{}if(r===n)break;let i=xa(n);if(i===n)break;n=i}return o}s(mD,"globUp");var Lo={};H(Lo,{ConfigMarkdown:()=>Lo,parse:()=>Tb,parseOption:()=>_P,sanitize:()=>_b});var Zp=wr(Ib(),1);function Tb(e){try{return(0,Zp.default)(e)}catch{return(0,Zp.default)(_b(e))}}s(Tb,"parse");function _P(e){try{return Tb(e)}catch{return}}s(_P,"parseOption");function _b(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return e;let r=t[1],n=r.split(/\r?\n/).flatMap(o=>{if(o.trim().startsWith("#")||o.trim()===""||/^\s+/.test(o))return[o];let i=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*(.*)$/);if(!i)return[o];let a=i[2].trim();return a===""||a===">"||a==="|"||a.startsWith('"')||a.startsWith("'")?[o]:a.includes(":")?[`${i[1]}: |-`,` ${a}`]:[o]});return e.replace(r,()=>n.join(`
706
+ `))}s(_b,"sanitize");var Ab=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,kb=/!`([^`]+)`/g;function AP(e){return Array.from(e.matchAll(Ab))}s(AP,"files");function kP(e){return Array.from(e.matchAll(kb))}s(kP,"shell");var RP=Lo.sanitize;async function Xs(e){let t=await St.readText(e);try{return Lo.parse(t)}catch(r){throw new kc({path:e,message:`${e}: Failed to parse YAML frontmatter: ${r instanceof Error?r.message:String(r)}`},{cause:r})}}s(Xs,"parse");function Qp(e,t){try{return Lo.parse(e)}catch(r){throw new kc({path:t,message:`${t}: Failed to parse YAML frontmatter: ${r instanceof Error?r.message:String(r)}`},{cause:r})}}s(Qp,"parseText");var rr={};H(rr,{ConfigParse:()=>rr,jsonc:()=>CP,schema:()=>DP});function CP(e,t){let r=[],n=iy(e,r,{allowTrailingComma:!0});if(r.length){let o=e.split(`
707
+ `),i=r.map(a=>{let l=e.substring(0,a.offset).split(`
708
+ `),d=l.length,f=l[l.length-1].length+1,m=o[d-1],g=`${ay(a.error)} at line ${d}, column ${f}`;return m?`${g}
709
+ Line ${d}: ${m}
710
+ ${"".padStart(f+9)}^`:g}).join(`
711
+ `);throw new Rp({path:t,message:`
712
+ --- JSONC Input ---
713
+ ${e}
714
+ --- Errors ---
715
+ ${i}
716
+ --- End ---`})}return n}s(CP,"jsonc");function DP(e,t,r){let n=c.decodeUnknownExit(e)(t,{errors:"all",onExcessProperty:"ignore",propertyOrder:"original"});if(bn.isSuccess(n))return n.value;let o=ss.squash(n.cause);throw new $r({path:r,issues:c.isSchemaError(o)?Tg.makeFormatterStandardSchemaV1()(o.issue).issues.map(i=>({...i,message:i.message,path:i.path?.map(String)??[]})):[{message:String(o),path:[]}]},{cause:o})}s(DP,"schema");async function MP(e){let t={};for(let r of await Zr.scan("{agent,agents}/**/*.md",{cwd:e,absolute:!0,dot:!0,symlink:!0})){let n=await Xs(r).catch(()=>{});if(!n)continue;let i={name:Sa(ef.relative(e,r),["agent/","agents/"]),...n.data,prompt:n.content.trim()};t[i.name]=rr.schema(kl.Info,i,r)}return t}s(MP,"load");async function PP(e,t){let r={},n=ef.join(e,".alchemy_lab","action-server.json"),o,i;for(let l=0;l<20&&!o;l++)try{let d=JSON.parse(await OP(n,"utf8"));d?.port&&(o=d.port),typeof d?.secret=="string"&&(i=d.secret)}catch{await new Promise(d=>setTimeout(d,500))}if(!o)return t("alchemy agents: no action-server.json; agents unavailable until config reload"),r;let a=[];try{let l=await fetch(`http://127.0.0.1:${o}/api/agents/markdown`,{signal:AbortSignal.timeout(8e3),headers:i?{"x-alchemy-local":i}:{}});if(!l.ok)throw new Error(`HTTP ${l.status}`);a=(await l.json()).data??[]}catch(l){return t("alchemy agents: fetch failed",{port:o,err:String(l)}),r}for(let l of a)try{let d=Qp(l.markdown,`alchemy agent ${l.name}`),f={name:l.name,...d.data,prompt:d.content.trim()};r[l.name]=rr.schema(kl.Info,f,`alchemy agent ${l.name}`)}catch(d){t("invalid alchemy agent",{agent:l.name,err:String(d)})}return r}s(PP,"loadAlchemy");async function NP(e){let t={};for(let r of await Zr.scan("{mode,modes}/*.md",{cwd:e,absolute:!0,dot:!0,symlink:!0})){let n=await Xs(r).catch(()=>{});if(!n)continue;let o={name:Sa(ef.relative(e,r),["mode/","modes/"]),...n.data,prompt:n.content.trim()},i=c.decodeUnknownExit(kl.Info)(o,{errors:"all",propertyOrder:"original"});bn.isSuccess(i)&&(t[o.name]={...i.value,mode:"primary"})}return t}s(NP,"loadMode");var Ma={};H(Ma,{AnthropicCompaction:()=>Ma,BETA:()=>rf,HEADER:()=>nf,IDENTITY:()=>Da,LOG:()=>Mb,METADATA_KEY:()=>Ob,THINKING_BETA:()=>Db,configure:()=>qP,cut:()=>VP,hasBlock:()=>qb,log:()=>of,newest:()=>Vc,newestStored:()=>eN,on:()=>sf,put:()=>GP,relocate:()=>XP,remember:()=>HP,restoreBlocks:()=>Bb,send:()=>YP,shape:()=>$b,stored:()=>Lb,storedOf:()=>Oa,supports:()=>Nb,supportsID:()=>af,take:()=>WP,validCut:()=>Ub,view:()=>QP,withSystem:()=>ZP});import{mkdirSync as LP,writeFileSync as FP}from"node:fs";import jP from"node:path";var rf="compact-2026-09-04",Db="thinking-binding-controls-2026-08-01",nf="x-alchemylab-anthropic-compaction",Ob="anthropicCompaction",Mb="anthcomp",Da="You are Claude Code, Anthropic's official CLI for Claude.",UP=new Set(["claude-fable-5-1","claude-mythos-5-1","claude-fable-5","claude-mythos-5","claude-mythos-preview","claude-opus-5-5","claude-opus-5","claude-opus-4-8","claude-opus-4-7","claude-opus-4-6","claude-sonnet-5-5","claude-sonnet-5","claude-sonnet-4-6","claude-haiku-5-5"]),Pb=!1;function qP(e){Pb=e.compaction?.anthropic===!0}s(qP,"configure");function sf(){return Ee.ALCHEMYLAB_ANTHROPIC_COMPACTION??Pb}s(sf,"on");function af(e){return typeof e!="string"?!1:UP.has(e.replace(/-\d{8}$/,""))}s(af,"supportsID");function Nb(e){return e.api.npm==="@ai-sdk/anthropic"&&af(e.api.id)}s(Nb,"supports");function of(e,t){try{process.stderr.write(`level=INFO service=session.anthropic-compaction message=${JSON.stringify(`${Mb} ${e}`)} ${JSON.stringify(t??{})}
717
+ `)}catch{}}s(of,"log");function Lb(e){if(!e||e.type!=="text")return;let t=e.metadata?.[Ob];if(!(!t||typeof t!="object"||t.block?.type!=="compaction")&&typeof t.block.content=="string")return t}s(Lb,"stored");function Oa(e){if(!(e.info.role!=="assistant"||!e.info.summary))for(let t of e.parts){let r=Lb(t);if(r&&t.type==="text")return{part:t,value:r}}}s(Oa,"storedOf");var Fb=s(e=>e.parts.some(t=>t.type==="tool"),"hasTools"),jb=s(e=>e.info.role==="user"&&e.parts.some(t=>t.type==="compaction"),"isCompactionUser");function tf(e){let t=e.info;return t.role!=="assistant"||t.summary||t.aside||t.error||!t.finish?!1:e.parts.some(r=>r.type==="text"||r.type==="reasoning"||r.type==="tool")}s(tf,"cleanStep");function Rb(e){return e.info.role!=="user"||jb(e)?!1:e.parts.some(t=>t.type==="text"&&!t.ignored&&t.text!==""||t.type==="file"&&t.mime!=="text/plain")}s(Rb,"realUser");function BP(e){if(!Fb(e))return!1;let t;for(let r of e.parts)(r.type==="text"||r.type==="reasoning"||r.type==="tool")&&(t=r);return!t||t.type!=="tool"?!1:e.parts.every(r=>r.type!=="tool"||r.state.status==="completed"||r.state.status==="error")}s(BP,"endsOnResults");function $P(e){if(Fb(e))return!1;let r=e.parts.filter(n=>n.type==="text"&&n.text!=="").at(-1);return!!r&&r.text===r.text.trimEnd()}s($P,"endsOnText");function Ub(e,t){if(t<=0||t>=e.length)return!1;let r=e[t],n=e[t-1];return Rb(r)?tf(n)&&$P(n):tf(r)?Rb(n)||tf(n)&&BP(n):!1}s(Ub,"validCut");function VP(e,t,r){if(r<=0||e.length<2)return;let n=e.filter(f=>f.info.role==="assistant"&&f.info.summary),o=Vc(n),i=o?e.indexOf(o)+2:1,a=e.flatMap((f,m)=>f.info.role==="user"&&!jb(f)?[m]:[]),l=Math.max(i,a.length>=2?a[a.length-2]:0,1),d=new Array(e.length+1).fill(0);for(let f=e.length-1;f>=0;f--)d[f]=d[f+1]+(t[f]??0);for(let f=l;f<e.length;f++)if(!(d[f]>r)&&Ub(e,f))return{index:f,id:e[f].info.id,tokens:d[f]}}s(VP,"cut");var Zs=new Map;function HP(e){for(Zs.delete(e.content),Zs.set(e.content,e);Zs.size>256;)Zs.delete(Zs.keys().next().value)}s(HP,"remember");function qb(e){let t=e.find(n=>n.role!=="system");if(!t||t.role!=="assistant"||!Array.isArray(t.content))return!1;let r=t.content[0];return r?.type==="text"&&r.providerOptions?.anthropic?.type==="compaction"}s(qb,"hasBlock");function Bb(e){let t=0,r=0;if(!Array.isArray(e?.messages))return{restored:t,missing:r};for(let o of e.messages)Array.isArray(o?.content)&&(o.content=o.content.map(i=>{if(i?.type!=="compaction"||i.signature!==void 0)return i;let a=Zs.get(i.content);return a?(t++,{...a,...i.cache_control?{cache_control:i.cache_control}:{}}):(r++,i)}));let n=e.messages[0];return n?.role==="assistant"&&Array.isArray(n.content)&&n.content[0]?.type==="compaction"&&n.content.length>1&&e.messages.splice(0,1,{role:"assistant",content:[n.content[0]]},{...n,content:n.content.slice(1)}),{restored:t,missing:r}}s(Bb,"restoreBlocks");var $c=new Map;function WP(e){let t=$c.get(e);return $c.delete(e),t}s(WP,"take");function GP(e,t){$c.set(e,t)}s(GP,"put");function Cb(e,t){for(let r of t.split(`
718
+ `)){if(!r.startsWith("data:"))continue;let n;try{n=JSON.parse(r.slice(5).trim())}catch{continue}n?.type==="message_start"&&(Array.isArray(n.message?.input_transformations)&&(e.inputTransformations=n.message.input_transformations),e.usage=n.message?.usage??e.usage),n?.type==="content_block_start"&&n.content_block?.type==="compaction"&&(e.block=n.content_block),n?.type==="message_delta"&&(e.stopReason=n.delta?.stop_reason??e.stopReason,n.usage&&(e.usage={...e.usage,...n.usage})),n?.type==="error"&&(e.error=JSON.stringify(n.error??n).slice(0,1e3))}}s(Cb,"readEvent");function JP(e,t){let r={status:e.status};if($c.set(t,r),!e.ok)return e.clone().text().then(a=>r.error=a.slice(0,2e3)).catch(()=>{}),e;if(!e.body)return e;if(!(e.headers.get("content-type")??"").includes("event-stream"))return e.clone().json().then(a=>{r.block=(a?.content??[]).find(l=>l?.type==="compaction"),r.stopReason=a?.stop_reason,r.usage=a?.usage,r.inputTransformations=a?.input_transformations}).catch(()=>{}),e;let n=new TextDecoder,o="",i=new TransformStream({transform(a,l){o+=n.decode(a,{stream:!0});let d;for(;(d=o.indexOf(`
719
+
720
+ `))!==-1;)Cb(r,o.slice(0,d)),o=o.slice(d+2);l.enqueue(a)},flush(){o&&Cb(r,o)}});return new Response(e.body.pipeThrough(i),{status:e.status,statusText:e.statusText,headers:e.headers})}s(JP,"capture");function zP(e){let t={};if(!e)return t;if(e instanceof Headers)e.forEach((r,n)=>t[n]=r);else if(Array.isArray(e))for(let[r,n]of e)t[String(r)]=String(n);else for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=String(n));return t}s(zP,"headerRecord");function $b(e){let t=s(o=>Array.isArray(o)?o.map(i=>i?.type+(i?.type==="compaction"&&i.signature?"+sig":"")).join(","):"text","kinds"),r=Array.isArray(e?.system)?e.system.length:e?.system?1:0,n=(e?.messages??[]).map(o=>`${o.role}[${t(o.content)}]`);return`system:${r} `+n.join(" ")}s($b,"shape");function KP(e,t){let r=process.env.ALCHEMYLAB_ANTHROPIC_COMPACTION_DUMP;if(r)try{LP(r,{recursive:!0}),FP(jP.join(r,`${Date.now()}-${Math.random().toString(36).slice(2,6)}-${e}.json`),JSON.stringify(t,null,1))}catch{}}s(KP,"dump");async function YP(e,t,r){if(!sf()||typeof r?.body!="string"||r?.method!=="POST")return e(t,r);let n;try{n=JSON.parse(r.body)}catch{return e(t,r)}if(!af(n?.model)||!Array.isArray(n?.messages))return e(t,r);let o=zP(r.headers),i=o[nf];delete o[nf];let a=Object.keys(o).find(y=>y.toLowerCase()==="anthropic-beta")??"anthropic-beta",l=new Set((o[a]??"").split(",").map(y=>y.trim()).filter(Boolean)),{restored:d,missing:f}=Bb(n);(d||f)&&l.add(rf),i&&(n.compaction={type:"summarize"},l.add(rf),delete n.stop_sequences,delete n.context_management,n.tool_choice&&(n.tool_choice.type==="any"||n.tool_choice.type==="tool")&&delete n.tool_choice,n.output_config&&(delete n.output_config.format,delete n.output_config.task_budget));let m=n.thinking;m&&(m.type==="adaptive"||m.type==="enabled")&&(m.block_binding||(m.block_binding={prefix_mismatch_behavior:"drop_block"}),l.add(Db)),o[a]=[...l].join(","),of(i?"compaction request":"request",{model:n.model,shape:$b(n),restored:d,missing:f,thinking:n.thinking}),f&&of("block without its signature",{missing:f});let g={...r,body:JSON.stringify(n),headers:o};KP(i?"compaction-request":"request",n);let h=await e(t,g);return i?JP(h,i):h}s(YP,"send");function XP(e){if(!qb(e.messages))return;let t=[],r=[];for(let d of e.system)if(d===Da)t.push(d);else if(d.startsWith(Da)){t.push(Da);let f=d.slice(Da.length).replace(/^\n+/,"");f&&r.push(f)}else d&&r.push(d);if(t.length===0)return;let n=r.join(`
721
+
722
+ `),o=e.messages.findLast(d=>d.role==="system"),i=o&&typeof o.content=="string"?o.content:void 0;if(!n||n===i||e.append===!1)return{system:t,messages:e.messages};let a=e.messages.length;for(;a>0&&e.messages[a-1].role==="assistant";)a--;let l=[...e.messages.slice(0,a),{role:"system",content:n},...e.messages.slice(a)];return{system:t,messages:l,added:n}}s(XP,"relocate");function ZP(e,t){return{...e,system:[...e.system??[],t]}}s(ZP,"withSystem");function QP(e,t){if(!sf()||!Nb(t))return;let r={blocks:new Map,drop:new Set,skip:new Set,after:new Map},n=e.filter(i=>i.info.role!=="assistant"||!i.info.summary||!i.info.finish||i.info.error||i.info.providerID!==t.providerID||i.info.modelID!==t.id?!1:!!Oa(i)),o=Vc(n);if(o){for(let i of n){let a=Oa(i);i===o?r.blocks.set(i.info.id,a.value.block):r.drop.add(i.info.id),i.info.role==="assistant"&&r.skip.add(i.info.parentID);for(let l of a.value.system??[])r.after.set(l.after,[...r.after.get(l.after)??[],l.text])}return r}}s(QP,"view");function Vc(e){let t;for(let r of e)t?(r.info.time.created>t.info.time.created||r.info.time.created===t.info.time.created&&r.info.id>t.info.id)&&(t=r):t=r;return t}s(Vc,"newest");function eN(e){let t=Vc(e.filter(r=>!!Oa(r)));return t?Oa(t):void 0}s(eN,"newestStored");var Pa={};H(Pa,{ConfigCommand:()=>Pa,load:()=>nN});import tN from"path";var rN=c.decodeUnknownExit(dy.Info);async function nN(e){let t={};for(let r of await Zr.scan("{command,commands}/**/*.md",{cwd:e,absolute:!0,dot:!0,symlink:!0})){let n=await Xs(r).catch(()=>{});if(!n)continue;let i={name:Sa(tN.relative(e,r),["command/","commands/"]),...n.data,template:n.content.trim()},a=rN(i,{errors:"all",propertyOrder:"original"});if(bn.isSuccess(a)){t[i.name]=a.value;continue}throw new $r({path:r,message:ss.pretty(a.cause)},{cause:ss.squash(a.cause)})}return t}s(nN,"load");var Qs={};H(Qs,{ConfigManaged:()=>Qs,managedConfigDir:()=>uN,parseManagedPlist:()=>zb,readManagedPreferences:()=>dN});import{existsSync as iN}from"fs";import aN from"os";import cf from"path";var Na={};H(Na,{Process:()=>Na,RunFailedError:()=>Hc,lines:()=>sN,run:()=>lf,spawn:()=>Wb,stop:()=>oN,text:()=>Gb});var Hb=wr(rA());import{buffer as Vb}from"node:stream/consumers";var Hc=class extends Error{static{s(this,"RunFailedError")}cmd;code;stdout;stderr;constructor(t,r,n,o){let i=o.toString().trim();super(i?`Command failed with code ${r}: ${t.join(" ")}
723
+ ${i}`:`Command failed with code ${r}: ${t.join(" ")}`),this.name="ProcessRunFailedError",this.cmd=[...t],this.code=r,this.stdout=n,this.stderr=o}};function Wb(e,t={}){if(e.length===0)throw new Error("Command is required");t.abort?.throwIfAborted();let r=(0,Hb.default)(e[0],e.slice(1),{cwd:t.cwd,shell:t.shell,env:t.env===null?{}:t.env?{...process.env,...t.env}:void 0,stdio:[t.stdin??"ignore",t.stdout??"ignore",t.stderr??"ignore"],windowsHide:process.platform==="win32"}),n=!1,o,i=s(()=>{if(n||r.exitCode!==null||r.signalCode!==null)return;n=!0,r.kill(t.kill??"SIGTERM");let d=t.timeout??5e3;d<=0||(o=setTimeout(()=>r.kill("SIGKILL"),d))},"abort"),a=new Promise((d,f)=>{let m=s(()=>{t.abort?.removeEventListener("abort",i),o&&clearTimeout(o)},"done");r.once("exit",(g,h)=>{m(),d(g??(h?1:0))}),r.once("error",g=>{m(),f(g)})});a.catch(()=>{}),t.abort&&(t.abort.addEventListener("abort",i,{once:!0}),t.abort.aborted&&i());let l=r;return l.exited=a,l}s(Wb,"spawn");async function lf(e,t={}){let r=Wb(e,{cwd:t.cwd,env:t.env,stdin:t.stdin,shell:t.shell,abort:t.abort,kill:t.kill,timeout:t.timeout,stdout:"pipe",stderr:"pipe"});if(!r.stdout||!r.stderr)throw new Error("Process output not available");let n=await Promise.all([r.exited,Vb(r.stdout),Vb(r.stderr)]).then(([o,i,a])=>({code:o,stdout:i,stderr:a})).catch(o=>{if(!t.nothrow)throw o;return{code:1,stdout:Buffer.alloc(0),stderr:Buffer.from(va(o))}});if(n.code===0||t.nothrow)return n;throw new Hc(e,n.code,n.stdout,n.stderr)}s(lf,"run");async function oN(e){if(e.exitCode!==null||e.signalCode!==null)return;if(process.platform!=="win32"||!e.pid){e.kill();return}(await lf(["taskkill","/pid",String(e.pid),"/T","/F"],{nothrow:!0})).code!==0&&e.kill()}s(oN,"stop");async function Gb(e,t={}){let r=await lf(e,t);return{...r,text:r.stdout.toString()}}s(Gb,"text");async function sN(e,t={}){return(await Gb(e,t)).text.split(/\r?\n/).filter(Boolean)}s(sN,"lines");var Jb="ai.opencode.managed",lN=new Set(["PayloadDisplayName","PayloadIdentifier","PayloadType","PayloadUUID","PayloadVersion","_manualProfile"]);function cN(){switch(process.platform){case"darwin":return"/Library/Application Support/opencode";case"win32":return cf.join(process.env.ProgramData||"C:\\ProgramData","opencode");default:return"/etc/opencode"}}s(cN,"systemManagedConfigDir");function uN(){return process.env.OPENCODE_TEST_MANAGED_CONFIG_DIR||cN()}s(uN,"managedConfigDir");function zb(e){let t=JSON.parse(e);for(let r of Object.keys(t))lN.has(r)&&delete t[r];return JSON.stringify(t)}s(zb,"parseManagedPlist");async function dN(){if(process.platform!=="darwin")return;let e=(()=>{try{return aN.userInfo().username||"user"}catch{return"user"}})(),t=[cf.join("/Library/Managed Preferences",e,`${Jb}.plist`),cf.join("/Library/Managed Preferences",`${Jb}.plist`)];for(let r of t){if(!iN(r))continue;let n=await Na.run(["plutil","-convert","json","-o","-",r],{nothrow:!0});if(n.code===0)return{source:`mobileconfig:${r}`,text:zb(n.stdout.toString())}}}s(dN,"readManagedPreferences");var ei={};H(ei,{ConfigPaths:()=>ei,directories:()=>fN,fileInDirectory:()=>mN,files:()=>pN});import Kb from"path";var pN=$u("ConfigPaths.projectFiles")(function*(e,t,r){return(yield*(yield*Ie.Service).up({targets:[`${e}.jsonc`,`${e}.json`],start:t,stop:r})).toReversed()}),fN=$u("ConfigPaths.directories")(function*(e,t){let r=yield*Ie.Service;return Tp([Fe.Path.config,...Ee.OPENCODE_DISABLE_PROJECT_CONFIG?[]:yield*r.up({targets:[".opencode"],start:e,stop:t}),...yield*r.up({targets:[".opencode"],start:Fe.Path.home,stop:Fe.Path.home}),...Ee.OPENCODE_CONFIG_DIR?[Ee.OPENCODE_CONFIG_DIR]:[]])});function mN(e,t){return[Kb.join(e,`${t}.json`),Kb.join(e,`${t}.jsonc`)]}s(mN,"fileInDirectory");var jo={};H(jo,{ConfigPlugin:()=>jo,deduplicatePluginOrigins:()=>RN,load:()=>_N,pluginOptions:()=>AN,pluginSpecifier:()=>mf,resolvePluginSpec:()=>kN});import{pathToFileURL as ff}from"url";var Xb=wr(py()),Wc=wr(PA());import Hr from"path";import{fileURLToPath as Gc,pathToFileURL as ti}from"url";var gN=["opencode-openai-codex-auth","opencode-copilot-auth"];function pK(e){return gN.some(t=>e.includes(t))}s(pK,"isDeprecatedPlugin");function Zb(e){try{return(0,Xb.default)(e)}catch{}}s(Zb,"parse");function Qb(e){let t=Zb(e);if(t?.type==="alias"&&!t.name){let r=t.subSpec;if(r?.name){let n=!r.rawSpec||r.rawSpec==="*"?"latest":r.rawSpec;return{pkg:r.name,version:n}}}return t?.name?t.raw===t.name?{pkg:t.name,version:"latest"}:{pkg:t.name,version:t.rawSpec}:{pkg:e,version:""}}s(Qb,"parsePluginSpecifier");var hN=["index.ts","index.tsx","index.js","index.mjs","index.cjs"];function eE(e){return Jc(e)?"file":"npm"}s(eE,"pluginSource");function yN(e,t){return e.startsWith("file://")?Gc(e):Hr.isAbsolute(e)?e:Hr.resolve(t,e)}s(yN,"resolveExportPath");function vN(e){return Hr.isAbsolute(e)||/^[A-Za-z]:[\\/]/.test(e)}s(vN,"isAbsolutePath");function SN(e){if(typeof e=="string")return e;if(He(e))for(let t of["import","default"]){let r=e[t];if(typeof r=="string")return r}}s(SN,"extractExportValue");function wN(e){let t=e.json.main;if(typeof t!="string")return;let r=t.trim();if(r)return r}s(wN,"packageMain");function xN(e,t,r,n){let o=yN(t,n.dir),i=St.resolve(n.dir),a=St.resolve(o);if(!St.contains(i,a))throw new Error(`Plugin ${e} resolved ${r} entry outside plugin directory`);return a}s(xN,"resolvePackageFile");function Yb(e,t,r,n){return ti(xN(e,t,r,n)).href}s(Yb,"resolvePackagePath");function bN(e,t,r){let n=r.json.exports;if(He(n)){let i=SN(n[`./${t}`]);if(i)return Yb(e,i,t,r)}if(t!=="server")return;let o=wN(r);if(o)return Yb(e,o,t,r)}s(bN,"resolvePackageEntrypoint");function EN(e){if(e.startsWith("file://"))return Gc(e);if(Hr.isAbsolute(e))return e}s(EN,"targetPath");async function uf(e){for(let t of hN){let r=Hr.join(e,t);if(await St.exists(r))return r}}s(uf,"resolveDirectoryIndex");async function IN(e){let t=EN(e);if(!(!t||!(await St.statAsync(t))?.isDirectory()))return t}s(IN,"resolveTargetDirectory");async function TN(e,t,r,n){let o=eE(e),i=n??(o==="npm"?await ri(t):await ri(t).catch(()=>{}));if(!i)return t;let a=bN(e,r,i);if(a)return a;let l=await IN(t);if(r==="tui"){if(o==="file"&&l){let d=await uf(l);if(d)return ti(d).href}return o==="npm"||l?void 0:t}if(l&&He(i.json.exports)){if(o==="file"){let d=await uf(l);if(d)return ti(d).href}return}return t}s(TN,"resolvePluginEntrypoint");function Jc(e){return e.startsWith("file://")||e.startsWith(".")||vN(e)}s(Jc,"isPathPluginSpec");async function df(e){let t=e.startsWith("file://")?Gc(e):e,r=Hr.isAbsolute(t)||/^[A-Za-z]:[\\/]/.test(t)?t:Hr.resolve(t);if(!(await St.statAsync(r))?.isDirectory())return e.startsWith("file://")?e:ti(r).href;if(await St.exists(Hr.join(r,"package.json")))return ti(r).href;let o=await uf(r);if(o)return ti(o).href;throw new Error(`Plugin directory ${r} is missing package.json or index file`)}s(df,"resolvePathPluginTarget");async function fK(e,t,r){if(!Wc.default.valid(t)||Wc.default.major(t)===0)return;let n=r??await ri(e).catch(()=>{});if(!n)return;let o=n.json.engines;if(!He(o))return;let i=o.opencode;if(typeof i=="string"&&!Wc.default.satisfies(t,i))throw new Error(`Plugin requires opencode ${i} but running ${t}`)}s(fK,"checkPluginCompatibility");async function mK(e){if(Jc(e))return df(e);let t=Zb(e),r=t?.name&&t.raw===t.name?`${t.name}@latest`:e;return(await $n.add(r)).directory}s(mK,"resolvePluginTarget");async function ri(e){let t=e.startsWith("file://")?Gc(e):e,n=(await St.statAsync(t))?.isDirectory()?t:Hr.dirname(t),o=Hr.join(n,"package.json"),i=await St.readJson(o);return{dir:n,pkg:o,json:i}}s(ri,"readPluginPackage");async function gK(e,t,r){let n=eE(e),o=n==="npm"?await ri(t):await ri(t).catch(()=>{}),i=await TN(e,t,r,o);return{spec:e,source:n,target:t,pkg:o,entry:i}}s(gK,"createPluginEntry");function hK(e,t){if(e===void 0)return;if(typeof e!="string")throw new TypeError(`Plugin ${t} has invalid id type ${typeof e}`);let r=e.trim();if(!r)throw new TypeError(`Plugin ${t} has an empty id`);return r}s(hK,"readPluginId");function yK(e,t,r,n="strict"){let o=e.default;if(!He(o)){if(n==="detect")return;throw new TypeError(`Plugin ${t} must default export an object with ${r}()`)}if(n==="detect"&&!("id"in o)&&!("server"in o)&&!("tui"in o))return;let i="server"in o?o.server:void 0,a="tui"in o?o.tui:void 0;if(i!==void 0&&typeof i!="function")throw new TypeError(`Plugin ${t} has invalid server export`);if(a!==void 0&&typeof a!="function")throw new TypeError(`Plugin ${t} has invalid tui export`);if(i!==void 0&&a!==void 0)throw new TypeError(`Plugin ${t} must default export either server() or tui(), not both`);if(r==="server"&&i===void 0)throw new TypeError(`Plugin ${t} must default export an object with server()`);if(r==="tui"&&a===void 0)throw new TypeError(`Plugin ${t} must default export an object with tui()`);return o}s(yK,"readV1Plugin");async function vK(e,t,r,n,o){if(e==="file"){if(n)return n;throw new TypeError(`Path plugin ${t} must export id`)}if(n)return n;let i=o??await ri(r);if(typeof i.json.name!="string"||!i.json.name.trim())throw new TypeError(`Plugin package ${i.pkg} is missing name`);return i.json.name.trim()}s(vK,"resolvePluginId");import pf from"path";async function _N(e){let t=[];for(let r of await Zr.scan("{plugin,plugins}/*.{ts,js}",{cwd:e,absolute:!0,dot:!0,symlink:!0}))t.push(ff(r).href);return t}s(_N,"load");function mf(e){return Array.isArray(e)?e[0]:e}s(mf,"pluginSpecifier");function AN(e){return Array.isArray(e)?e[1]:void 0}s(AN,"pluginOptions");async function kN(e,t){let r=mf(e);if(!Jc(r))return e;let n=pf.dirname(t),o=r.startsWith("file://")?r:pf.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r)?ff(r).href:ff(pf.resolve(n,r)).href,i=await df(o).catch(()=>o);return Array.isArray(e)?[i,e[1]]:i}s(kN,"resolvePluginSpec");function RN(e){let t=new Set,r=[];for(let n of e.toReversed()){let o=mf(n.spec),i=o.startsWith("file://")?o:Qb(o).pkg;t.has(i)||(t.add(i),r.push(n))}return r.toReversed()}s(RN,"deduplicatePluginOrigins");var Uo={};H(Uo,{ConfigVariable:()=>Uo,substitute:()=>MN});import zc from"path";import CN from"os";function DN(e){return e.type==="path"?e.path:e.source}s(DN,"source");function ON(e){return e.type==="path"?zc.dirname(e.path):e.dir}s(ON,"dir");async function MN(e){let t=e.missing??"error",r=e.text.replace(/\{env:([^}]+)\}/g,(d,f)=>(e.env?.[f]??process.env[f])||""),n=Array.from(r.matchAll(/\{file:[^}]+\}/g));if(!n.length)return r;let o=ON(e),i=DN(e),a="",l=0;for(let d of n){let f=d[0],m=d.index;a+=r.slice(l,m);let g=r.lastIndexOf(`
724
+ `,m-1)+1;if(r.slice(g,m).trimStart().startsWith("//")){a+=f,l=m+f.length;continue}let y=f.replace(/^\{file:/,"").replace(/\}$/,"");y.startsWith("~/")&&(y=zc.join(CN.homedir(),y.slice(2)));let E=zc.isAbsolute(y)?y:zc.resolve(o,y),w=(await St.readText(E).catch(v=>{if(t==="empty")return"";let O=`bad file reference: "${f}"`;throw v.code==="ENOENT"?new $r({path:i,message:O+` ${E} does not exist`},{cause:v}):new $r({path:i,message:O},{cause:v})})).trim();a+=JSON.stringify(w).slice(1,-1),l=m+f.length}return a+=r.slice(l),a}s(MN,"substitute");var ni={};H(ni,{ConfigV2Compat:()=>ni,lower:()=>qN});import{isDeepStrictEqual as hf}from"node:util";var Fa={errors:"all",onExcessProperty:"ignore",propertyOrder:"original"},Kc=c.Record(c.String,c.Unknown),gf=c.Struct({startup:c.optional(Yr),catalog:c.optional(Yr),execution:c.optional(Yr)}),PN=c.Struct({client_id:c.optional(c.String),client_secret:c.optional(c.String),scope:c.optional(c.String),callback_port:c.optional(c.Int.check(c.isBetween({minimum:1,maximum:65535}))),redirect_uri:c.optional(c.String)}),NN=c.Union([c.Struct({type:c.Literal("local"),command:c.Array(c.String),cwd:c.optional(c.String),environment:c.optional(c.Record(c.String,c.String)),disabled:c.optional(c.Boolean),codemode:c.optional(c.Boolean),timeout:c.optional(gf)}),c.Struct({type:c.Literal("remote"),url:c.String,headers:c.optional(c.Record(c.String,c.String)),oauth:c.optional(c.Union([PN,c.Literal(!1)])),disabled:c.optional(c.Boolean),codemode:c.optional(c.Boolean),timeout:c.optional(gf)})]),yf=c.Union([c.String.check(c.isPattern(/^[^/#]+\/[^#]+(?:#[^#]+)?$/)),c.Struct({providerID:c.String.check(c.isPattern(/^[^/#]+$/)),model:c.String.check(c.isPattern(/^[^#]+$/)),variant:c.optional(c.String.check(c.isPattern(/^[^#]+$/)))})]),LN=c.Struct({model:c.optional(yf),request:c.optional(c.Struct({headers:c.optional(c.Record(c.String,c.String)),body:c.optional(c.Record(c.String,c.Json))})),system:c.optional(c.String),description:c.optional(c.String),mode:c.optional(c.Literals(["subagent","primary","all"])),hidden:c.optional(c.Boolean),color:c.optional(c.String.check(c.isPattern(/^#[0-9a-fA-F]{6}$/))),steps:c.optional(Yr),disabled:c.optional(c.Boolean)}),FN=c.Struct({template:c.String,description:c.optional(c.String),agent:c.optional(c.String),model:c.optional(yf),subtask:c.optional(c.Boolean)}),Tt=c.decodeUnknownOption(Kc,Fa),jN=c.decodeUnknownOption(ad.Entry,Fa),UN=new Set(ad.builtinServerIds);function qN(e,t="configuration"){let r=Tt(e);if(P.isNone(r))return{value:e,diagnostics:[]};let n=[...Object.hasOwn(r.value,"permissions")?[["permissions"]]:[],...["agents","agent","mode"].flatMap(a=>{let l=Tt(r.value[a]);return P.isNone(l)?[]:Object.entries(l.value).flatMap(([d,f])=>{let m=Tt(f);return P.isSome(m)&&Object.hasOwn(m.value,"permissions")?[[a,d,"permissions"]]:[]})})];if(n.length)throw new $r({path:t,issues:n.map(a=>({path:a,message:'V2 permissions are not supported by OpenCode V1. Use V1 "permission" rules or run opencode2.'}))});let o={...r.value},i=[];for(let a of["plugins","providers","websearch","warming"])Object.hasOwn(r.value,a)&&Wn([a],i);return BN(r.value,o,i),$N(r.value,o,i),VN(r.value,o,i),HN(r.value,o,i),WN(r.value,o,i),GN(r.value,o,i),JN(r.value,o,i),zN(r.value,o,i),KN(r.value,o,i),{value:o,diagnostics:i}}s(qN,"lower");function BN(e,t,r){if(Object.hasOwn(e,"snapshots")){let n=gr(c.Boolean,e.snapshots,["snapshots"],r);n!==void 0&&qo(t,"snapshot",n,["snapshots"],r)}if(Object.hasOwn(e,"media")){let n=gr(uy.Info,e.media,["media"],r);n!==void 0&&qo(t,"attachment",n,["media"],r)}}s(BN,"normalizeSettings");function $N(e,t,r){if(!Object.hasOwn(e,"model"))return;let n=c.decodeUnknownOption(yf,Fa)(e.model);if(P.isNone(n))return;let o=vf(n.value);t.model=o.model,o.variant!==void 0&&Wn(["model","variant"],r)}s($N,"normalizeModel");function VN(e,t,r){if(!Array.isArray(e.skills))return;let n=gr(c.Array(c.String),e.skills,["skills"],r);n!==void 0&&(t.skills={paths:n.filter(o=>!/^https?:\/\//i.test(o)),urls:n.filter(o=>/^https?:\/\//i.test(o))})}s(VN,"normalizeSkills");function HN(e,t,r){let n=Tt(e.compaction);if(P.isNone(n))return;let o={...n.value};if(Object.hasOwn(o,"keep")){let i=gr(Kc,o.keep,["compaction","keep"],r);if(i!==void 0&&Object.hasOwn(i,"tokens")){let a=gr(zt,i.tokens,["compaction","keep","tokens"],r);a!==void 0&&qo(o,"preserve_recent_tokens",a,["compaction","keep","tokens"],r)}}if(Object.hasOwn(o,"buffer")){let i=gr(zt,o.buffer,["compaction","buffer"],r);i!==void 0&&qo(o,"reserved",i,["compaction","buffer"],r)}t.compaction=o}s(HN,"normalizeCompaction");function WN(e,t,r){let n=Tt(e.experimental);if(P.isNone(n)||(Object.hasOwn(n.value,"portable_shell_scanner")&&Wn(["experimental","portable_shell_scanner"],r),!Object.hasOwn(n.value,"subagent_depth")))return;let o=gr(zt,n.value.subagent_depth,["experimental","subagent_depth"],r);o!==void 0&&qo(t,"subagent_depth",o,["experimental","subagent_depth"],r)}s(WN,"normalizeExperimental");function GN(e,t,r){if(!Object.hasOwn(e,"agents"))return;let n=gr(Kc,e.agents,["agents"],r);if(n===void 0)return;let o=Tt(t.agent),i=P.isSome(o)?{...o.value}:{};for(let[a,l]of Object.entries(n)){let d=["agents",a];if(Object.hasOwn(i,a)){hf(i[a],l)||Yc(d,r);continue}let f=gr(LN,l,d,r);f!==void 0&&(f.request?.headers!==void 0&&Wn([...d,"request","headers"],r),La(i,a,YN(f)))}Object.hasOwn(t,"agent")&&P.isNone(o)||(Object.keys(i).length>0||P.isSome(o))&&(t.agent=i)}s(GN,"normalizeAgents");function JN(e,t,r){if(!Object.hasOwn(e,"commands"))return;let n=gr(Kc,e.commands,["commands"],r);if(n===void 0)return;let o=Tt(t.command);if(Object.hasOwn(t,"command")&&P.isNone(o))return;let i=P.isSome(o)?{...o.value}:{};for(let[a,l]of Object.entries(n)){let d=["commands",a],f=gr(FN,l,d,r);f!==void 0&&qo(i,a,XN(f),d,r)}(Object.keys(i).length>0||P.isSome(o))&&(t.command=i)}s(JN,"normalizeCommands");function zN(e,t,r){let n=Tt(e.mcp);if(P.isNone(n))return;let o={},i=Tt(n.value.servers),a=P.isSome(i)&&!tE(i.value),l=Tt(n.value.timeout),d=c.decodeUnknownOption(gf,Fa)(n.value.timeout),f=P.isSome(d)&&P.isSome(l)&&!tE(l.value)&&(Object.keys(l.value).length===0||["startup","catalog","execution"].some(y=>Object.hasOwn(l.value,y)));for(let[y,E]of Object.entries(n.value)){if(y==="servers"&&a||y==="timeout"&&f)continue;let w=["mcp",y],v=Tt(E),O=P.isSome(v)?Tt(v.value.oauth):P.none(),k=P.isSome(v)&&(Object.hasOwn(v.value,"disabled")||Object.hasOwn(v.value,"codemode")||typeof v.value.timeout=="object"||P.isSome(O)&&["client_id","client_secret","callback_port","redirect_uri"].some(S=>Object.hasOwn(O.value,S)));La(o,y,k?rE(E,w,r)??E:E)}if(a&&P.isSome(i))for(let[y,E]of Object.entries(i.value)){let w=["mcp","servers",y];if(Object.hasOwn(o,y)){hf(o[y],E)||Yc(w,r);continue}let v=Tt(E);if(P.isSome(v)&&typeof v.value.enabled=="boolean"&&!Object.hasOwn(v.value,"disabled")){La(o,y,E);continue}let O=rE(E,w,r);O!==void 0&&La(o,y,O)}if(t.mcp=o,!f||P.isNone(d))return;let m=Sf(d.value);if(m===void 0){Object.keys(d.value).length&&Wn(["mcp","timeout"],r);return}let g=Tt(t.experimental);if(Object.hasOwn(t,"experimental")&&P.isNone(g))return;let h=P.isSome(g)?{...g.value}:{};qo(h,"mcp_timeout",m,["mcp","timeout"],r),t.experimental=h}s(zN,"normalizeMcp");function tE(e){return["type","enabled"].some(t=>Object.hasOwn(e,t)&&(e[t]===null||typeof e[t]!="object"||Array.isArray(e[t])))}s(tE,"isDirectServer");function rE(e,t,r){let n=gr(NN,e,t,r);if(n===void 0)return;n.codemode!==void 0&&Wn([...t,"codemode"],r),n.timeout&&Sf(n.timeout)===void 0&&Object.keys(n.timeout).length&&Wn([...t,"timeout"],r);let o=Tt(e);return P.isNone(o)||!Object.hasOwn(o.value,"enabled")?nE(n):(n.disabled!==void 0&&o.value.enabled===n.disabled&&Yc([...t,"disabled"],r),{...nE(n),enabled:o.value.enabled})}s(rE,"normalizeServer");function KN(e,t,r){let n=Tt(e.lsp);P.isNone(n)||(t.lsp=Object.fromEntries(Object.entries(n.value).filter(([o,i])=>{if(UN.has(o))return!0;let a=jN(i);return P.isNone(a)||a.value.disabled===!0||"extensions"in a.value&&a.value.extensions!==void 0?!0:(Wn(["lsp",o],r),!1)})))}s(KN,"normalizeLsp");function vf(e){if(typeof e!="string")return{model:`${e.providerID}/${e.model}`,...e.variant!==void 0?{variant:e.variant}:{}};let t=e.indexOf("#");return t===-1?{model:e}:{model:e.slice(0,t),variant:e.slice(t+1)}}s(vf,"lowerSelection");function Sf(e){if(e.startup===void 0&&!(e.catalog===void 0||e.execution===void 0)&&e.catalog===e.execution)return e.catalog}s(Sf,"lowerTimeout");function nE(e){let t={...e,enabled:e.disabled!==!0};if(delete t.disabled,delete t.codemode,delete t.timeout,e.timeout){let r=Sf(e.timeout);r!==void 0&&(t.timeout=r)}if(e.type==="remote"&&e.oauth&&typeof e.oauth=="object"){let r={};e.oauth.client_id!==void 0&&(r.clientId=e.oauth.client_id),e.oauth.client_secret!==void 0&&(r.clientSecret=e.oauth.client_secret),e.oauth.scope!==void 0&&(r.scope=e.oauth.scope),e.oauth.callback_port!==void 0&&(r.callbackPort=e.oauth.callback_port),e.oauth.redirect_uri!==void 0&&(r.redirectUri=e.oauth.redirect_uri),t.oauth=r}return t}s(nE,"lowerServer");function YN(e){let t={};for(let r of["description","mode","hidden","color","steps"])e[r]!==void 0&&(t[r]=e[r]);return e.system!==void 0&&(t.prompt=e.system),e.disabled!==void 0&&(t.disable=e.disabled),e.model!==void 0&&Object.assign(t,vf(e.model)),e.request?.body!==void 0&&(t.options=e.request.body),t}s(YN,"lowerAgent");function XN(e){return{...e,...e.model!==void 0?vf(e.model):{}}}s(XN,"lowerCommand");function gr(e,t,r,n){let o=c.decodeUnknownOption(e,Fa)(t);if(P.isSome(o))return o.value;n.push({kind:"invalid",path:r,message:"Native setting could not be lowered because it is malformed"})}s(gr,"decodeValue");function qo(e,t,r,n,o){if(Object.hasOwn(e,t)){hf(e[t],r)||Yc(n,o);return}La(e,t,r)}s(qo,"preferLegacy");function La(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0})}s(La,"setOwn");function Wn(e,t){t.push({kind:"unsupported",path:e,message:"Omitted native setting that cannot be represented in V1"})}s(Wn,"unsupported");function Yc(e,t){t.push({kind:"conflict",path:e,message:"Retained legacy value over native value"})}s(Yc,"conflict");function oi(e,t){return mr(e,t)}s(oi,"mergeConfig");function sE(e,t){let r=oi(e,t);return e.instructions&&t.instructions&&(r.instructions=Array.from(new Set([...e.instructions,...t.instructions]))),r}s(sE,"mergeConfigConcatArrays");function iE(e){if(!He(e))return e;let t={...e};return("theme"in t||"keybinds"in t||"tui"in t)&&(delete t.theme,delete t.keybinds,delete t.tui),t}s(iE,"normalizeLoadedConfig");async function eL(e){if(!He(e.value)||typeof e.value.url!="string")return;let t=await Uo.substitute({text:e.value.url,type:"virtual",dir:e.dir,source:e.source,env:e.env}),r=He(e.value.headers)?Object.fromEntries(await Promise.all(Object.entries(e.value.headers).filter(n=>typeof n[1]=="string").map(async([n,o])=>[n,await Uo.substitute({text:o,type:"virtual",dir:e.dir,source:e.source,env:e.env})]))):void 0;return{url:t,headers:r}}s(eL,"substituteWellKnownRemoteConfig");async function tL(e,t){if(!e.plugin)return e;for(let r=0;r<e.plugin.length;r++)e.plugin[r]=await jo.resolvePluginSpec(e.plugin[r],t);return e}s(tL,"resolveLoadedPlugins");var Bo=class extends ae.Service()("@opencode/Config"){static{s(this,"Service")}},rL=Rn(Bo);function aE(){let e=["opencode.jsonc","opencode.json","config.json"].map(t=>nr.join(Fe.Path.config,t));for(let t of e)if(Xc(t))return t;return e[0]}s(aE,"globalConfigFile");function lE(e,t,r=[]){if(!He(t)){let n=ly(e,r,t,{formattingOptions:{insertSpaces:!0,tabSize:2}});return cy(e,n)}return Object.entries(t).reduce((n,[o,i])=>lE(n,i,[...r,o]),e)}s(lE,"patchJsonc");function Zc(e){let{plugin_origins:t,...r}=e;return r}s(Zc,"writable");function nL(e){let t=Zc(e);return"shell"in t&&t.shell===""?{...t,shell:void 0}:t}s(nL,"writableGlobal");var oL=B.effect(Bo,p.gen(function*(){let e=yield*Ie.Service,t=yield*qs.Service,r=yield*js.Service,n=yield*Bs.Service,o=yield*$n.Service,i=yield*Mr.HttpClient,a=s(T=>e.readFileStringSafe(T).pipe(p.orDie),"readConfigFile"),l=p.fnUntraced(function*(T,b){let A=ni.lower(iE(T),b);return yield*p.forEach(A.diagnostics,N=>p.logWarning("configuration compatibility diagnostic",{source:b,path:N.path,kind:N.kind,action:N.message})),rr.schema(Rl.Info,A.value,b)}),d=p.fnUntraced(function*(T,b,A,N){let J=yield*Mr.filterStatusOk(dc(i)).execute(Le.get(T).pipe(Le.acceptJson,Le.setHeaders(b??{}))).pipe(p.catch(he=>p.die(new Error(`failed to fetch remote config from ${T}: ${String(he)}`)))),ne=yield*J.text.pipe(p.catch(he=>p.die(new Error(`failed to read remote config from ${T}: ${String(he)}`))));return(J.headers["content-type"]??"").toLowerCase().includes("html")||/^\s*<!doctype|^\s*<html/i.test(ne)?yield*p.die(new Cp({url:N,remote:T})):yield*c.decodeEffect(c.fromJsonString(A))(ne).pipe(p.catch(he=>p.die(new Error(`failed to decode remote config from ${T}: ${String(he)}`))))}),f=p.fnUntraced(function*(T,b,A){let N="path"in b?b.path:b.source,J=yield*p.promise(()=>Uo.substitute("path"in b?{text:T,type:"path",path:b.path,env:A}:{text:T,type:"virtual",...b,env:A})),ne=rr.jsonc(J,N),de=yield*l(ne,N);if(!("path"in b))return de;if(yield*p.promise(()=>tL(de,b.path)),!de.$schema){de.$schema="https://opencode.ai/config.json";let he=T.replace(/^\s*\{/,`{
725
+ "$schema": "https://opencode.ai/config.json",`);yield*e.writeFileString(b.path,he).pipe(p.catch(()=>p.void))}return de}),m=p.fnUntraced(function*(T,b){yield*p.logInfo("loading",{path:T});let A=yield*a(T);return A?yield*f(A,{path:T},b):{}}),g=p.fnUntraced(function*(T){let b={};if(!Ee.OPENCODE_CONFIG&&!Ee.OPENCODE_CONFIG_DIR&&!Ee.OPENCODE_CONFIG_CONTENT){let N=aE();Xc(N)||(yield*e.writeWithDirs(N,JSON.stringify({$schema:"https://opencode.ai/config.json"},null,2)).pipe(p.catch(()=>p.void)))}b=oi(b,yield*m(nr.join(Fe.Path.config,"config.json"),T)),b=oi(b,yield*m(nr.join(Fe.Path.config,"opencode.json"),T)),b=oi(b,yield*m(nr.join(Fe.Path.config,"opencode.jsonc"),T));let A=nr.join(Fe.Path.config,"config");return Xc(A)&&(yield*p.promise(()=>import(ZN(A).href,{with:{type:"toml"}}).then(async N=>{let{provider:J,model:ne,...de}=N.default;J&&ne&&(b.model=`${J}/${ne}`),b.$schema="https://opencode.ai/config.json",b=oi(b,de),await oE.writeFile(nr.join(Fe.Path.config,"config.json"),JSON.stringify(b,null,2)),await oE.unlink(A)}).catch(()=>{}))),b}),[h,y]=yield*p.cachedInvalidateWithTTL(g().pipe(p.tapError(T=>p.logError("failed to load global config, using defaults",{error:String(T)})),p.orElseSucceed(()=>({}))),ur.infinity),E=p.fn("Config.getGlobal")(function*(){return yield*h}),w=p.fn("Config.ensureGitignore")(function*(T){yield*e.ensureDir(T);let b=nr.join(T,".gitignore");(yield*e.existsSafe(b))||(yield*e.writeFileString(b,["node_modules","package.json","package-lock.json","bun.lock",".gitignore"].join(`
726
+ `)).pipe(p.catchIf(N=>N.reason._tag==="PermissionDenied",()=>p.void)))}),v=p.fn("Config.loadInstanceState")(function*(T){let b=yield*t.all().pipe(p.orDie),A={},N={},J=new Set,ne,de=p.fnUntraced(function*(L){return L.startsWith("http://")||L.startsWith("https://")?"global":L==="OPENCODE_CONFIG_CONTENT"||YS(L,T)?"local":"global"}),he=p.fnUntraced(function*(L,$,ue){if(!$?.length)return;let Q=ue??(yield*de(L)),Se=jo.deduplicatePluginOrigins([...A.plugin_origins??[],...$.map(ke=>({spec:ke,source:L,scope:Q}))]);A.plugin=Se.map(ke=>ke.spec),A.plugin_origins=Se}),Ae=s((L,$,ue)=>(A=sE(A,$),he(L,$.plugin,ue)),"merge");for(let[L,$]of Object.entries(b))if($.type==="wellknown"){let ue=L.replace(/\/+$/,"");N[$.key]=$.token;let Q=`${ue}/.well-known/opencode`;yield*p.logDebug("fetching remote config",{url:Q});let Se=yield*d(Q,void 0,Rl.WellKnown,ue),ke=yield*p.promise(()=>eL({value:Se.remote_config,dir:ue,source:Q,env:N})),Ne=ke?yield*p.gen(function*(){yield*p.logDebug("fetching remote config",{url:ke.url});let me=yield*d(ke.url,ke.headers,c.Json,ue);return He(me)&&He(me.config)?me.config:He(me)?me:yield*p.die(new Error(`failed to decode remote config from ${ke.url}: expected object`))}):{},mt=oi(He(Se.config)?Se.config:{},Ne);mt.$schema||(mt.$schema="https://opencode.ai/config.json");let Lt=Q,yr=yield*f(JSON.stringify(mt),{dir:nr.dirname(Lt),source:Lt},N);yield*Ae(Lt,yr,"global"),yield*p.logDebug("loaded remote config from well-known",{url:ue})}let it=Object.keys(N).length?yield*g(N):yield*E();if(yield*Ae(Fe.Path.config,it,"global"),Ee.OPENCODE_CONFIG&&(yield*Ae(Ee.OPENCODE_CONFIG,yield*m(Ee.OPENCODE_CONFIG,N)),yield*p.logDebug("loaded custom config",{path:Ee.OPENCODE_CONFIG})),!Ee.OPENCODE_DISABLE_PROJECT_CONFIG)for(let L of yield*ei.files("opencode",T.directory,T.worktree).pipe(p.orDie))yield*Ae(L,yield*m(L,N),"local");A.agent=A.agent||{},A.mode=A.mode||{},A.plugin=A.plugin||[];let ft=yield*ei.directories(T.directory,T.worktree);Ee.OPENCODE_CONFIG_DIR&&(yield*p.logDebug("loading config from OPENCODE_CONFIG_DIR",{path:Ee.OPENCODE_CONFIG_DIR}));let Ze=[];for(let L of ft){if(L.endsWith(".opencode")||L===Ee.OPENCODE_CONFIG_DIR)for(let Q of["opencode.json","opencode.jsonc"]){let Se=nr.join(L,Q);yield*p.logDebug(`loading config from ${Se}`),yield*Ae(Se,yield*m(Se,N)),A.agent??={},A.mode??={},A.plugin??=[]}yield*w(L).pipe(p.orDie);let $=yield*o.install(L,{add:[{name:"@opencode-ai/plugin",version:lh?void 0:ms}]}).pipe(p.exit,p.tap(Q=>bn.isFailure(Q)?p.logWarning("background dependency install failed",{dir:L,error:String(Q.cause)}):p.void),p.asVoid,p.forkDetach);Ze.push($),A.command=mr(A.command??{},yield*p.promise(()=>Pa.load(L))),A.agent=mr(A.agent??{},yield*p.promise(()=>Fo.load(L))),A.agent=mr(A.agent??{},yield*p.promise(()=>Fo.loadMode(L)));let ue=yield*p.promise(()=>jo.load(L));yield*he(L,ue)}if(Ee.ALCHEMYLAB){let L=[],$=yield*p.promise(()=>Fo.loadAlchemy(T.directory,(ue,Q)=>L.push([ue,Q])));for(let[ue,Q]of L)yield*p.logWarning(ue,Q??{});Object.keys($).length>0&&(A.agent=mr(A.agent??{},$),yield*p.logInfo("alchemy agents loaded in memory",{count:Object.keys($).length}))}if(process.env.OPENCODE_CONFIG_CONTENT){let L="OPENCODE_CONFIG_CONTENT",$=yield*f(process.env.OPENCODE_CONFIG_CONTENT,{dir:T.directory,source:L});yield*Ae(L,$,"local"),yield*p.logDebug("loaded custom config from OPENCODE_CONFIG_CONTENT")}let q=P.getOrUndefined(yield*r.active().pipe(p.catch(()=>p.succeed(P.none()))));if(q?.active_org_id){let L=q.id,$=q.active_org_id,ue=q.url;yield*p.gen(function*(){let[Q,Se]=yield*p.all([r.config(L,$),r.token(L)],{concurrency:2});if(P.isSome(Se)&&(process.env.OPENCODE_CONSOLE_TOKEN=Se.value,yield*n.set("OPENCODE_CONSOLE_TOKEN",Se.value)),P.isSome(Q)){let ke=`${ue}/api/config`,Ne=yield*f(JSON.stringify(Q.value),{dir:nr.dirname(ke),source:ke});for(let mt of Object.keys(Ne.provider??{}))J.add(mt);yield*Ae(ke,Ne,"global")}}).pipe(p.withSpan("Config.loadActiveOrgConfig"),p.catch(Q=>p.logDebug("failed to fetch remote account config",{error:Q instanceof Error?Q.message:String(Q)})))}let fe=Qs.managedConfigDir();if(Xc(fe))for(let L of["opencode.json","opencode.jsonc"]){let $=nr.join(fe,L);yield*Ae($,yield*m($),"global")}let pe=yield*p.promise(()=>Qs.readManagedPreferences());pe&&(A=sE(A,yield*f(pe.text,{dir:nr.dirname(pe.source),source:pe.source})));for(let[L,$]of Object.entries(A.mode??{}))A.agent=mr(A.agent??{},{[L]:{...$,mode:"primary"}});if(Ee.OPENCODE_PERMISSION)try{A.permission=mr(A.permission??{},JSON.parse(Ee.OPENCODE_PERMISSION))}catch(L){yield*p.logWarning("OPENCODE_PERMISSION contains invalid JSON, skipping",{err:L})}if(A.tools){let L={};for(let[$,ue]of Object.entries(A.tools)){let Q=ue?"allow":"deny";if($==="write"||$==="edit"||$==="patch"){L.edit=Q;continue}L[$]=Q}A.permission=mr(L,A.permission??{})}if(!A.username)try{A.username=QN.userInfo().username||"user"}catch(L){yield*p.logWarning("failed to read system username, using fallback",{err:L}),A.username="user"}return A.autoshare===!0&&!A.share&&(A.share="auto"),Ee.OPENCODE_DISABLE_AUTOCOMPACT&&(A.compaction={...A.compaction,auto:!1}),Ee.OPENCODE_DISABLE_PRUNE&&(A.compaction={...A.compaction,prune:!1}),Ma.configure(A),{config:A,directories:ft,deps:Ze,consoleState:{consoleManagedProviders:Array.from(J),activeOrgName:ne,switchableOrgCount:0}}},p.provideService(Ie.Service,e)),O=yield*Et.make(p.fn("Config.state")(function*(T){return yield*v(T).pipe(p.orDie)})),k=p.fn("Config.get")(function*(){return yield*Et.use(O,T=>T.config)}),S=p.fn("Config.directories")(function*(){return yield*Et.use(O,T=>T.directories)}),R=p.fn("Config.getConsoleState")(function*(){return yield*Et.use(O,T=>T.consoleState)}),M=p.fn("Config.waitForDependencies")(function*(){yield*Et.useEffect(O,T=>p.forEach(T.deps,Vu.join,{concurrency:"unbounded"}).pipe(p.asVoid))}),C=p.fn("Config.update")(function*(T){let b=yield*Et.directory,A=nr.join(b,"config.json");Li.assert(A,"config update");let N=yield*m(A),J=yield*a(A),ne=J?rr.jsonc(J,A):Zc(N);yield*e.writeFileString(A,JSON.stringify(mr(He(ne)?ne:Zc(N),Zc(T)),null,2)).pipe(p.orDie)}),x=p.fn("Config.invalidate")(function*(){yield*y}),_=p.fn("Config.updateGlobal")(function*(T){let b=aE(),A=(yield*a(b))??"{}",N=nL(T),J,ne;if(b.endsWith(".jsonc")){let de=lE(A,N);J=yield*l(rr.jsonc(de,b),b),ne=de!==A,ne&&(yield*e.writeFileString(b,de).pipe(p.orDie))}else{let de=rr.jsonc(A,b);rr.schema(Rl.Info,ni.lower(iE(de),b).value,b);let he=mr(He(de)?de:{},N),Ae=JSON.stringify(he,null,2);J=yield*l(he,b),ne=Ae!==A,ne&&(yield*e.writeFileString(b,Ae).pipe(p.orDie))}return ne&&(yield*x()),{info:J,changed:ne}});return Bo.of({get:k,getGlobal:E,getConsoleState:R,update:C,updateGlobal:_,invalidate:x,directories:S,waitForDependencies:M})})),sL=Ue.make({service:Bo,layer:oL,deps:[Ie.node,qs.node,js.node,Bs.node,$n.node,Tl]});import{EventEmitter as fL}from"events";var ja={};H(ja,{Identifier:()=>ja,ascending:()=>lL,compareAscending:()=>dL,create:()=>dE,descending:()=>cL,timestamp:()=>pL});import{randomBytes as iL}from"crypto";var xf={job:"job",event:"evt",session:"ses",message:"msg",permission:"per",question:"que",part:"prt",pty:"pty",tool:"tool",workspace:"wrk"},aL=26,cE=0,bf=0;function lL(e,t){return uE(e,"ascending",t)}s(lL,"ascending");function cL(e,t){return uE(e,"descending",t)}s(cL,"descending");function uE(e,t,r){if(!r)return dE(xf[e],t);if(!r.startsWith(xf[e]))throw new Error(`ID ${r} does not start with ${xf[e]}`);return r}s(uE,"generateID");function uL(e){let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",r="",n=iL(e);for(let o=0;o<e;o++)r+=t[n[o]%62];return r}s(uL,"randomBase62");function dE(e,t,r){let n=r??Date.now();n!==cE&&(cE=n,bf=0),bf++;let o=BigInt(n)*BigInt(4096)+BigInt(bf);o=t==="descending"?~o:o;let i=Buffer.alloc(6);for(let a=0;a<6;a++)i[a]=Number(o>>BigInt(40-8*a)&BigInt(255));return e+"_"+i.toString("hex")+uL(aL-12)}s(dE,"create");function dL(e,t){if(e===t)return 0;try{let r=BigInt("0x"+e.slice(e.indexOf("_")+1,e.indexOf("_")+13)),n=BigInt("0x"+t.slice(t.indexOf("_")+1,t.indexOf("_")+13));if(r!==n){let o=1n<<48n,i=1n<<47n,a=(r-n)%o;return a<0n&&(a+=o),a<i?1:-1}}catch{}return e<t?-1:1}s(dL,"compareAscending");function pL(e){let t=e.split("_")[0],r=e.slice(t.length+1,t.length+13),n=BigInt("0x"+r);return Number(n/BigInt(4096))}s(pL,"timestamp");var Ef=class extends fL{static{s(this,"GlobalBusEmitter")}emit(t,r){return r.payload&&typeof r.payload=="object"&&!("id"in r.payload)&&(r.payload.id=r.payload.syncEvent?.id??ja.create("evt","ascending")),super.emit(t,r)}},If=new Ef;var Tf={};H(Tf,{EventV2Bridge:()=>Tf,Service:()=>si,node:()=>gL});var si=class extends ae.Service()("@opencode/EventV2Bridge"){static{s(this,"Service")}},mL=B.effect(si,p.gen(function*(){let e=yield*ut.Service,t=s((n,o,i)=>p.gen(function*(){if(i?.location)return yield*e.publish(n,o,i);let a=yield*ga;if(!a)return yield*e.publish(n,o,i);let l=yield*ha;return yield*e.publish(n,o,{...i,location:new no.Info({directory:Nr.make(a.directory),...l?{workspaceID:l}:{},project:{id:Mn.ID.make(a.project.id),directory:Nr.make(a.worktree)}})})}),"publish"),r=yield*e.listen(n=>p.gen(function*(){let o=yield*ga,i=(yield*ha)??n.location?.workspaceID;If.emit("event",{directory:n.location?.directory??o?.directory,project:o?.project.id,workspace:i,payload:{id:n.id,type:n.type,properties:n.data}}),n.durable!==void 0&&If.emit("event",{directory:n.location?.directory??o?.directory,project:o?.project.id,workspace:i,payload:{type:"sync",syncEvent:{id:n.id,type:ut.versionedType(n.type,n.durable.version),seq:n.durable.seq,aggregateID:n.durable.aggregateID,data:n.data}}})}));return yield*p.addFinalizer(()=>r),si.of({...e,publish:t})})),gL=Ue.make({service:si,layer:mL,deps:[ut.node]});var Af={};H(Af,{Git:()=>Af,Service:()=>ii,node:()=>SL});var hL=["--no-optional-locks","-c","core.autocrlf=false","-c","core.fsmonitor=false","-c","core.longpaths=true","-c","core.symlinks=true","-c","core.quotepath=false"],Ua=s(e=>e.text().trim(),"out"),_f=s(e=>e.split("\0").filter(Boolean),"nuls"),yL=s(e=>({exitCode:1,text:s(()=>"","text"),stdout:Buffer.alloc(0),stderr:Buffer.from(e instanceof Error?e.message:String(e)),truncated:!1}),"fail"),pE=s(e=>e==="??"?"added":e.includes("U")?"modified":e.includes("A")&&!e.includes("D")?"added":e.includes("D")&&!e.includes("A")?"deleted":"modified","kind"),ii=class extends ae.Service()("@opencode/Git"){static{s(this,"Service")}},vL=B.effect(ii,p.gen(function*(){let e=yield*rd.Service,t=new TextEncoder,r=s(x=>Mi.make(t.encode(x)),"stdin"),n=p.fn("Git.run")(function*(x,_){let T=yield*e.run(Cg.make("git",[...hL,...x],{cwd:_.cwd,env:_.env,extendEnv:!0,stdin:_.stdin??"ignore",stdout:"pipe",stderr:"pipe"}),{maxOutputBytes:_.maxOutputBytes});return{exitCode:T.exitCode,text:s(()=>T.stdout.toString("utf8"),"text"),stdout:T.stdout,stderr:T.stderr,truncated:T.stdoutTruncated||T.stderrTruncated}},p.catch(x=>p.succeed(yL(x)))),o=p.fn("Git.text")(function*(x,_){return(yield*n(x,_)).text()}),i=p.fn("Git.lines")(function*(x,_){return(yield*o(x,_)).split(/\r?\n/).map(T=>T.trim()).filter(Boolean)}),a=p.fnUntraced(function*(x){return yield*i(["for-each-ref","--format=%(refname:short)","refs/heads"],{cwd:x})}),l=p.fnUntraced(function*(x,_){let T=yield*n(["config","init.defaultBranch"],{cwd:x}),b=Ua(T);if(!(!b||!_.includes(b)))return{name:b,ref:b}}),d=p.fnUntraced(function*(x){let _=yield*i(["remote"],{cwd:x});return _.includes("origin")?"origin":_.length===1?_[0]:_.includes("upstream")?"upstream":_[0]}),f=p.fn("Git.branch")(function*(x){let _=yield*n(["symbolic-ref","--quiet","--short","HEAD"],{cwd:x});return _.exitCode!==0?void 0:Ua(_)||void 0}),m=p.fn("Git.prefix")(function*(x){let _=yield*n(["rev-parse","--show-prefix"],{cwd:x});return _.exitCode!==0?"":Ua(_)}),g=p.fn("Git.defaultBranch")(function*(x){let _=yield*d(x);if(_){let A=yield*n(["symbolic-ref",`refs/remotes/${_}/HEAD`],{cwd:x});if(A.exitCode===0){let N=Ua(A).replace(/^refs\/remotes\//,""),J=N.startsWith(`${_}/`)?N.slice(`${_}/`.length):"";if(J)return{name:J,ref:N}}}let T=yield*a(x),b=yield*l(x,T);if(b)return b;if(T.includes("main"))return{name:"main",ref:"main"};if(T.includes("master"))return{name:"master",ref:"master"}}),h=p.fn("Git.hasHead")(function*(x){return(yield*n(["rev-parse","--verify","HEAD"],{cwd:x})).exitCode===0}),y=p.fn("Git.mergeBase")(function*(x,_,T="HEAD"){let b=yield*n(["merge-base",_,T],{cwd:x});return b.exitCode!==0?void 0:Ua(b)||void 0}),E=p.fn("Git.show")(function*(x,_,T,b=""){let A=b?`${b}${T}`:T,N=yield*n(["show",`${_}:${A}`],{cwd:x});return N.exitCode!==0||N.stdout.includes(0)?"":N.text()}),w=p.fn("Git.status")(function*(x){return _f(yield*o(["status","--porcelain=v1","--untracked-files=all","--no-renames","-z","--","."],{cwd:x})).flatMap(_=>{let T=_.slice(3);if(!T)return[];let b=_.slice(0,2);return[{file:T,code:b,status:pE(b)}]})}),v=p.fn("Git.diff")(function*(x,_){let T=_f(yield*o(["diff","--no-ext-diff","--no-renames","--name-status","-z",_,"--","."],{cwd:x}));return T.flatMap((b,A)=>{if(A%2!==0)return[];let N=T[A+1];return!b||!N?[]:[{file:N,code:b,status:pE(b)}]})}),O=p.fn("Git.stats")(function*(x,_){return _f(yield*o(["diff","--no-ext-diff","--no-renames","--numstat","-z",_,"--","."],{cwd:x})).flatMap(T=>{let b=T.indexOf(" "),A=T.indexOf(" ",b+1);if(b===-1||A===-1)return[];let N=T.slice(A+1);if(!N)return[];let J=T.slice(0,b),ne=T.slice(b+1,A),de=J==="-"?0:Number.parseInt(J||"0",10),he=ne==="-"?0:Number.parseInt(ne||"0",10);return[{file:N,additions:Number.isFinite(de)?de:0,deletions:Number.isFinite(he)?he:0}]})}),k=p.fn("Git.patch")(function*(x,_,T,b){let A=yield*n(["diff","--patch","--no-ext-diff","--no-renames",`--unified=${b?.context??3}`,_,"--",T],{cwd:x,maxOutputBytes:b?.maxOutputBytes});return{text:A.truncated?"":A.text(),truncated:A.truncated}}),S=p.fn("Git.patchAll")(function*(x,_,T){let b=yield*n(["diff","--patch","--no-ext-diff","--no-renames",`--unified=${T?.context??3}`,_,"--","."],{cwd:x,maxOutputBytes:T?.maxOutputBytes});return{text:b.text(),truncated:b.truncated}}),R=p.fn("Git.patchUntracked")(function*(x,_,T){let b=yield*n(["diff","--no-index","--patch","--no-ext-diff","--no-renames",`--unified=${T?.context??3}`,"--","/dev/null",_],{cwd:x,maxOutputBytes:T?.maxOutputBytes});return{text:b.truncated?"":b.text(),truncated:b.truncated}}),M=p.fn("Git.statUntracked")(function*(x,_){let T=yield*n(["diff","--no-index","--numstat","--","/dev/null",_],{cwd:x,maxOutputBytes:4096});if(T.truncated)return;let A=T.text().split(" ");if(A.length<2)return;let N=A[0]==="-"?0:Number.parseInt(A[0]||"0",10),J=A[1]==="-"?0:Number.parseInt(A[1]||"0",10);return{file:_,additions:Number.isFinite(N)?N:0,deletions:Number.isFinite(J)?J:0}}),C=p.fn("Git.applyPatch")(function*(x,_){return yield*n(["apply","-"],{cwd:x,stdin:r(_)})});return ii.of({run:n,branch:f,prefix:m,defaultBranch:g,hasHead:h,mergeBase:y,show:E,status:w,diff:v,stats:O,patch:k,patchAll:S,patchUntracked:R,statUntracked:M,applyPatch:C})})),SL=Ue.make({service:ii,layer:vL,deps:[rd.node]});var kf={};H(kf,{RuntimeFlags:()=>kf,Service:()=>pn,layer:()=>bL,node:()=>EL});var qa={};H(qa,{ConfigService:()=>qa,Service:()=>wL});var wL=s(()=>(e,t)=>{class r extends ae.Service()(e){static{s(this,"ConfigTag")}static configLayer(o){return B.succeed(this,this.of(o))}static get layer(){let o=this;return B.effect(o,p.gen(function*(){let i=yield*Me.all(t);return o.of(i)}))}}return r},"Service");var Xe=s(e=>Me.boolean(e).pipe(Me.withDefault(!1)),"bool"),fE=s(e=>Me.number(e).pipe(Me.map(t=>Number.isInteger(t)&&t>0?t:void 0),Me.orElse(()=>Me.succeed(void 0))),"positiveInteger"),mE=Xe("OPENCODE_EXPERIMENTAL"),dn=s(e=>Me.all({experimental:mE,enabled:Me.boolean(e).pipe(Me.option)}).pipe(Me.map(t=>P.getOrElse(t.enabled,()=>t.experimental))),"enabledByExperimental"),pn=class extends qa.Service()("@opencode/RuntimeFlags",{autoShare:Xe("OPENCODE_AUTO_SHARE"),pure:Xe("OPENCODE_PURE"),disableDefaultPlugins:Xe("OPENCODE_DISABLE_DEFAULT_PLUGINS"),disableEmbeddedWebUi:Xe("OPENCODE_DISABLE_EMBEDDED_WEB_UI"),disableExternalSkills:Xe("OPENCODE_DISABLE_EXTERNAL_SKILLS"),disableLspDownload:Xe("OPENCODE_DISABLE_LSP_DOWNLOAD"),disableClaudeCodePrompt:Me.all({broad:Xe("OPENCODE_DISABLE_CLAUDE_CODE"),direct:Xe("OPENCODE_DISABLE_CLAUDE_CODE_PROMPT")}).pipe(Me.map(t=>t.broad||t.direct)),disableClaudeCodeSkills:Me.all({broad:Xe("OPENCODE_DISABLE_CLAUDE_CODE"),direct:Xe("OPENCODE_DISABLE_CLAUDE_CODE_SKILLS")}).pipe(Me.map(t=>t.broad||t.direct)),enableExa:Me.all({experimental:mE,enabled:Xe("OPENCODE_ENABLE_EXA"),legacy:Xe("OPENCODE_EXPERIMENTAL_EXA")}).pipe(Me.map(t=>t.experimental||t.enabled||t.legacy)),enableParallel:Me.all({enabled:Xe("OPENCODE_ENABLE_PARALLEL"),legacy:Xe("OPENCODE_EXPERIMENTAL_PARALLEL")}).pipe(Me.map(t=>t.enabled||t.legacy)),enableExperimentalModels:Xe("OPENCODE_ENABLE_EXPERIMENTAL_MODELS"),enableQuestionTool:Xe("OPENCODE_ENABLE_QUESTION_TOOL"),experimentalReferences:dn("OPENCODE_EXPERIMENTAL_REFERENCES"),experimentalBackgroundSubagents:dn("OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS"),experimentalLspTy:Xe("OPENCODE_EXPERIMENTAL_LSP_TY"),experimentalLspTool:dn("OPENCODE_EXPERIMENTAL_LSP_TOOL"),experimentalOxfmt:dn("OPENCODE_EXPERIMENTAL_OXFMT"),experimentalPlanMode:dn("OPENCODE_EXPERIMENTAL_PLAN_MODE"),experimentalCodeMode:dn("OPENCODE_EXPERIMENTAL_CODE_MODE"),experimentalEventSystem:dn("OPENCODE_EXPERIMENTAL_EVENT_SYSTEM"),experimentalWorkspaces:dn("OPENCODE_EXPERIMENTAL_WORKSPACES"),experimentalIconDiscovery:dn("OPENCODE_EXPERIMENTAL_ICON_DISCOVERY"),outputTokenMax:fE("OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX"),bashDefaultTimeoutMs:fE("OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS"),experimentalNativeLlm:Xe("OPENCODE_EXPERIMENTAL_NATIVE_LLM"),experimentalWebSockets:Xe("OPENCODE_EXPERIMENTAL_WEBSOCKETS"),client:Me.string("OPENCODE_CLIENT").pipe(Me.withDefault("cli")),alchemyLab:Xe("ALCHEMYLAB")}){static{s(this,"Service")}},xL=pn.layer.pipe(B.provide(Wu.layer(Wu.fromUnknown({}))),B.orDie),bL=s((e={})=>B.effect(pn,p.gen(function*(){let t=yield*pn;return pn.of({...t,...e})})).pipe(B.provide(xL)),"layer"),EL=Ue.make({service:pn,layer:pn.layer.pipe(B.orDie),deps:[]});var ai={};H(ai,{LocationServiceMap:()=>ai,Service:()=>Qc,node:()=>IL});var Qc=class e extends ae.Service()("@opencode/example/LocationServiceMap"){static{s(this,"Service")}static get(t){return B.unwrap(p.map(e,r=>r.get(t)))}},IL=Ue.unbound(Qc,fl.tags.values.global);var ru={};H(ru,{Tool:()=>ru,ToolFailure:()=>hs,make:()=>eu,toDefinitions:()=>tu});function eu(e){return"jsonSchema"in e?{description:e.description,parameters:c.Unknown,success:c.Unknown,execute:e.execute,toModelOutput:e.toModelOutput,toStructuredOutput:e.toStructuredOutput,_decode:p.succeed,_encode:p.succeed,_project:s((t,r,n)=>yE(e.toModelOutput,e.toStructuredOutput,t,r,n),"_project"),_legacyResult:e.toModelOutput===void 0&&e.toStructuredOutput===void 0,_definition:new gs({name:"",description:e.description,inputSchema:e.jsonSchema,outputSchema:e.outputSchema})}:{description:e.description,parameters:e.parameters,success:e.success,execute:e.execute,toModelOutput:e.toModelOutput,toStructuredOutput:e.toStructuredOutput,_decode:c.decodeUnknownEffect(e.parameters),_encode:c.encodeEffect(e.success),_project:s((t,r,n)=>yE(e.toModelOutput,e.toStructuredOutput,t,r,n),"_project"),_legacyResult:!1,_definition:new gs({name:"",description:e.description,inputSchema:hE(e.parameters),outputSchema:hE(e.success)})}}s(eu,"make");var tu=s(e=>Object.entries(e).map(([t,r])=>new gs({name:t,description:r._definition.description,inputSchema:r._definition.inputSchema,outputSchema:r._definition.outputSchema})),"toDefinitions"),hE=s(e=>{let t=c.toJsonSchemaDocument(e);return Object.keys(t.definitions).length===0?t.schema:{...t.schema,$defs:t.definitions}},"toJsonSchema"),yE=s((e,t,r,n,o)=>Fi.make(t?.(o)??o,e?.({callID:n,parameters:r,output:o})??(typeof o=="string"?[{type:"text",text:o}]:[])),"project");var TL=s((e,t)=>{let r=e[t.name];return r?r.execute?_L(r,t).pipe(p.map(n=>nu(t,n)),p.catchTag("LLM.ToolFailure",n=>p.succeed(nu(t,{type:"error",value:n.message},n.error)))):p.succeed(nu(t,{type:"error",value:`Tool has no execute handler: ${t.name}`})):p.succeed(nu(t,{type:"error",value:`Unknown tool: ${t.name}`}))},"dispatch"),_L=s((e,t)=>e._decode(t.input).pipe(p.mapError(r=>new hs({message:`Invalid tool input: ${r.message}`})),p.flatMap(r=>e.execute(r,{id:t.id,name:t.name}).pipe(p.flatMap(n=>e._encode(n).pipe(p.mapError(o=>new hs({message:`Tool returned an invalid value for its success schema: ${o.message}`})))),p.map(n=>{if(e._legacyResult&&Xu.is(n))return{result:n,output:Fi.fromResultValue(n)};let o=e._project(r,t.id,n),i=Fi.toResultValue(o);return i.type==="error"?{result:i}:{result:i,output:o}})))),"decodeAndExecute"),nu=s((e,t,r)=>{let n=Xu.is(t)?{result:t}:t;return{result:n.result,output:n.output,events:n.result.type==="error"?[ce.toolError({id:e.id,name:e.name,message:String(n.result.value),error:r}),ce.toolResult({id:e.id,name:e.name,result:n.result})]:[ce.toolResult({id:e.id,name:e.name,result:n.result,output:n.output})]}},"result"),AL={dispatch:TL};var xE={};H(xE,{GenerateObjectResponse:()=>su,generate:()=>kL,generateObject:()=>DL,request:()=>Rf,requestInput:()=>wE,stream:()=>RL,updateRequest:()=>CL});var kL=qi.generate,RL=qi.stream,wE=s(e=>({...bl.input(e)}),"requestInput"),Rf=s(e=>{let{system:t,prompt:r,messages:n,tools:o,toolChoice:i,generation:a,providerOptions:l,http:d,...f}=e;return new bl({...f,system:ph.content(t),messages:[...n?.map(Zu.make)??[],...r===void 0?[]:[Zu.user(r)]],tools:o?.map(gs.make)??[],toolChoice:i?Qu.make(i):void 0,generation:a===void 0?void 0:dh.make(a),providerOptions:l,http:d===void 0?void 0:uh.make(d)})},"request"),CL=s((e,t)=>Rf({...wE(e),...t}),"updateRequest"),ou="generate_object",vE="Return the structured result by calling this tool.",su=class{constructor(t,r){this.object=t;this.response=r}object;response;static{s(this,"GenerateObjectResponse")}get events(){return this.response.events}get usage(){return this.response.usage}},SE=p.fn("LLM.generateObject")(function*(e,t){let r=Rf(e),n=bl.update(r,{tools:tu({[ou]:t}),toolChoice:Qu.named(ou)}),o=yield*qi.generate(n),i=o.toolCalls.find(l=>ce.is.toolCall(l)&&l.name===ou);if(!i||!ce.is.toolCall(i))return yield*new ji({module:"LLM",method:"generateObject",reason:new ed({message:`generateObject: model did not call the forced \`${ou}\` tool`})});let a=yield*t._decode(i.input).pipe(p.mapError(l=>new ji({module:"LLM",method:"generateObject",reason:new ed({message:`generateObject: tool input failed schema decode: ${l.message}`})})));return new su(a,o)});function DL(e){if("schema"in e){let{schema:n,...o}=e;return SE(o,eu({description:vE,parameters:n,success:c.Unknown,execute:s(()=>p.void,"execute")}))}let{jsonSchema:t,...r}=e;return SE(r,eu({description:vE,jsonSchema:t,execute:s(()=>p.void,"execute")}))}s(DL,"generateObject");var di={};H(di,{Service:()=>ui,SessionExecution:()=>di,node:()=>oU,noopLayer:()=>sU});var $f={};H($f,{Service:()=>Bf,SessionRunner:()=>$f});var qf={};H(qf,{ModelNotSelectedError:()=>du,ModelUnavailableError:()=>pu,Service:()=>Yn,SessionRunnerModel:()=>qf,UnsupportedApiError:()=>mu,VariantUnavailableError:()=>fu,fromCatalogModel:()=>oI,layerWith:()=>Qj,locationLayer:()=>iI,node:()=>nU,resolve:()=>sI,supported:()=>Uf});var bE=s(e=>({remaining:e,dropped:0}),"newBreakpoints"),EE=s(e=>e!==void 0&&e>=3600?"1h":void 0,"ttlBucket");var se={};H(se,{Lifecycle:()=>se,finish:()=>UL,initial:()=>ML,reasoningDelta:()=>NL,reasoningEnd:()=>LL,reasoningStart:()=>IE,stepStart:()=>li,textDelta:()=>PL,textEnd:()=>FL});var ML=s(()=>({stepStarted:!1,text:new Set,reasoning:new Set}),"initial"),li=s((e,t)=>e.stepStarted?e:(t.push(ce.stepStart({index:0})),{...e,stepStarted:!0}),"stepStart"),PL=s((e,t,r,n)=>{let o=li(e,t);return o.text.has(r)?(t.push(ce.textDelta({id:r,text:n})),o):(t.push(ce.textStart({id:r}),ce.textDelta({id:r,text:n})),{...o,text:new Set([...o.text,r])})},"textDelta"),IE=s((e,t,r,n)=>{if(e.reasoning.has(r))return e;let o=li(e,t);return t.push(ce.reasoningStart({id:r,providerMetadata:n})),{...o,reasoning:new Set([...o.reasoning,r])}},"reasoningStart"),NL=s((e,t,r,n,o)=>{let i=IE(e,t,r,o);return t.push(ce.reasoningDelta({id:r,text:n})),i},"reasoningDelta"),LL=s((e,t,r,n)=>{if(!e.reasoning.has(r))return e;let o=li(e,t);t.push(ce.reasoningEnd({id:r,providerMetadata:n}));let i=new Set(o.reasoning);return i.delete(r),{...o,reasoning:i}},"reasoningEnd"),FL=s((e,t,r,n)=>{if(!e.text.has(r))return e;let o=li(e,t);t.push(ce.textEnd({id:r,providerMetadata:n}));let i=new Set(o.text);return i.delete(r),{...o,text:i}},"textEnd"),jL=s((e,t)=>{for(let r of e.reasoning)t.push(ce.reasoningEnd({id:r}));for(let r of e.text)t.push(ce.textEnd({id:r}));return{...e,text:new Set,reasoning:new Set}},"closeOpenBlocks"),UL=s((e,t,r)=>{let n=jL(li(e,t),t);return t.push(ce.stepFinish({index:0,reason:r.reason,usage:r.usage,providerMetadata:r.providerMetadata}),ce.finish(r)),{...n,stepStarted:!1}},"finish");var Ba={};H(Ba,{GeminiToolSchema:()=>Ba,convert:()=>VL});var qL=["type","properties","items","prefixItems","enum","const","$ref","additionalProperties","patternProperties","required","not","if","then","else"],Cf=s(e=>tt(e)&&(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)||Array.isArray(e.allOf)),"hasCombiner"),BL=s(e=>tt(e)&&(Cf(e)||qL.some(t=>t in e)),"hasSchemaIntent"),Df=s(e=>{if(!tt(e))return Array.isArray(e)?e.map(Df):e;let t=Object.fromEntries(Object.entries(e).map(([n,o])=>[n,n==="enum"&&Array.isArray(o)?o.map(String):Df(o)]));Array.isArray(t.enum)&&(t.type==="integer"||t.type==="number")&&(t.type="string");let r=t.properties;return t.type==="object"&&tt(r)&&Array.isArray(t.required)&&(t.required=t.required.filter(n=>typeof n=="string"&&n in r)),t.type==="array"&&!Cf(t)&&(t.items=t.items??{},tt(t.items)&&!BL(t.items)&&(t.items={...t.items,type:"string"})),typeof t.type=="string"&&t.type!=="object"&&!Cf(t)&&(delete t.properties,delete t.required),t},"sanitizeNode"),$L=s(e=>e.type==="object"&&(!tt(e.properties)||Object.keys(e.properties).length===0)&&!e.additionalProperties,"emptyObjectSchema"),$o=s(e=>{if(tt(e)&&!$L(e))return Object.fromEntries([["description",e.description],["required",e.required],["format",e.format],["type",Array.isArray(e.type)?e.type.filter(t=>t!=="null")[0]:e.type],["nullable",Array.isArray(e.type)&&e.type.includes("null")?!0:void 0],["enum",e.const!==void 0?[e.const]:e.enum],["properties",tt(e.properties)?Object.fromEntries(Object.entries(e.properties).map(([t,r])=>[t,$o(r)])):void 0],["items",Array.isArray(e.items)?e.items.map($o):e.items===void 0?void 0:$o(e.items)],["allOf",Array.isArray(e.allOf)?e.allOf.map($o):void 0],["anyOf",Array.isArray(e.anyOf)?e.anyOf.map($o):void 0],["oneOf",Array.isArray(e.oneOf)?e.oneOf.map($o):void 0],["minLength",e.minLength]].filter(t=>t[1]!==void 0))},"projectNode"),VL=s(e=>$o(Df(e)),"convert");var iu=s(e=>{if(Array.isArray(e))return e.map(iu);if(!tt(e))return e;let t=Object.fromEntries(Object.entries(e).filter(([n])=>n!=="anyOf").map(([n,o])=>[n,iu(o)]));if(!Array.isArray(e.anyOf))return t;let r=e.anyOf.filter(n=>!tt(n)||n.type!=="null").map(iu);return r.length===1&&tt(r[0])?{...t,...r[0]}:{...t,anyOf:r}},"removeNullSchemas"),TE=s(e=>{let t=e.map(au);return t.length===0?{}:t.length===1?t[0]:{anyOf:t}},"tupleItemsSchema"),au=s(e=>Array.isArray(e)?e.map(au):tt(e)?typeof e.$ref=="string"?{$ref:e.$ref}:Object.fromEntries(Object.entries(e).flatMap(([t,r])=>t==="items"&&Array.isArray(r)?[[t,TE(r)]]:t==="prefixItems"?"items"in e?[]:[["items",TE(Array.isArray(r)?r:[])]]:t==="unevaluatedItems"?[]:[[t,au(r)]])):e,"moonshotNode"),_E=s(e=>{let t=au(e);return tt(t)?t:{}},"moonshot"),HL=s(e=>{let t=Array.isArray(e.anyOf)?e.anyOf.filter(tt):[],r=t.length===0?{...e,type:"object"}:{...Object.fromEntries(Object.entries(e).filter(([o])=>o!=="anyOf")),type:"object",properties:t.reduce((o,i)=>({...tt(i.properties)?i.properties:{},...o}),{}),additionalProperties:!1},n=iu(r);return tt(n)?n:{type:"object"}},"openAI"),AE=s(e=>Ba.convert(e)??{},"gemini"),WL=s((e,t)=>{if(t===void 0)return e;switch(t){case"gemini":return AE(e);case"moonshot":return _E(e)}},"modelCompatibility"),Gn={gemini:AE,modelCompatibility:WL,moonshot:_E,openAI:HL};var Ge={};H(Ge,{ToolStream:()=>Ge,appendExisting:()=>XL,appendOrStart:()=>YL,empty:()=>kE,finish:()=>ZL,finishAll:()=>e1,finishWithInput:()=>QL,isError:()=>zL,start:()=>KL});var kE=s(()=>({}),"empty"),RE=s((e,t,r)=>({...e,[t]:r}),"withTool"),CE=s((e,t)=>{let r={...e};return delete r[t],r},"withoutTool"),GL=s(e=>ce.toolInputStart({id:e.id,name:e.name,providerMetadata:e.providerMetadata}),"inputStart"),JL=s((e,t)=>ce.toolInputDelta({id:e.id,name:e.name,text:t}),"inputDelta"),Of=s((e,t,r)=>fh(e,t.name,r??t.input).pipe(p.map(n=>ce.toolCall({id:t.id,name:t.name,input:n,providerExecuted:t.providerExecuted?!0:void 0,providerMetadata:t.providerMetadata}))),"toolCall"),DE=s((e,t,r,n)=>{let o=[];return e[t]||o.push(GL(r)),n.length>0&&o.push(JL(r,n)),{tools:RE(e,t,r),tool:r,events:o}},"appendTool"),zL=s(e=>e instanceof ji,"isError"),KL=s((e,t,r)=>RE(e,t,{...r,input:r.input??""}),"start"),YL=s((e,t,r,n,o)=>{let i=t[r],a=n.id??i?.id,l=n.name??i?.name;if(!a||!l)return td(e,o);let d={id:a,name:l,input:`${i?.input??""}${n.text}`,providerExecuted:i?.providerExecuted,providerMetadata:i?.providerMetadata};return i&&n.text.length===0&&i.id===a&&i.name===l?{tools:t,tool:i,events:[]}:DE(t,r,d,n.text)},"appendOrStart"),XL=s((e,t,r,n,o)=>{let i=t[r];return i?n.length===0?{tools:t,tool:i,events:[]}:DE(t,r,{...i,input:`${i.input}${n}`},n):td(e,o)},"appendExisting"),ZL=s((e,t,r)=>p.gen(function*(){let n=t[r];return n?{tools:CE(t,r),events:[ce.toolInputEnd({id:n.id,name:n.name,providerMetadata:n.providerMetadata}),yield*Of(e,n)]}:{tools:t}}),"finish"),QL=s((e,t,r,n)=>p.gen(function*(){let o=t[r];return o?{tools:CE(t,r),events:[ce.toolInputEnd({id:o.id,name:o.name,providerMetadata:o.providerMetadata}),yield*Of(e,o,n)]}:{tools:t}}),"finishWithInput"),e1=s((e,t)=>p.gen(function*(){let r=Object.values(t).filter(n=>n!==void 0);return{tools:kE(),events:yield*p.forEach(r,n=>Of(e,n).pipe(p.map(o=>[ce.toolInputEnd({id:n.id,name:n.name,providerMetadata:n.providerMetadata}),o]))).pipe(p.map(n=>n.flat()))}}),"finishAll");var cu="anthropic-messages",t1="https://api.anthropic.com/v1",r1="/messages",Jn=c.Struct({type:c.tag("ephemeral"),ttl:c.optional(c.Literals(["5m","1h"]))}),$a=c.Struct({type:c.tag("text"),text:c.String,cache_control:c.optional(Jn)}),PE=c.Struct({type:c.tag("image"),source:c.Struct({type:c.tag("base64"),media_type:c.String,data:c.String}),cache_control:c.optional(Jn)}),n1=c.Struct({type:c.tag("thinking"),thinking:c.String,signature:c.optional(c.String),cache_control:c.optional(Jn)}),o1=c.Struct({type:c.tag("tool_use"),id:c.String,name:c.String,input:c.Unknown,cache_control:c.optional(Jn)}),s1=c.Struct({type:c.tag("server_tool_use"),id:c.String,name:c.String,input:c.Unknown,cache_control:c.optional(Jn)}),i1=c.Literals(["web_search_tool_result","code_execution_tool_result","web_fetch_tool_result"]),a1=c.Struct({type:i1,tool_use_id:c.String,content:c.Unknown,cache_control:c.optional(Jn)}),l1=c.Union([$a,PE]),c1=c.Struct({type:c.tag("tool_result"),tool_use_id:c.String,content:c.Union([c.String,c.Array(l1)]),is_error:c.optional(c.Boolean),cache_control:c.optional(Jn)}),u1=c.Union([$a,PE,c1]),d1=c.Union([$a,n1,o1,s1,a1]),p1=c.Union([c.Struct({role:c.Literal("user"),content:c.Array(u1)}),c.Struct({role:c.Literal("assistant"),content:c.Array(d1)}),c.Struct({role:c.Literal("system"),content:c.Array($a)})]).pipe(c.toTaggedUnion("role")),f1=c.Struct({name:c.String,description:c.String,input_schema:ys,cache_control:c.optional(Jn)}),m1=c.Union([c.Struct({type:c.Literals(["auto","any"])}),c.Struct({type:c.tag("tool"),name:c.String})]),g1=c.Struct({type:c.tag("enabled"),budget_tokens:c.Number}),h1={model:c.String,system:Er($a),messages:c.Array(p1),tools:Er(f1),tool_choice:c.optional(m1),stream:c.Literal(!0),max_tokens:c.Number,temperature:c.optional(c.Number),top_p:c.optional(c.Number),top_k:c.optional(c.Number),stop_sequences:Er(c.String),thinking:c.optional(g1)},y1=c.Struct(h1),OE=c.Struct({input_tokens:c.optional(c.Number),output_tokens:c.optional(c.Number),cache_creation_input_tokens:ve(c.Number),cache_read_input_tokens:ve(c.Number)}),v1=c.Struct({type:c.String,id:c.optional(c.String),name:c.optional(c.String),text:c.optional(c.String),thinking:c.optional(c.String),signature:c.optional(c.String),input:c.optional(c.Unknown),tool_use_id:c.optional(c.String),content:c.optional(c.Unknown)}),S1=c.Struct({type:c.optional(c.String),text:c.optional(c.String),thinking:c.optional(c.String),partial_json:c.optional(c.String),signature:c.optional(c.String),stop_reason:ve(c.String),stop_sequence:ve(c.String)}),w1=c.Struct({type:c.String,index:c.optional(c.Number),message:c.optional(c.Struct({usage:c.optional(OE)})),content_block:c.optional(v1),delta:c.optional(S1),usage:c.optional(OE),error:c.optional(c.Struct({type:c.optional(c.String),message:c.optional(c.String)}))}),lu=G.invalidRequest,ME=4,x1={type:"ephemeral"},b1={type:"ephemeral",ttl:"1h"},Vo=s((e,t)=>{if(!(t?.type!=="ephemeral"&&t?.type!=="persistent")){if(e.remaining<=0){e.dropped+=1;return}return e.remaining-=1,EE(t.ttlSeconds)==="1h"?b1:x1}},"cacheControl"),Mf=s(e=>({anthropic:e}),"anthropicMetadata"),E1=s(e=>{let t=e?.anthropic;if(G.isRecord(t))return typeof t.signature=="string"?t.signature:void 0},"signatureFromMetadata"),I1=s((e,t,r)=>({name:t.name,description:t.description,input_schema:r,cache_control:Vo(e,t.cache)}),"lowerTool"),T1=s(e=>G.matchToolChoice("Anthropic Messages",e,{auto:s(()=>({type:"auto"}),"auto"),none:s(()=>{},"none"),required:s(()=>({type:"any"}),"required"),tool:s(t=>({type:"tool",name:t}),"tool")}),"lowerToolChoice"),_1=s(e=>({type:"tool_use",id:e.id,name:e.name,input:e.input}),"lowerToolCall"),A1=s(e=>({type:"server_tool_use",id:e.id,name:e.name,input:e.input}),"lowerServerToolCall"),k1=s(e=>{if(e==="web_search")return"web_search_tool_result";if(e==="code_execution")return"code_execution_tool_result";if(e==="web_fetch")return"web_fetch_tool_result"},"serverToolResultType"),R1=p.fn("AnthropicMessages.lowerServerToolResult")(function*(e){let t=k1(e.name);return t?{type:t,tool_use_id:e.id,content:e.result.value}:yield*lu(`Anthropic Messages does not know how to round-trip server tool result for ${e.name}`)}),C1=p.fn("AnthropicMessages.lowerImage")(function*(e){let t=yield*G.validateMedia("Anthropic Messages",e,new Set(G.IMAGE_MIMES));return{type:"image",source:{type:"base64",media_type:t.mime,data:t.base64}}}),D1=p.fn("AnthropicMessages.lowerToolResultContentItem")(function*(e){if(e.type==="text")return{type:"text",text:e.text};let t=yield*G.validateToolFile("Anthropic Messages",e,new Set(G.IMAGE_MIMES));return{type:"image",source:{type:"base64",media_type:t.mime,data:t.base64}}}),O1=p.fn("AnthropicMessages.lowerToolResultContent")(function*(e){if(e.result.type!=="content")return G.toolResultText(e);let t=e.result.value;return yield*p.forEach(t,D1)}),M1=s(e=>String(e.model.id)==="claude-opus-4-8","supportsNativeSystemUpdates"),P1=s(e=>{let t=e.content.at(-1);return e.role==="assistant"&&t?.type==="tool-call"&&t.providerExecuted===!0},"endsInServerToolUse"),N1=s((e,t)=>{let r=e[t-1],n=e[t+1];return r!==void 0&&r.role!=="system"&&(r.role==="user"||r.role==="tool"||P1(r))&&n?.role!=="system"&&(n===void 0||n.role==="assistant")},"canUseNativeSystemUpdate"),L1=s((e,t)=>{let r=new Set;for(let n of e.slice(0,t))for(let o of n.content)n.role==="assistant"&&o.type==="tool-call"&&o.providerExecuted!==!0&&r.add(o.id),n.role==="tool"&&o.type==="tool-result"&&r.delete(o.id);return r.size>0},"splitsLocalToolResults"),F1=p.fn("AnthropicMessages.lowerNativeSystemUpdate")(function*(e,t){return{role:"system",content:(yield*G.systemUpdateText("Anthropic Messages",e)).map(n=>({type:"text",text:n.text,cache_control:Vo(t,n.cache)}))}}),j1=p.fn("AnthropicMessages.lowerMessages")(function*(e,t){let r=[];for(let[n,o]of e.messages.entries()){if(o.role==="system"){if(L1(e.messages,n))return yield*lu("Anthropic Messages system updates cannot split a local tool call from its tool result");if(M1(e)&&N1(e.messages,n)){r.push(yield*F1(o,t));continue}let a=yield*G.wrappedSystemUpdate("Anthropic Messages",o),l={type:"text",text:a.text,cache_control:Vo(t,a.cache)},d=r.at(-1);d?.role==="user"?r[r.length-1]={role:"user",content:[...d.content,l]}:r.push({role:"user",content:[l]});continue}if(o.role==="user"){let a=[];for(let l of o.content){if(l.type==="text"){a.push({type:"text",text:l.text,cache_control:Vo(t,l.cache)});continue}if(l.type==="media"){a.push(yield*C1(l));continue}return yield*G.unsupportedContent("Anthropic Messages","user",["text","media"])}r.push({role:"user",content:a});continue}if(o.role==="assistant"){let a=[];for(let l of o.content){if(l.type==="text"){a.push({type:"text",text:l.text,cache_control:Vo(t,l.cache)});continue}if(l.type==="reasoning"){a.push({type:"thinking",thinking:l.text,signature:l.encrypted??E1(l.providerMetadata)});continue}if(l.type==="tool-call"){a.push(l.providerExecuted?A1(l):_1(l));continue}if(l.type==="tool-result"&&l.providerExecuted){a.push(yield*R1(l));continue}return yield*lu("Anthropic Messages assistant messages only support text, reasoning, and tool-call content for now")}r.push({role:"assistant",content:a});continue}let i=[];for(let a of o.content){if(!G.supportsContent(a,["tool-result"]))return yield*G.unsupportedContent("Anthropic Messages","tool",["tool-result"]);i.push({type:"tool_result",tool_use_id:a.id,content:yield*O1(a),is_error:a.result.type==="error"?!0:void 0,cache_control:Vo(t,a.cache)})}r.push({role:"user",content:i})}return r}),U1=s(e=>e.providerOptions?.anthropic,"anthropicOptions"),q1=p.fn("AnthropicMessages.lowerThinking")(function*(e){let t=U1(e)?.thinking;if(!G.isRecord(t)||t.type!=="enabled")return;let r=typeof t.budgetTokens=="number"?t.budgetTokens:typeof t.budget_tokens=="number"?t.budget_tokens:void 0;return r===void 0?yield*lu("Anthropic thinking provider option requires budgetTokens"):{type:"enabled",budget_tokens:r}}),B1=p.fn("AnthropicMessages.fromRequest")(function*(e){let t=e.toolChoice?yield*T1(e.toolChoice):void 0,r=e.generation,n=e.model.compatibility?.toolSchema,o=e.model.defaults?.limits?.output??e.model.route.defaults.limits?.output??4096,i=bE(ME),a=e.tools.length===0||e.toolChoice?.type==="none"?void 0:e.tools.map(f=>I1(i,f,Gn.modelCompatibility(f.inputSchema,n))),l=e.system.length===0?void 0:e.system.map(f=>({type:"text",text:f.text,cache_control:Vo(i,f.cache)})),d=yield*j1(e,i);return i.dropped>0&&(yield*p.logWarning(`Anthropic Messages: dropped ${i.dropped} cache breakpoint(s); the API allows at most ${ME} per request.`)),{model:e.model.id,system:l,messages:d,tools:a,tool_choice:t,stream:!0,max_tokens:r?.maxTokens??o,temperature:r?.temperature,top_p:r?.topP,top_k:r?.topK,stop_sequences:r?.stop,thinking:yield*q1(e)}}),$1=s(e=>e==="end_turn"||e==="stop_sequence"||e==="pause_turn"?"stop":e==="max_tokens"?"length":e==="tool_use"?"tool-calls":e==="refusal"?"content-filter":"unknown","mapFinishReason"),NE=s(e=>{if(!e)return;let t=e.input_tokens,r=e.cache_read_input_tokens??void 0,n=e.cache_creation_input_tokens??void 0,o=G.sumTokens(t,r,n);return new ro({inputTokens:o,outputTokens:e.output_tokens,nonCachedInputTokens:t,cacheReadInputTokens:r,cacheWriteInputTokens:n,totalTokens:G.totalTokens(o,e.output_tokens,void 0),providerMetadata:{anthropic:e}})},"mapUsage"),LE=s((e,t)=>{if(!e)return t;if(!t)return e;let r=t.nonCachedInputTokens??e.nonCachedInputTokens,n=t.cacheReadInputTokens??e.cacheReadInputTokens,o=t.cacheWriteInputTokens??e.cacheWriteInputTokens,i=G.sumTokens(r,n,o),a=t.outputTokens??e.outputTokens;return new ro({inputTokens:i,outputTokens:a,nonCachedInputTokens:r,cacheReadInputTokens:n,cacheWriteInputTokens:o,totalTokens:G.totalTokens(i,a,void 0),providerMetadata:{anthropic:{...e.providerMetadata?.anthropic,...t.providerMetadata?.anthropic}}})},"mergeUsage"),FE={web_search_tool_result:"web_search",code_execution_tool_result:"code_execution",web_fetch_tool_result:"web_fetch"},V1=s(e=>e in FE,"isServerToolResultType"),H1=s(e=>{if(!e.type||!V1(e.type))return;let r=(typeof e.content=="object"&&e.content!==null&&"type"in e.content?String(e.content.type):"").endsWith("_tool_result_error");return ce.toolResult({id:e.tool_use_id??"",name:FE[e.type],result:r?{type:"error",value:e.content}:{type:"json",value:e.content},providerExecuted:!0,providerMetadata:Mf({blockType:e.type})})},"serverToolResultEvent"),Ho=[],W1=s((e,t)=>{let r=NE(t.message?.usage);return[r?{...e,usage:LE(e.usage,r)}:e,Ho]},"onMessageStart"),G1=s((e,t)=>{let r=t.content_block;if(!r)return[e,Ho];if((r.type==="tool_use"||r.type==="server_tool_use")&&t.index!==void 0){let i=[],a=se.stepStart(e.lifecycle,i);return[{...e,lifecycle:a,tools:Ge.start(e.tools,t.index,{id:r.id??String(t.index),name:r.name??"",providerExecuted:r.type==="server_tool_use"})},[...i,ce.toolInputStart({id:r.id??String(t.index),name:r.name??""})]]}if(r.type==="text"&&r.text){let i=[];return[{...e,lifecycle:se.textDelta(e.lifecycle,i,`text-${t.index??0}`,r.text)},i]}if(r.type==="thinking"&&r.thinking){let i=[];return[{...e,lifecycle:se.reasoningDelta(e.lifecycle,i,`reasoning-${t.index??0}`,r.thinking)},i]}let n=H1(r);if(!n)return[e,Ho];let o=[];return[{...e,lifecycle:se.stepStart(e.lifecycle,o)},[...o,n]]},"onContentBlockStart"),J1=p.fn("AnthropicMessages.onContentBlockDelta")(function*(e,t){let r=t.delta;if(r?.type==="text_delta"&&r.text){let n=[];return[{...e,lifecycle:se.textDelta(e.lifecycle,n,`text-${t.index??0}`,r.text)},n]}if(r?.type==="thinking_delta"&&r.thinking){let n=[];return[{...e,lifecycle:se.reasoningDelta(e.lifecycle,n,`reasoning-${t.index??0}`,r.thinking)},n]}if(r?.type==="signature_delta"&&r.signature){let n=[];return[{...e,lifecycle:se.reasoningEnd(e.lifecycle,n,`reasoning-${t.index??0}`,Mf({signature:r.signature}))},n]}if(r?.type==="input_json_delta"&&t.index!==void 0){if(!r.partial_json)return[e,Ho];let n=Ge.appendExisting(cu,e.tools,t.index,r.partial_json,"Anthropic Messages tool argument delta is missing its tool call");if(Ge.isError(n))return yield*n;let o=[],i=n.events.length?se.stepStart(e.lifecycle,o):e.lifecycle;return o.push(...n.events),[{...e,lifecycle:i,tools:n.tools},o]}return[e,Ho]}),z1=p.fn("AnthropicMessages.onContentBlockStop")(function*(e,t){if(t.index===void 0)return[e,Ho];let r=yield*Ge.finish(cu,e.tools,t.index),n=[],o=r.events??[],i=o.length?se.stepStart(e.lifecycle,n):se.reasoningEnd(se.textEnd(e.lifecycle,n,`text-${t.index}`),n,`reasoning-${t.index}`);return n.push(...o),[{...e,lifecycle:i,tools:r.tools},n]}),K1=s((e,t)=>{let r=LE(e.usage,NE(t.usage)),n=[],o=se.finish(e.lifecycle,n,{reason:$1(t.delta?.stop_reason),usage:r,providerMetadata:t.delta?.stop_sequence?Mf({stopSequence:t.delta.stop_sequence}):void 0});return[{...e,lifecycle:o,usage:r},n]},"onMessageDelta"),Y1=s(e=>{let t=e.error?.type,r=e.error?.message;return t&&r?`${t}: ${r}`:r||t||"Anthropic Messages stream error"},"providerErrorMessage"),X1=s((e,t)=>[e,[ce.providerError({message:Y1(t),classification:Ui(t.error?.message??"")?"context-overflow":void 0})]],"onError"),Z1=s((e,t)=>t.type==="message_start"?p.succeed(W1(e,t)):t.type==="content_block_start"?p.succeed(G1(e,t)):t.type==="content_block_delta"?J1(e,t):t.type==="content_block_stop"?z1(e,t):t.type==="message_delta"?p.succeed(K1(e,t)):t.type==="error"?p.succeed(X1(e,t)):p.succeed([e,Ho]),"step"),Q1=en.make({id:cu,body:{schema:y1,from:B1},stream:{event:en.jsonEvent(w1),initial:s(()=>({tools:Ge.empty(),lifecycle:se.initial()}),"initial"),step:Z1}}),jE=Qr.make({id:cu,provider:"anthropic",protocol:Q1,endpoint:Cn.path(r1,{baseURL:t1}),auth:yt.none,framing:El.sse,headers:s(()=>({"anthropic-version":"2023-06-01"}),"headers")});var Be={};H(Be,{OpenAIOptions:()=>Be,OpenAIReasoningEffort:()=>sF,OpenAIReasoningEfforts:()=>Pf,OpenAIResponseIncludable:()=>aF,OpenAIResponseIncludables:()=>Nf,OpenAIServiceTier:()=>lF,OpenAIServiceTiers:()=>Lf,OpenAITextVerbosity:()=>iF,include:()=>gF,instructions:()=>SF,isReasoningEffort:()=>uF,promptCacheKey:()=>hF,reasoningEffort:()=>fF,reasoningSummary:()=>mF,serviceTier:()=>vF,store:()=>pF,textVerbosity:()=>yF});var Pf=Yu.filter(e=>e!=="max"),Nf=["file_search_call.results","web_search_call.results","web_search_call.action.sources","message.input_image.image_url","computer_call_output.output.image_url","code_interpreter_call.outputs","reasoning.encrypted_content","message.output_text.logprobs"],Lf=["auto","default","flex","priority"],eF=new Set(Yu),tF=new Set(Pf),rF=new Set(["low","medium","high"]),nF=new Set(Nf),oF=new Set(Lf),sF=c.Literals(Pf),iF=ch,aF=c.Literals(Nf),lF=c.Literals(Lf),cF=s(e=>typeof e=="string"&&eF.has(e),"isAnyReasoningEffort"),uF=s(e=>typeof e=="string"&&tF.has(e),"isReasoningEffort"),dF=s(e=>typeof e=="string"&&rF.has(e),"isTextVerbosity"),zn=s(e=>e.providerOptions?.openai,"options"),pF=s(e=>{let t=zn(e)?.store;return typeof t=="boolean"?t:void 0},"store"),fF=s(e=>{let t=zn(e)?.reasoningEffort;return cF(t)?t:void 0},"reasoningEffort"),mF=s(e=>zn(e)?.reasoningSummary==="auto"?"auto":void 0,"reasoningSummary"),gF=s(e=>{let t=zn(e)?.include;if(!Array.isArray(t))return;let r=t.filter(n=>nF.has(n));return r.length>0?r:void 0},"include"),hF=s(e=>{let t=zn(e)?.promptCacheKey;return typeof t=="string"?t:void 0},"promptCacheKey"),yF=s(e=>{let t=zn(e)?.textVerbosity;return dF(t)?t:void 0},"textVerbosity"),vF=s(e=>{let t=zn(e)?.serviceTier;return typeof t=="string"&&oF.has(t)?t:void 0},"serviceTier"),SF=s(e=>{let t=zn(e)?.instructions;return typeof t=="string"?t:void 0},"instructions");var uu="openai-chat",wF=new Set(G.IMAGE_MIMES),xF="https://api.openai.com/v1",bF="/chat/completions",EF=c.Struct({name:c.String,description:c.String,parameters:ys}),IF=c.Struct({type:c.tag("function"),function:EF}),TF=c.Struct({id:c.String,type:c.tag("function"),function:c.Struct({name:c.String,arguments:c.String})}),_F=c.Union([c.Struct({type:c.Literal("text"),text:c.String}),c.Struct({type:c.Literal("image_url"),image_url:c.Struct({url:c.String})})]),AF=c.Union([c.Struct({role:c.Literal("system"),content:c.String}),c.Struct({role:c.Literal("user"),content:c.Union([c.String,c.Array(_F)])}),c.Struct({role:c.Literal("assistant"),content:c.NullOr(c.String),tool_calls:Er(TF),reasoning_content:c.optional(c.String)}),c.Struct({role:c.Literal("tool"),tool_call_id:c.String,content:c.String})]).pipe(c.toTaggedUnion("role")),kF=c.Union([c.Literals(["auto","none","required"]),c.Struct({type:c.tag("function"),function:c.Struct({name:c.String})})]),RF={model:c.String,messages:c.Array(AF),tools:Er(IF),tool_choice:c.optional(kF),stream:c.Literal(!0),stream_options:c.optional(c.Struct({include_usage:c.Boolean})),store:c.optional(c.Boolean),reasoning_effort:c.optional(Be.OpenAIReasoningEffort),max_tokens:c.optional(c.Number),temperature:c.optional(c.Number),top_p:c.optional(c.Number),frequency_penalty:c.optional(c.Number),presence_penalty:c.optional(c.Number),seed:c.optional(c.Number),stop:Er(c.String)},CF=c.Struct(RF),DF=c.Struct({prompt_tokens:c.optional(c.Number),completion_tokens:c.optional(c.Number),total_tokens:c.optional(c.Number),prompt_tokens_details:ve(c.Struct({cached_tokens:c.optional(c.Number)})),completion_tokens_details:ve(c.Struct({reasoning_tokens:c.optional(c.Number)}))}),OF=c.Struct({name:ve(c.String),arguments:ve(c.String)}),MF=c.Struct({index:c.Number,id:ve(c.String),function:ve(OF)}),PF=c.Struct({content:ve(c.String),reasoning_content:ve(c.String),tool_calls:ve(c.Array(MF))}),NF=c.Struct({delta:ve(PF),finish_reason:ve(c.String)}),LF=c.Struct({choices:c.Array(NF),usage:ve(DF)}),FF=G.invalidRequest,jF=s((e,t)=>({type:"function",function:{name:e.name,description:e.description,parameters:Gn.openAI(t)}}),"lowerTool"),UF=s(e=>G.matchToolChoice("OpenAI Chat",e,{auto:s(()=>"auto","auto"),none:s(()=>"none","none"),required:s(()=>"required","required"),tool:s(t=>({type:"function",function:{name:t}}),"tool")}),"lowerToolChoice"),qF=s(e=>({id:e.id,type:"function",function:{name:e.name,arguments:G.encodeJson(e.input)}}),"lowerToolCall"),qE=p.fn("OpenAIChat.lowerMedia")(function*(e){return{type:"image_url",image_url:{url:(yield*G.validateMedia("OpenAI Chat",e,wF)).dataUrl}}}),BF=s(e=>tt(e)&&typeof e.reasoning_content=="string"?e.reasoning_content:void 0,"openAICompatibleReasoningContent"),$F=p.fn("OpenAIChat.lowerUserMessage")(function*(e){let t=[];for(let r of e.content){if(r.type==="text"){t.push({type:"text",text:r.text});continue}if(r.type==="media"){t.push(yield*qE(r));continue}return yield*G.unsupportedContent("OpenAI Chat","user",["text","media"])}return t.every(r=>r.type==="text")?{role:"user",content:t.map(r=>r.text).join("")}:{role:"user",content:t}}),VF=p.fn("OpenAIChat.lowerAssistantMessage")(function*(e){let t=[],r=[],n=[];for(let o of e.content){if(!G.supportsContent(o,["text","reasoning","tool-call"]))return yield*G.unsupportedContent("OpenAI Chat","assistant",["text","reasoning","tool-call"]);if(o.type==="text"){t.push(o);continue}if(o.type==="reasoning"){r.push(o);continue}if(o.type==="tool-call"){n.push(qF(o));continue}}return{role:"assistant",content:t.length===0?null:G.joinText(t),tool_calls:n.length===0?void 0:n,reasoning_content:r.length>0?r.map(o=>o.text).join(""):BF(e.native?.openaiCompatible)}}),BE=p.fn("OpenAIChat.lowerToolMessages")(function*(e){let t=[],r=[];for(let n of e.content){if(!G.supportsContent(n,["tool-result"]))return yield*G.unsupportedContent("OpenAI Chat","tool",["tool-result"]);if(n.result.type!=="content"){t.push({role:"tool",tool_call_id:n.id,content:G.toolResultText(n)});continue}let o=n.result.value,i=o.filter(l=>l.type==="text").map(l=>l.text);t.push({role:"tool",tool_call_id:n.id,content:i.join(`
727
+ `)});let a=o.filter(l=>l.type==="file");r.push(...yield*p.forEach(a,l=>qE({type:"media",mediaType:l.mime,data:l.uri,filename:l.name})))}return{messages:t,images:r}}),HF=p.fn("OpenAIChat.lowerMessage")(function*(e){return e.role==="user"?[yield*$F(e)]:e.role==="assistant"?[yield*VF(e)]:(yield*BE(e)).messages}),WF=p.fn("OpenAIChat.lowerMessages")(function*(e){let r=[...e.system.length===0?[]:[{role:"system",content:G.joinText(e.system)}]],n=[],o=s(()=>{n.length!==0&&r.push({role:"user",content:n.splice(0)})},"flushImages");for(let i of e.messages){if(i.role==="system"){let a=yield*G.wrappedSystemUpdate("OpenAI Chat",i);if(n.length>0){r.push({role:"user",content:[...n.splice(0),{type:"text",text:a.text}]});continue}let l=r.at(-1);l?.role==="user"&&typeof l.content=="string"?r[r.length-1]={role:"user",content:`${l.content}
728
+ ${a.text}`}:l?.role==="user"&&Array.isArray(l.content)?r[r.length-1]={role:"user",content:[...l.content,{type:"text",text:a.text}]}:r.push({role:"user",content:a.text});continue}if(i.role==="tool"){let a=yield*BE(i);r.push(...a.messages),n.push(...a.images);continue}o(),r.push(...yield*HF(i))}return o(),r}),GF=p.fn("OpenAIChat.lowerOptions")(function*(e){let t=Be.store(e),r=Be.reasoningEffort(e);return r&&!Be.isReasoningEffort(r)?yield*FF(`OpenAI Chat does not support reasoning effort ${r}`):{...t!==void 0?{store:t}:{},...r?{reasoning_effort:r}:{}}}),JF=p.fn("OpenAIChat.fromRequest")(function*(e){let t=e.generation,r=e.model.compatibility?.toolSchema;return{model:e.model.id,messages:yield*WF(e),tools:e.tools.length===0?void 0:e.tools.map(n=>jF(n,Gn.modelCompatibility(n.inputSchema,r))),tool_choice:e.toolChoice?yield*UF(e.toolChoice):void 0,stream:!0,stream_options:{include_usage:!0},max_tokens:t?.maxTokens,temperature:t?.temperature,top_p:t?.topP,frequency_penalty:t?.frequencyPenalty,presence_penalty:t?.presencePenalty,seed:t?.seed,stop:t?.stop,...yield*GF(e)}}),zF=s(e=>e==="stop"?"stop":e==="length"?"length":e==="content_filter"?"content-filter":e==="function_call"||e==="tool_calls"?"tool-calls":"unknown","mapFinishReason"),KF=s(e=>{if(!e)return;let t=e.prompt_tokens_details?.cached_tokens,r=e.completion_tokens_details?.reasoning_tokens,n=G.subtractTokens(e.prompt_tokens,t);return new ro({inputTokens:e.prompt_tokens,outputTokens:e.completion_tokens,nonCachedInputTokens:n,cacheReadInputTokens:t,reasoningTokens:r,totalTokens:G.totalTokens(e.prompt_tokens,e.completion_tokens,e.total_tokens),providerMetadata:{openai:e}})},"mapUsage"),YF=s((e,t)=>p.gen(function*(){let r=[],n=KF(t.usage)??e.usage,o=t.choices[0],i=o?.finish_reason?zF(o.finish_reason):e.finishReason,a=o?.delta,l=a?.tool_calls??[],d=e.tools,f=e.lifecycle;a?.reasoning_content&&(f=se.reasoningDelta(f,r,"reasoning-0",a.reasoning_content)),a?.content&&(f=se.reasoningEnd(f,r,"reasoning-0"),f=se.textDelta(f,r,"text-0",a.content)),l.length&&(f=se.reasoningEnd(f,r,"reasoning-0"));for(let g of l){let h=Ge.appendOrStart(uu,d,g.index,{id:g.id??void 0,name:g.function?.name??void 0,text:g.function?.arguments??""},"OpenAI Chat tool call delta is missing id or name");if(Ge.isError(h))return yield*h;d=h.tools,h.events.length&&(f=se.stepStart(f,r)),r.push(...h.events)}let m=i!==void 0&&e.finishReason===void 0&&Object.keys(d).length>0?yield*Ge.finishAll(uu,d):void 0;return[{tools:m?.tools??d,toolCallEvents:m?.events??e.toolCallEvents,usage:n,finishReason:i,lifecycle:f},r]}),"step"),XF=s(e=>{let t=[],r=e.toolCallEvents.length>0,n=e.finishReason==="stop"&&r?"tool-calls":e.finishReason,o=e.toolCallEvents.length?se.stepStart(e.lifecycle,t):e.lifecycle;return t.push(...e.toolCallEvents),n&&se.finish(o,t,{reason:n,usage:e.usage}),t},"finishEvents"),Ff=en.make({id:uu,body:{schema:CF,from:JF},stream:{event:en.jsonEvent(LF),initial:s(()=>({tools:Ge.empty(),toolCallEvents:[],lifecycle:se.initial()}),"initial"),step:YF,onHalt:XF}}),ZF=Il.sseJson.with(),SY=Qr.make({id:uu,provider:"openai",protocol:Ff,endpoint:Cn.path(bF,{baseURL:xF}),auth:yt.none,transport:ZF});var QF="openai-compatible-chat",VE=Qr.make({id:QF,protocol:Ff,endpoint:Cn.path("/chat/completions"),framing:El.sse});var ci="openai-responses",ej="https://api.openai.com/v1",tj="/responses",WE=c.Struct({type:c.tag("input_text"),text:c.String}),GE=c.Struct({type:c.tag("input_image"),image_url:c.String}),rj=c.Union([WE,GE]),nj=c.Struct({type:c.tag("output_text"),text:c.String}),oj=c.Struct({type:c.tag("summary_text"),text:c.String}),sj=c.Struct({type:c.tag("reasoning"),id:c.optionalKey(c.String),summary:c.Array(oj),encrypted_content:ve(c.String)}),ij=c.Struct({type:c.tag("item_reference"),id:c.String}),aj=c.Union([WE,GE]),lj=c.Union([c.String,c.Array(aj)]),cj=c.Union([c.Struct({role:c.tag("system"),content:c.String}),c.Struct({role:c.tag("user"),content:c.Array(rj)}),c.Struct({role:c.tag("assistant"),content:c.Array(nj)}),sj,ij,c.Struct({type:c.tag("function_call"),call_id:c.String,name:c.String,arguments:c.String}),c.Struct({type:c.tag("function_call_output"),call_id:c.String,output:lj})]),uj=c.Struct({type:c.tag("function"),name:c.String,description:c.String,parameters:ys,strict:c.optional(c.Boolean)}),dj=c.Union([c.Literals(["auto","none","required"]),c.Struct({type:c.tag("function"),name:c.String})]),JE={model:c.String,input:c.Array(cj),instructions:c.optional(c.String),tools:Er(uj),tool_choice:c.optional(dj),store:c.optional(c.Boolean),service_tier:c.optional(Be.OpenAIServiceTier),prompt_cache_key:c.optional(c.String),include:Er(Be.OpenAIResponseIncludable),reasoning:c.optional(c.Struct({effort:c.optional(Be.OpenAIReasoningEffort),summary:c.optional(c.Literal("auto"))})),text:c.optional(c.Struct({verbosity:c.optional(Be.OpenAITextVerbosity)})),max_output_tokens:c.optional(c.Number),temperature:c.optional(c.Number),top_p:c.optional(c.Number)},pj=c.Struct({...JE,stream:c.Literal(!0)}),zE=c.StructWithRest(c.Struct({type:c.tag("response.create"),...JE}),[c.Record(c.String,c.Unknown)]),fj=c.encodeSync(c.fromJsonString(zE)),mj=c.Struct({input_tokens:c.optional(c.Number),input_tokens_details:ve(c.Struct({cached_tokens:c.optional(c.Number)})),output_tokens:c.optional(c.Number),output_tokens_details:ve(c.Struct({reasoning_tokens:c.optional(c.Number)})),total_tokens:c.optional(c.Number)}),gj=c.Struct({type:c.String,id:c.optional(c.String),call_id:c.optional(c.String),name:c.optional(c.String),arguments:c.optional(c.String),status:c.optional(c.String),action:c.optional(c.Unknown),queries:c.optional(c.Unknown),results:c.optional(c.Unknown),code:c.optional(c.String),container_id:c.optional(c.String),outputs:c.optional(c.Unknown),server_label:c.optional(c.String),output:c.optional(c.Unknown),error:c.optional(c.Unknown),encrypted_content:ve(c.String)}),hj=c.Struct({code:ve(c.String),message:ve(c.String),param:ve(c.String)}),yj=c.Struct({type:c.String,delta:c.optional(c.String),item_id:c.optional(c.String),summary_index:c.optional(c.Number),item:c.optional(gj),response:c.optional(c.StructWithRest(c.Struct({id:c.optional(c.String),service_tier:ve(c.String),incomplete_details:ve(c.Struct({reason:c.String})),usage:ve(mj),error:ve(hj)}),[c.Record(c.String,c.Unknown)])),code:c.optional(c.String),message:c.optional(c.String),param:c.optional(c.String)}),vj=G.invalidRequest,Sj=s((e,t)=>({type:"function",name:e.name,description:e.description,parameters:Gn.openAI(t),strict:!1}),"lowerTool"),wj=s(e=>G.matchToolChoice("OpenAI Responses",e,{auto:s(()=>"auto","auto"),none:s(()=>"none","none"),required:s(()=>"required","required"),tool:s(t=>({type:"function",name:t}),"tool")}),"lowerToolChoice"),xj=s(e=>({type:"function_call",call_id:e.id,name:e.name,arguments:G.encodeJson(e.input)}),"lowerToolCall"),bj=s(e=>{let t=e.providerMetadata?.openai;if(!G.isRecord(t)||typeof t.itemId!="string"||t.itemId.length===0)return;let r=typeof t.reasoningEncryptedContent=="string"?t.reasoningEncryptedContent:t.reasoningEncryptedContent===null?null:void 0;return{type:"reasoning",id:t.itemId,summary:e.text.length>0?[{type:"summary_text",text:e.text}]:[],encrypted_content:r}},"lowerReasoning"),Ej=s(e=>{let t=e.providerMetadata?.openai;return G.isRecord(t)&&typeof t.itemId=="string"&&t.itemId.length>0?t.itemId:void 0},"hostedToolItemID"),Ij=p.fn("OpenAIResponses.lowerUserContent")(function*(e){return e.type==="text"?{type:"input_text",text:e.text}:e.type==="media"?{type:"input_image",image_url:(yield*G.validateMedia("OpenAI Responses",e,new Set(G.IMAGE_MIMES))).dataUrl}:yield*G.unsupportedContent("OpenAI Responses","user",["text","media"])}),Tj=p.fn("OpenAIResponses.lowerToolResultContentItem")(function*(e){return e.type==="text"?{type:"input_text",text:e.text}:{type:"input_image",image_url:(yield*G.validateToolFile("OpenAI Responses",e,new Set(G.IMAGE_MIMES))).dataUrl}}),_j=p.fn("OpenAIResponses.lowerToolResultOutput")(function*(e){if(e.result.type!=="content")return G.toolResultText(e);let t=e.result.value;return yield*p.forEach(t,Tj)}),Aj=p.fn("OpenAIResponses.lowerMessages")(function*(e){let r=[...e.system.length===0?[]:[{role:"system",content:G.joinText(e.system)}]],n=Be.store(e);for(let o of e.messages){if(o.role==="system"){let i=yield*G.wrappedSystemUpdate("OpenAI Responses",o),a=r.at(-1);a&&"role"in a&&a.role==="user"?r[r.length-1]={role:"user",content:[...a.content,{type:"input_text",text:i.text}]}:r.push({role:"user",content:[{type:"input_text",text:i.text}]});continue}if(o.role==="user"){r.push({role:"user",content:yield*p.forEach(o.content,Ij)});continue}if(o.role==="assistant"){let i=[],a={},l=new Set,d=new Set,f=s(()=>{i.length!==0&&(r.push({role:"assistant",content:i.map(m=>({type:"output_text",text:m.text}))}),i.splice(0,i.length))},"flushText");for(let m of o.content){if(m.type==="text"){i.push(m);continue}if(m.type==="reasoning"){f();let g=bj(m);if(!g)continue;if(n!==!1){l.has(g.id)||r.push({type:"item_reference",id:g.id}),l.add(g.id);continue}let h=a[g.id];if(h){h.summary.push(...g.summary),typeof g.encrypted_content=="string"&&(h.encrypted_content=g.encrypted_content);continue}let y={type:g.type,summary:g.summary,encrypted_content:g.encrypted_content};a[g.id]=y,r.push(y);continue}if(m.type==="tool-call"){if(f(),m.providerExecuted===!0)continue;r.push(xj(m));continue}if(m.type==="tool-result"&&m.providerExecuted===!0){f();let g=Ej(m);n!==!1&&g&&!d.has(g)&&r.push({type:"item_reference",id:g}),g&&d.add(g);continue}return yield*G.unsupportedContent("OpenAI Responses","assistant",["text","reasoning","tool-call","tool-result"])}f();continue}for(let i of o.content){if(!G.supportsContent(i,["tool-result"]))return yield*G.unsupportedContent("OpenAI Responses","tool",["tool-result"]);r.push({type:"function_call_output",call_id:i.id,output:yield*_j(i)})}}return n===!1?r.filter(o=>!("type"in o)||o.type!=="reasoning"||typeof o.encrypted_content=="string"):r}),kj=p.fn("OpenAIResponses.lowerOptions")(function*(e){let t=Be.store(e),r=Be.promptCacheKey(e),n=Be.reasoningEffort(e);if(n&&!Be.isReasoningEffort(n))return yield*vj(`OpenAI Responses does not support reasoning effort ${n}`);let o=Be.reasoningSummary(e),i=Be.include(e),a=Be.textVerbosity(e),l=Be.instructions(e),d=Be.serviceTier(e);return{...l?{instructions:l}:{},...t!==void 0?{store:t}:{},...r?{prompt_cache_key:r}:{},...i?{include:i}:{},...n||o?{reasoning:{effort:n,summary:o}}:{},...a?{text:{verbosity:a}}:{},...d?{service_tier:d}:{}}}),Rj=p.fn("OpenAIResponses.fromRequest")(function*(e){let t=e.generation,r=yield*kj(e),n=e.model.compatibility?.toolSchema;return{model:e.model.id,input:yield*Aj(e),tools:e.tools.length===0?void 0:e.tools.map(o=>Sj(o,Gn.modelCompatibility(o.inputSchema,n))),tool_choice:e.toolChoice?yield*wj(e.toolChoice):void 0,stream:!0,max_output_tokens:t?.maxTokens,temperature:t?.temperature,top_p:t?.topP,...r}}),Cj=s(e=>{if(!e)return;let t=e.input_tokens_details?.cached_tokens,r=e.output_tokens_details?.reasoning_tokens,n=G.subtractTokens(e.input_tokens,t);return new ro({inputTokens:e.input_tokens,outputTokens:e.output_tokens,nonCachedInputTokens:n,cacheReadInputTokens:t,reasoningTokens:r,totalTokens:G.totalTokens(e.input_tokens,e.output_tokens,e.total_tokens),providerMetadata:{openai:e}})},"mapUsage"),Dj=s((e,t)=>{let r=e.response?.incomplete_details?.reason;return r==null?t?"tool-calls":"stop":r==="max_output_tokens"?"length":r==="content_filter"?"content-filter":t?"tool-calls":"unknown"},"mapFinishReason"),Kn=s(e=>({openai:e}),"openaiMetadata"),KE={web_search_call:{name:"web_search",input:s(e=>e.action??{},"input")},web_search_preview_call:{name:"web_search_preview",input:s(e=>e.action??{},"input")},file_search_call:{name:"file_search",input:s(e=>({queries:e.queries??[]}),"input")},code_interpreter_call:{name:"code_interpreter",input:s(e=>({code:e.code,container_id:e.container_id}),"input")},computer_use_call:{name:"computer_use",input:s(e=>e.action??{},"input")},image_generation_call:{name:"image_generation",input:s(()=>({}),"input")},mcp_call:{name:"mcp",input:s(e=>({server_label:e.server_label,name:e.name,arguments:e.arguments}),"input")},local_shell_call:{name:"local_shell",input:s(e=>e.action??{},"input")}},Oj=s(e=>e.type in KE&&typeof e.id=="string"&&e.id.length>0,"isHostedToolItem"),YE=s(e=>e.type==="reasoning"&&typeof e.id=="string"&&e.id.length>0,"isReasoningItem"),Mj=s(e=>typeof e.error<"u"&&e.error!==null?{type:"error",value:e.error}:{type:"json",value:e},"hostedToolResult"),Pj=s(e=>{let t=KE[e.type],r=Kn({itemId:e.id});return[ce.toolCall({id:e.id,name:t.name,input:t.input(e),providerExecuted:!0,providerMetadata:r}),ce.toolResult({id:e.id,name:t.name,result:Mj(e),providerExecuted:!0,providerMetadata:r})]},"hostedToolEvents"),or=[],Nj=new Set(["response.completed","response.incomplete","response.failed"]),Lj=s((e,t)=>{if(!t.delta)return[e,or];let r=[];return[{...e,lifecycle:se.textDelta(e.lifecycle,r,t.item_id??"text-0",t.delta)},r]},"onOutputTextDelta"),Fj=s((e,t)=>{if(!t.delta)return[e,or];let r=[],n=t.item_id??"reasoning-0",o=t.summary_index!==void 0||e.reasoningItems[n]?`${n}:${t.summary_index??0}`:n;return[{...e,lifecycle:se.reasoningDelta(e.lifecycle,r,o,t.delta)},r]},"onReasoningDelta"),jj=s((e,t)=>[e,or],"onReasoningDone"),XE=s(e=>Kn({itemId:e.id,reasoningEncryptedContent:e.encrypted_content??null}),"reasoningMetadata"),Uj=s((e,t)=>{let r=t.item;if(r&&YE(r)){let a=[];return[{...e,lifecycle:se.reasoningStart(e.lifecycle,a,`${r.id}:0`,XE(r)),reasoningItems:{...e.reasoningItems,[r.id]:{encryptedContent:r.encrypted_content,summaryParts:{0:"active"}}}},a]}if(r?.type!=="function_call"||!r.id)return[e,or];let n=Kn({itemId:r.id}),o=[],i=se.stepStart(e.lifecycle,o);return[{...e,lifecycle:i,hasFunctionCall:e.hasFunctionCall,tools:Ge.start(e.tools,r.id,{id:r.call_id??r.id,name:r.name??"",input:r.arguments??"",providerMetadata:n})},[...o,ce.toolInputStart({id:r.call_id??r.id,name:r.name??"",providerMetadata:n})]]},"onOutputItemAdded"),qj=s((e,t)=>{if(!t.item_id||t.summary_index===void 0)return[e,or];let r=e.reasoningItems[t.item_id]??{encryptedContent:void 0,summaryParts:{}};if(t.summary_index===0){if(e.reasoningItems[t.item_id])return[e,or];let i=[];return[{...e,lifecycle:se.reasoningStart(e.lifecycle,i,`${t.item_id}:0`,Kn({itemId:t.item_id,reasoningEncryptedContent:null})),reasoningItems:{...e.reasoningItems,[t.item_id]:{...r,summaryParts:{0:"active"}}}},i]}let n=[],o=Object.entries(r.summaryParts).filter(i=>i[1]==="can-conclude").reduce((i,a)=>se.reasoningEnd(i,n,`${t.item_id}:${a[0]}`,Kn({itemId:t.item_id})),e.lifecycle);return[{...e,lifecycle:se.reasoningStart(o,n,`${t.item_id}:${t.summary_index}`,Kn({itemId:t.item_id,reasoningEncryptedContent:r.encryptedContent??null})),reasoningItems:{...e.reasoningItems,[t.item_id]:{...r,summaryParts:{...Object.fromEntries(Object.entries(r.summaryParts).map(i=>i[1]==="can-conclude"?[i[0],"concluded"]:i)),[t.summary_index]:"active"}}}},n]},"onReasoningSummaryPartAdded"),Bj=s((e,t)=>{if(!t.item_id||t.summary_index===void 0)return[e,or];let r=e.reasoningItems[t.item_id];if(!r)return[e,or];let n=[];return[{...e,lifecycle:e.store!==!1?se.reasoningEnd(e.lifecycle,n,`${t.item_id}:${t.summary_index}`,Kn({itemId:t.item_id})):e.lifecycle,reasoningItems:{...e.reasoningItems,[t.item_id]:{...r,summaryParts:{...r.summaryParts,[t.summary_index]:e.store!==!1?"concluded":"can-conclude"}}}},n]},"onReasoningSummaryPartDone"),$j=p.fn("OpenAIResponses.onFunctionCallArgumentsDelta")(function*(e,t){if(!t.item_id||!t.delta)return[e,or];let r=Ge.appendExisting(ci,e.tools,t.item_id,t.delta,"OpenAI Responses tool argument delta is missing its tool call");if(Ge.isError(r))return yield*r;let n=[],o=r.events.length?se.stepStart(e.lifecycle,n):e.lifecycle;return n.push(...r.events),[{...e,lifecycle:o,tools:r.tools},n]}),Vj=p.fn("OpenAIResponses.onOutputItemDone")(function*(e,t){let r=t.item;if(!r)return[e,or];if(r.type==="function_call"){if(!r.id||!r.call_id||!r.name)return[e,or];let n=e.tools[r.id]?e.tools:Ge.start(e.tools,r.id,{id:r.call_id,name:r.name}),o=r.arguments===void 0?yield*Ge.finish(ci,n,r.id):yield*Ge.finishWithInput(ci,n,r.id,r.arguments),i=[],a=o.events??[],l=a.length?se.stepStart(e.lifecycle,i):e.lifecycle;return i.push(...a),[{...e,lifecycle:l,hasFunctionCall:a.some(ce.is.toolCall)?!0:e.hasFunctionCall,tools:o.tools},i]}if(Oj(r)){let n=[],o=se.stepStart(e.lifecycle,n);return n.push(...Pj(r)),[{...e,lifecycle:o},n]}if(YE(r)){let n=[],o=XE(r),i=e.reasoningItems[r.id];if(i){let a=Object.entries(i.summaryParts).filter(f=>f[1]==="active"||f[1]==="can-conclude").reduce((f,m)=>se.reasoningEnd(f,n,`${r.id}:${m[0]}`,o),e.lifecycle),{[r.id]:l,...d}=e.reasoningItems;return[{...e,lifecycle:a,reasoningItems:d},n]}if(!e.lifecycle.reasoning.has(r.id)){let a=se.stepStart(e.lifecycle,n);return n.push(ce.reasoningStart({id:r.id,providerMetadata:o})),n.push(ce.reasoningEnd({id:r.id,providerMetadata:o})),[{...e,lifecycle:a},n]}return[{...e,lifecycle:se.reasoningEnd(e.lifecycle,n,r.id,o)},n]}return[e,or]}),Hj=s((e,t)=>{let r=[],n=se.finish(e.lifecycle,r,{reason:Dj(t,e.hasFunctionCall),usage:Cj(t.response?.usage),providerMetadata:t.response?.id||t.response?.service_tier?Kn({responseId:t.response.id,serviceTier:t.response.service_tier}):void 0});return[{...e,lifecycle:n},r]},"onResponseFinish"),Wj=s((e,t)=>{let r=e.response?.error??void 0,n=e.message||r?.message||void 0,o=e.code||r?.code||void 0;return n&&o?`${o}: ${n}`:n||o||t},"providerErrorMessage"),ZE=s((e,t)=>{let r=e.code||e.response?.error?.code||void 0,n=Wj(e,t);return ce.providerError({message:n,classification:r==="context_length_exceeded"||Ui(n)?"context-overflow":void 0})},"providerError"),Gj=s((e,t)=>[e,[ZE(t,"OpenAI Responses response failed")]],"onResponseFailed"),Jj=s((e,t)=>[e,[ZE(t,"OpenAI Responses stream error")]],"onError"),zj=s((e,t)=>t.type==="response.output_text.delta"?p.succeed(Lj(e,t)):t.type==="response.reasoning_text.delta"||t.type==="response.reasoning_summary.delta"||t.type==="response.reasoning_summary_text.delta"?p.succeed(Fj(e,t)):t.type==="response.reasoning_text.done"||t.type==="response.reasoning_summary.done"||t.type==="response.reasoning_summary_text.done"?p.succeed(jj(e,t)):t.type==="response.reasoning_summary_part.added"?p.succeed(qj(e,t)):t.type==="response.reasoning_summary_part.done"?p.succeed(Bj(e,t)):t.type==="response.output_item.added"?p.succeed(Uj(e,t)):t.type==="response.function_call_arguments.delta"?$j(e,t):t.type==="response.output_item.done"?Vj(e,t):t.type==="response.completed"||t.type==="response.incomplete"?p.succeed(Hj(e,t)):t.type==="response.failed"?p.succeed(Gj(e,t)):t.type==="error"?p.succeed(Jj(e,t)):p.succeed([e,or]),"step"),QE=en.make({id:ci,body:{schema:pj,from:Rj},stream:{event:en.jsonEvent(yj),initial:s(e=>({hasFunctionCall:!1,tools:Ge.empty(),lifecycle:se.initial(),reasoningItems:{},store:Be.store(e)}),"initial"),step:zj,terminal:s(e=>Nj.has(e.type),"terminal")}}),eI=Cn.path(tj,{baseURL:ej}),tI=yt.none,Kj=Il.sseJson.with(),rI=Qr.make({id:ci,provider:"openai",protocol:QE,endpoint:eI,auth:tI,transport:Kj,defaults:{providerOptions:{openai:{store:!1}}}}),Yj=G.validateWith(c.decodeUnknownEffect(zE)),Xj=s(e=>p.gen(function*(){if(!G.isRecord(e))return yield*G.invalidRequest("OpenAI Responses WebSocket body must be a JSON object");let{stream:t,...r}=e;return yield*Yj({...r,type:"response.create"})}),"webSocketMessage"),Zj=mh.jsonTransport.with({toMessage:Xj,encodeMessage:fj}),FY=Qr.make({id:`${ci}-websocket`,provider:"openai",protocol:QE,endpoint:eI,auth:tI,transport:Zj,defaults:{providerOptions:{openai:{store:!1}}}});var du=class extends c.TaggedErrorClass()("SessionRunnerModel.ModelNotSelectedError",{sessionID:Pe.ID}){static{s(this,"ModelNotSelectedError")}get message(){return`No model is available for session ${this.sessionID}`}},pu=class extends c.TaggedErrorClass()("SessionRunnerModel.ModelUnavailableError",{providerID:fs.ID,modelID:Lr.ID}){static{s(this,"ModelUnavailableError")}get message(){return`Model unavailable: ${this.providerID}/${this.modelID}`}},fu=class extends c.TaggedErrorClass()("SessionRunnerModel.VariantUnavailableError",{providerID:fs.ID,modelID:Lr.ID,variant:Lr.VariantID}){static{s(this,"VariantUnavailableError")}get message(){return`Variant unavailable for ${this.providerID}/${this.modelID}: ${this.variant}`}},mu=class extends c.TaggedErrorClass()("SessionRunnerModel.UnsupportedApiError",{providerID:fs.ID,modelID:Lr.ID,api:c.String}){static{s(this,"UnsupportedApiError")}get message(){return`Unsupported API for ${this.providerID}/${this.modelID}: ${this.api}`}},Yn=class extends ae.Service()("@opencode/v2/SessionRunnerModel"){static{s(this,"Service")}},Qj=s(e=>B.succeed(Yn,Yn.of({resolve:e})),"layerWith"),eU=s((e,t)=>{if(t?.type==="key")return yt.value(t.key);if(t?.type==="oauth")return yt.value(t.access);let r=e.request.body.apiKey??e.api.settings?.apiKey;if(typeof r=="string")return yt.value(r)},"apiKey"),jf=s((e,t)=>{let r=e.request.body,n=Object.hasOwn(r,"apiKey")?Object.fromEntries(Object.entries(r).filter(([o])=>o!=="apiKey")):r;return t.with({provider:e.providerID,endpoint:e.api.url===void 0?void 0:{baseURL:e.api.url},headers:e.request.headers,http:{body:n},limits:{context:e.limit.context,output:e.limit.output}})},"withDefaults"),tU=s((e,t)=>{let r=t==="default"||t===void 0?e.request.variant:t,n=e.variants.find(o=>o.id===r);return!n&&t!==void 0&&t!=="default"?p.fail(new fu({providerID:e.providerID,modelID:e.id,variant:t})):p.succeed(n?lo(e,o=>{Object.assign(o.request.headers,n.headers),Object.assign(o.request.body,n.body)}):e)},"withVariant"),rU=s(e=>e.api.type==="aisdk"?`${e.api.type}:${e.api.package}`:e.api.type,"apiName"),oI=s((e,t)=>{let r=t?.type!=="key"||t.metadata===void 0?e:lo(e,o=>{Object.assign(o.request.body,t.metadata)}),n=eU(r,t);return r.api.type==="aisdk"&&r.api.package==="@ai-sdk/openai"?p.succeed(jf(r,rI).with({auth:n===void 0?yt.none:yt.bearer(n)}).model({id:r.api.id})):r.api.type==="aisdk"&&r.api.package==="@ai-sdk/anthropic"?p.succeed(jf(r,jE).with({auth:n===void 0?yt.none:yt.header("x-api-key",n)}).model({id:r.api.id})):r.api.type==="aisdk"&&r.api.package==="@ai-sdk/openai-compatible"&&r.api.url?p.succeed(jf(r,VE).with({auth:n===void 0?yt.none:yt.bearer(n)}).model({id:r.api.id})):p.fail(new mu({providerID:r.providerID,modelID:r.id,api:rU(r)}))},"fromCatalogModel"),sI=s((e,t,r)=>tU(t,e.model?.variant).pipe(p.flatMap(n=>oI(n,r))),"resolve"),Uf=s(e=>e.api.type==="aisdk"&&(e.api.package==="@ai-sdk/openai"||e.api.package==="@ai-sdk/anthropic"||e.api.package==="@ai-sdk/openai-compatible"&&e.api.url!==void 0),"supported"),iI=B.effect(Yn,p.gen(function*(){let e=yield*id.Service,t=yield*Al.Service;return Yn.of({resolve:p.fn("SessionRunnerModel.resolve")(function*(r){let n=r.model?void 0:yield*e.model.default(),o=r.model?(yield*e.model.available()).find(l=>l.providerID===r.model?.providerID&&l.id===r.model.id):n&&Uf(n)?n:(yield*e.model.available()).find(Uf);if(!o&&r.model)return yield*new pu({providerID:r.model.providerID,modelID:r.model.id});if(!o)return yield*new du({sessionID:r.id});let i=yield*e.provider.get(o.providerID),a=yield*t.connection.active(i?.integrationID??Al.ID.make(o.providerID));return yield*sI(r,o,a?yield*t.connection.resolve(a):void 0)})})})),nU=ds({service:Yn,layer:iI,deps:[id.node,Al.node]});var Bf=class extends ae.Service()("@opencode/v2/SessionRunner"){static{s(this,"Service")}};var ui=class extends ae.Service()("@opencode/v2/SessionExecution"){static{s(this,"Service")}},oU=Ue.unbound(ui,fl.tags.values.global),sU=B.succeed(ui,ui.of({active:p.succeed(new Set),resume:s(()=>p.void,"resume"),wake:s(()=>p.void,"wake"),interrupt:s(()=>p.void,"interrupt")}));var Gf={};H(Gf,{ContextSnapshotDecodeError:()=>hu,ID:()=>Gy,Info:()=>Jy,ListAnchor:()=>Kl,ListInput:()=>IU,MessageDecodeError:()=>Zn,MessageNotFoundError:()=>TU,NotFoundError:()=>vu,OperationUnavailableError:()=>Wo,PromptConflictError:()=>Ha,RevertState:()=>wU,Service:()=>gi,SessionSchema:()=>Pe,SessionV2:()=>Gf,node:()=>kU});var Vf={};H(Vf,{FileAttachment:()=>aI,Prompt:()=>iU,PromptInput:()=>Vf});var aI=c.Struct({uri:c.String,name:c.String.pipe(Je),description:c.String.pipe(Je),source:nd.pipe(Je)}).annotate({identifier:"PromptInput.FileAttachment"}).pipe(ml(e=>({create:s(t=>e.make(t),"create")}))),iU=c.Struct({text:c.String,files:c.Array(aI).pipe(Je),agents:c.Array(od).pipe(Je)}).annotate({identifier:"PromptInput"});import SU from"path";var fn={};H(fn,{Error:()=>Wr,ID:()=>lI,Service:()=>Xn,Snapshot:()=>fn,locationLayer:()=>aU,node:()=>lU,noopLayer:()=>cU});import Va from"path";var lI=c.String.pipe(c.brand("Snapshot.ID")),Wr=class extends c.TaggedErrorClass()("Snapshot.Error",{operation:c.Literals(["capture","files","diff","preview","restore"]),message:c.String,cause:c.optional(c.Defect())}){static{s(this,"Error")}},Xn=class extends ae.Service()("@opencode/v2/Snapshot"){static{s(this,"Service")}},cI=B.effect(Xn,p.gen(function*(){let e=yield*Bi.Service,t=yield*Ie.Service,r=yield*On.Service,n=yield*Fe.Service,o=yield*no.Service,i=yield*r.repo.discover(o.project.directory),a=i?Nr.make(yield*t.realPath(i.worktree).pipe(p.orDie)):o.project.directory,l=Nr.make(Va.join(n.data,"snapshot",o.project.id,xl.fast(a))),d=p.fnUntraced(function*(){let S=Va.relative(a,o.directory);return S.startsWith("..")||Va.isAbsolute(S)?yield*new Wr({operation:"capture",message:"Location is outside the project"}):_n.make(S.replaceAll("\\","/")||".")}),f=p.fnUntraced(function*(){return i?(yield*t.existsSafe(Va.join(l,"HEAD")))?new On.Repository({worktree:a,gitDirectory:l,commonDirectory:l}):yield*r.repo.create({worktree:a,gitDirectory:l,seed:i}).pipe(p.mapError(S=>Ht("capture",S))):yield*new Wr({operation:"capture",message:"Project is not a Git repository"})}),m=p.fnUntraced(function*(){return o.vcs?.type!=="git"?!1:Bi.latest(yield*e.entries(),"snapshots")!==!1}),g=p.fn("Snapshot.capture")(function*(){if(yield*m())return yield*p.gen(function*(){let S=yield*f();return lI.make(yield*r.tree.capture({repository:S,scopes:[yield*d()],ignores:i,maximumUntrackedFileBytes:2*1024*1024}))}).pipe(p.catch(S=>p.logWarning("failed to capture snapshot",{cause:S}).pipe(p.as(void 0))))}),h=p.fnUntraced(function*(S,R){return{repository:yield*f().pipe(p.mapError(C=>Ht(S,C))),from:On.TreeID.make(R.from),to:On.TreeID.make(R.to)}}),y=p.fn("Snapshot.files")(function*(S){let R=yield*h("files",S),M=yield*r.tree.files(R).pipe(p.mapError(x=>Ht("files",x)));if(!i)return M;let C=yield*r.index.ignored({repository:i,paths:M}).pipe(p.mapError(x=>Ht("files",x)));return M.filter(x=>!C.has(x))}),E=p.fn("Snapshot.diff")(function*(S){let R=yield*h("diff",S),M=yield*r.tree.files(R).pipe(p.mapError(x=>Ht("diff",x))),C=i?yield*r.index.ignored({repository:i,paths:M}).pipe(p.mapError(x=>Ht("diff",x))):new Set;return yield*r.tree.diff({...R,context:S.context,paths:(S.paths??M).filter(x=>!C.has(x))}).pipe(p.mapError(x=>Ht("diff",x)))}),w=p.fnUntraced(function*(S,R){let M=new Map;for(let[C,x]of R.files){let _=Va.resolve(a,C);if(!Ie.contains(a,_))return yield*new Wr({operation:S,message:`Path escapes the project: ${C}`});M.set(C,On.TreeID.make(x))}return M}),v=p.fn("Snapshot.preview")(function*(S){if(!(yield*m()))return yield*new Wr({operation:"preview",message:"Snapshots are disabled"});let R=yield*f().pipe(p.mapError(x=>Ht("preview",x))),M=yield*w("preview",S),C=yield*r.tree.capture({repository:R,scopes:Array.from(M.keys()),ignores:i,maximumUntrackedFileBytes:2*1024*1024}).pipe(p.mapError(x=>Ht("preview",x)));return yield*r.tree.preview({repository:R,current:C,files:M,context:S.context}).pipe(p.mapError(x=>Ht("preview",x)))}),O=p.fn("Snapshot.restore")(function*(S){if(!(yield*m()))return yield*new Wr({operation:"restore",message:"Snapshots are disabled"});let R=yield*f().pipe(p.mapError(M=>Ht("restore",M)));yield*r.tree.restore({repository:R,files:yield*w("restore",S)}).pipe(p.mapError(M=>Ht("restore",M)))}),k=p.fn("Snapshot.checkout")(function*(S){let R=yield*f().pipe(p.mapError(M=>Ht("restore",M)));yield*r.tree.checkout({repository:R,tree:On.TreeID.make(S)}).pipe(p.mapError(M=>Ht("restore",M)))});return Xn.of({capture:g,files:y,diff:E,preview:v,restore:O,checkout:k})})),aU=cI.pipe(B.provideMerge(Bi.locationLayer)),lU=ds({service:Xn,layer:cI,deps:[Bi.node,Ie.node,On.node,Fe.node,no.node]}),cU=B.succeed(Xn,Xn.of({capture:s(()=>p.succeed(void 0),"capture"),files:s(()=>p.succeed([]),"files"),diff:s(()=>p.succeed([]),"diff"),preview:s(()=>p.succeed([]),"preview"),restore:s(()=>p.void,"restore"),checkout:s(()=>p.void,"checkout")}));function Ht(e,t){return t instanceof Wr&&t.operation===e?t:new Wr({operation:e,message:t instanceof globalThis.Error?t.message:String(t),cause:t})}s(Ht,"failure");function gu(e){return Pe.Info.make({id:Pe.ID.make(e.id),projectID:Mn.ID.make(e.project_id),title:e.title,parentID:e.parent_id?Pe.ID.make(e.parent_id):void 0,agent:e.agent?Gi.ID.make(e.agent):void 0,model:e.model?{id:Lr.ID.make(e.model.id),providerID:fs.ID.make(e.model.providerID),variant:Lr.VariantID.make(e.model.variant??"default")}:void 0,cost:e.cost,tokens:{input:e.tokens_input,output:e.tokens_output,reasoning:e.tokens_reasoning,cache:{read:e.tokens_cache_read,write:e.tokens_cache_write}},location:no.Ref.make({directory:Nr.make(e.directory),workspaceID:e.workspace_id?Fr.ID.make(e.workspace_id):void 0}),subpath:e.path?_n.make(e.path):void 0,revert:e.revert?{...e.revert,messageID:Z.ID.make(e.revert.messageID)}:void 0,time:{created:be.makeUnsafe(e.time_created),updated:be.makeUnsafe(e.time_updated),archived:e.time_archived?be.makeUnsafe(e.time_archived):void 0}})}s(gu,"fromRow");var mi={};H(mi,{Service:()=>fi,SessionStore:()=>mi,node:()=>mU});var pi={};H(pi,{SessionHistory:()=>pi,entriesForRunner:()=>pI,latestCompaction:()=>Hf,load:()=>dU,loadForRunner:()=>pU});var Zn=class extends c.TaggedErrorClass()("Session.MessageDecodeError",{sessionID:Pe.ID,messageID:Z.ID}){static{s(this,"MessageDecodeError")}get message(){return`Failed to decode message ${this.messageID} in session ${this.sessionID}`}},hu=class extends c.TaggedErrorClass()("Session.ContextSnapshotDecodeError",{sessionID:Pe.ID,details:c.String}){static{s(this,"ContextSnapshotDecodeError")}get message(){return`Failed to decode context snapshot for session ${this.sessionID}: ${this.details}`}};var uU=c.decodeUnknownEffect(Z.Message),Hf=p.fnUntraced(function*(e,t){return yield*e.select({seq:U.seq}).from(U).where(ye(F(U.session_id,t),F(U.type,"compaction"))).orderBy(Xr(U.seq)).limit(1).get().pipe(p.orDie)}),uI=p.fnUntraced(function*(e,t,r,n){return yield*e.select().from(U).where(ye(F(U.session_id,t),r?kn(nh(U.seq,r.seq),n===void 0?void 0:ye(F(U.type,"system"),Kt(U.seq,n))):void 0,n===void 0?void 0:kn(rh(U.type,"system"),Kt(U.seq,n)))).orderBy(br(U.seq)).all().pipe(p.orDie)}),dI=s(e=>uU({...e.data,id:e.id,type:e.type}).pipe(p.mapError(()=>new Zn({sessionID:Pe.ID.make(e.session_id),messageID:Z.ID.make(e.id)}))),"decodeMessageRow"),dU=p.fn("SessionHistory.load")(function*(e,t){let[r,n]=yield*p.all([e.select({baselineSeq:Cl.baseline_seq}).from(Cl).where(F(Cl.session_id,t)).get().pipe(p.orDie),Hf(e,t)],{concurrency:"unbounded"});return yield*p.forEach(yield*uI(e,t,n,r?.baselineSeq),dI)}),pU=p.fn("SessionHistory.loadForRunner")(function*(e,t,r){return(yield*pI(e,t,r)).map(n=>n.message)}),pI=p.fn("SessionHistory.entriesForRunner")(function*(e,t,r){let n=yield*uI(e,t,yield*Hf(e,t),r);return yield*p.forEach(n,o=>dI(o).pipe(p.map(i=>({seq:o.seq,message:i}))))});var fi=class extends ae.Service()("@opencode/v2/SessionStore"){static{s(this,"Service")}},fU=B.effect(fi,p.gen(function*(){let{db:e}=yield*Rt.Service,t=c.decodeUnknownEffect(Z.Message);return fi.of({get:p.fn("SessionStore.get")(function*(r){let n=yield*e.select().from(ee).where(F(ee.id,r)).get().pipe(p.orDie);return n?gu(n):void 0}),context:p.fn("SessionStore.context")(function*(r){return yield*pi.load(e,r)}),runnerContext:p.fn("SessionStore.runnerContext")(function*(r,n){return yield*pi.loadForRunner(e,r,n)}),message:p.fn("SessionStore.message")(function*(r){let n=yield*e.select().from(U).where(F(U.id,r)).get().pipe(p.orDie);return n?{sessionID:Pe.ID.make(n.session_id),message:yield*t({...n.data,id:n.id,type:n.type}).pipe(p.orDie)}:void 0})})})),mU=Pr({service:fi,layer:fU,deps:[Rt.node]});var Qn={};H(Qn,{MessageNotFoundError:()=>yu,SessionRevert:()=>Qn,clear:()=>yU,commit:()=>vU,stage:()=>hU});var yu=class extends c.TaggedErrorClass()("Session.MessageNotFoundError",{sessionID:Pe.ID,messageID:Z.ID}){static{s(this,"MessageNotFoundError")}},gU=p.fn("SessionRevert.plan")(function*(e){let t=(yield*Rt.Service).db,r=yield*t.select({seq:U.seq}).from(U).where(ye(F(U.session_id,e.sessionID),F(U.id,e.messageID))).get().pipe(p.orDie);if(!r)return yield*new yu(e);let n=yield*t.select().from(U).where(ye(F(U.session_id,e.sessionID),F(U.type,"assistant"),Kt(U.seq,r.seq))).orderBy(br(U.seq)).all().pipe(p.orDie),o=c.decodeUnknownEffect(Z.Message),i=new Map;for(let a of n){let l=yield*o({...a.data,id:a.id,type:a.type}).pipe(p.orDie);if(!(l.type!=="assistant"||!l.snapshot?.start))for(let d of l.snapshot.files??[])i.has(d)||i.set(d,fn.ID.make(l.snapshot.start))}return i}),hU=p.fn("SessionRevert.stage")(function*(e){let t=yield*fn.Service,r=yield*ut.Service,n=e.session.revert?.snapshot?fn.ID.make(e.session.revert.snapshot):yield*t.capture(),o=yield*gU({sessionID:e.session.id,messageID:e.messageID}),i=new Map;if(n)for(let f of e.session.revert?.files??[])i.set(f.path,n);if(e.files!==!1)for(let[f,m]of o)i.set(f,m);i.size&&(yield*t.restore({files:i}));let a=e.files===!1?[]:Array.from(o.keys()),l=n?yield*t.diff({from:n,to:(yield*t.capture())??n,paths:a}):[],d={messageID:e.messageID,snapshot:n,diff:l.map(f=>f.patch).join("").trim(),files:l};return yield*r.publish(oe.RevertEvent.Staged,{sessionID:e.session.id,timestamp:yield*be.now,revert:d}),d}),yU=p.fn("SessionRevert.clear")(function*(e){if(!e.revert)return;let t=yield*fn.Service,r=e.revert.snapshot?fn.ID.make(e.revert.snapshot):void 0;r&&(yield*t.restore({files:new Map((e.revert.files??[]).map(o=>[o.path,r]))})),yield*(yield*ut.Service).publish(oe.RevertEvent.Cleared,{sessionID:e.id,timestamp:yield*be.now})}),vU=p.fn("SessionRevert.commit")(function*(e){if(!e.revert)return;yield*(yield*ut.Service).publish(oe.RevertEvent.Committed,{sessionID:e.id,messageID:e.revert.messageID,timestamp:yield*be.now})});var wU=_l.State;var Wf={workspaceID:Fr.ID.pipe(c.optional),search:c.String.pipe(c.optional),limit:Yr.pipe(c.optional),order:c.Literals(["asc","desc"]).pipe(c.optional),anchor:Kl.pipe(c.optional)},xU=c.Struct({...Wf,directory:Nr}),bU=c.Struct({...Wf,project:Mn.ID,subpath:_n.pipe(c.optional)}),EU=c.Struct(Wf),IU=c.Union([xU,bU,EU]),vu=class extends c.TaggedErrorClass()("Session.NotFoundError",{sessionID:Pe.ID}){static{s(this,"NotFoundError")}},Wo=class extends c.TaggedErrorClass()("Session.OperationUnavailableError",{operation:c.Literals(["move","shell","skill","switchAgent","compact","wait"])}){static{s(this,"OperationUnavailableError")}},Ha=class extends c.TaggedErrorClass()("Session.PromptConflictError",{sessionID:Pe.ID,messageID:Z.ID}){static{s(this,"PromptConflictError")}},TU=Qn.MessageNotFoundError,gi=class extends ae.Service()("@opencode/v2/Session"){static{s(this,"Service")}},_U=B.effect(gi,p.gen(function*(){let e=yield*Rt.Service,t=e.db,r=yield*ut.Service,n=yield*Mn.Service,o=yield*di.Service,i=yield*mi.Service,a=yield*ai.Service,l=c.decodeUnknownEffect(Z.Message),d=c.is(oe.Durable),f=s(g=>l({...g.data,id:g.id,type:g.type}).pipe(p.mapError(()=>new Zn({sessionID:Pe.ID.make(g.session_id),messageID:Z.ID.make(g.id)}))),"decode"),m=gi.of({create:p.fn("V2Session.create")(function*(g){let h=g.id??Pe.ID.create(),y=yield*i.get(h);if(y)return y;let E=yield*n.resolve(g.location.directory);yield*t.insert(vs).values({id:E.id,worktree:E.directory,vcs:E.vcs?.type,sandboxes:[]}).onConflictDoNothing().run().pipe(p.orDie);let w=Date.now(),v=qt.SessionInfo.make({id:h,slug:Cd.create(),version:ms,projectID:E.id,directory:g.location.directory,path:SU.relative(E.directory,g.location.directory).replaceAll("\\","/"),workspaceID:g.location.workspaceID?Fr.ID.make(g.location.workspaceID):void 0,title:`New session - ${new Date(w).toISOString()}`,agent:g.agent,model:g.model?{id:Lr.ID.make(g.model.id),providerID:g.model.providerID,variant:g.model.variant}:void 0,cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},time:{created:w,updated:w}}),O=yield*r.publish(qt.Event.Created,{sessionID:h,info:v},{location:g.location}).pipe(p.as({type:"created"}),p.catchDefect(k=>k instanceof bs.SessionAlreadyProjected?i.get(h).pipe(p.flatMap(S=>S?p.succeed({type:"existing",session:S}):p.die(k))):p.die(k)));return O.type==="existing"?O.session:yield*m.get(h).pipe(p.orDie)}),get:p.fn("V2Session.get")(function*(g){let h=yield*i.get(g);return h||(yield*new vu({sessionID:g}))}),list:p.fn("V2Session.list")(function*(g={}){let h=g.anchor?.direction??"next",y=g.order??"desc",E=h==="previous"?y==="asc"?"desc":"asc":y,w=ee.time_created,v=[];"directory"in g&&v.push(F(ee.directory,g.directory)),g.workspaceID&&v.push(F(ee.workspace_id,g.workspaceID)),"project"in g&&v.push(F(ee.project_id,g.project)),g.search&&v.push(sh(ee.title,`%${g.search}%`)),g.anchor&&v.push(E==="asc"?kn(Kt(w,g.anchor.time),ye(F(w,g.anchor.time),Kt(ee.id,g.anchor.id))):kn(vl(w,g.anchor.time),ye(F(w,g.anchor.time),vl(ee.id,g.anchor.id))));let O=t.select().from(ee).where(v.length>0?ye(...v):void 0).orderBy(E==="asc"?br(w):Xr(w),E==="asc"?br(ee.id):Xr(ee.id)),k=yield*(g.limit===void 0?O.all():O.limit(g.limit).all()).pipe(p.orDie);return(h==="previous"?k.toReversed():k).map(S=>gu(S))}),messages:p.fn("V2Session.messages")(function*(g){yield*m.get(g.sessionID);let h=g.cursor?.direction??"next",y=g.order??"desc",E=h==="previous"?y==="asc"?"desc":"asc":y,w=g.cursor?yield*t.select({seq:U.seq}).from(U).where(ye(F(U.session_id,g.sessionID),F(U.id,g.cursor.id))).get().pipe(p.orDie):void 0;if(g.cursor&&!w)return[];let v=w?E==="asc"?Kt(U.seq,w.seq):vl(U.seq,w.seq):void 0,O=v?ye(F(U.session_id,g.sessionID),v):F(U.session_id,g.sessionID),k=t.select().from(U).where(O).orderBy(E==="asc"?br(U.seq):Xr(U.seq)),S=yield*(g.limit===void 0?k.all():k.limit(g.limit).all()).pipe(p.orDie);return yield*p.forEach(h==="previous"?S.toReversed():S,f)}),message:p.fn("V2Session.message")(function*(g){let h=yield*i.message(g.messageID);return h?.sessionID===g.sessionID?h.message:void 0}),context:p.fn("V2Session.context")(function*(g){return yield*m.get(g),yield*i.context(g)}),events:s(g=>Mi.unwrap(m.get(g.sessionID).pipe(p.as(r.durable({aggregateID:g.sessionID,after:g.after})))).pipe(Mi.filter(h=>d(h))),"events"),history:p.fn("V2Session.history")(function*(g){return yield*m.get(g.sessionID),yield*ut.readAggregate(t,{...g,aggregateID:g.sessionID,manifest:sy})}),prompt:p.fn("V2Session.prompt")(g=>p.uninterruptible(p.gen(function*(){yield*m.get(g.sessionID);let h=AU(g.prompt),y=g.id??Z.ID.create(),E=g.delivery??"steer",w={sessionID:g.sessionID,messageID:y,prompt:h,delivery:E},v=yield*jr.admit(t,r,{id:y,sessionID:g.sessionID,prompt:h,delivery:E}).pipe(p.catchDefect(O=>O instanceof jr.LifecycleConflict?new Ha({sessionID:g.sessionID,messageID:y}):p.die(O)));return jr.equivalent(v,w)?(g.resume!==!1&&(yield*o.wake(v.sessionID)),v):yield*new Ha({sessionID:g.sessionID,messageID:y})}))),shell:p.fn("V2Session.shell")(function*(){return yield*new Wo({operation:"shell"})}),skill:p.fn("V2Session.skill")(function*(){return yield*new Wo({operation:"skill"})}),switchAgent:p.fn("V2Session.switchAgent")(function*(g){yield*m.get(g.sessionID),yield*r.publish(oe.AgentSwitched,{sessionID:g.sessionID,messageID:Z.ID.create(),timestamp:yield*be.now,agent:g.agent})}),switchModel:p.fn("V2Session.switchModel")(function*(g){let h=yield*m.get(g.sessionID);h.model?.providerID===g.model.providerID&&h.model.id===g.model.id&&(h.model.variant??"default")===(g.model.variant??"default")||(yield*r.publish(oe.ModelSwitched,{sessionID:g.sessionID,messageID:Z.ID.create(),timestamp:yield*be.now,model:g.model}))}),compact:p.fn("V2Session.compact")(function*(g){return yield*m.get(g.sessionID),yield*new Wo({operation:"compact"})}),wait:p.fn("V2Session.wait")(function*(g){return yield*m.get(g),yield*new Wo({operation:"wait"})}),active:o.active,resume:p.fn("V2Session.resume")(function*(g){yield*m.get(g),yield*o.resume(g)}),interrupt:p.fn("V2Session.interrupt")(g=>p.uninterruptible(o.interrupt(g))),revert:{stage:p.fn("V2Session.revert.stage")(function*(g){let h=yield*m.get(g.sessionID);return yield*Qn.stage({session:h,messageID:g.messageID,files:g.files}).pipe(p.provideService(Rt.Service,e),p.provideService(ut.Service,r),p.provide(a.get(h.location)))}),clear:p.fn("V2Session.revert.clear")(function*(g){let h=yield*m.get(g);yield*Qn.clear(h).pipe(p.provideService(ut.Service,r),p.provide(a.get(h.location)))}),commit:p.fn("V2Session.revert.commit")(function*(g){let h=yield*m.get(g);yield*Qn.commit(h).pipe(p.provideService(ut.Service,r))})}});return m})),AU=s(e=>Dn.make({text:e.text,agents:e.agents,files:e.files?.map(t=>{let r=t.uri.match(/^data:([^;,]+)[;,]/i)?.[1],n=URL.canParse(t.uri)?new URL(t.uri).pathname:t.name??t.uri;return{...t,mime:r??(n.endsWith("/")?"application/x-directory":Ie.mimeType(n))}})}),"resolvePrompt"),kU=Pr({service:gi,layer:_U.pipe(B.orDie),deps:[Rt.node,ut.node,Mn.node,di.node,mi.node,ai.node,bs.node]});function Rr(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}s(Rr,"combineHeaders");async function SI(e,t){if(e==null)return Promise.resolve();let r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(fI());return}let i=setTimeout(()=>{a(),n()},e),a=s(()=>{clearTimeout(i),r?.removeEventListener("abort",l)},"cleanup"),l=s(()=>{a(),o(fI())},"onAbort");r?.addEventListener("abort",l)})}s(SI,"delay");function fI(){return new DOMException("Delay was aborted","AbortError")}s(fI,"createAbortError");var Wt=class{static{s(this,"DelayedPromise")}constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function Wa(e){return Object.fromEntries([...e.headers])}s(Wa,"extractResponseHeaders");var{btoa:RU,atob:CU}=globalThis;function hi(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=CU(t);return Uint8Array.from(r,n=>n.codePointAt(0))}s(hi,"convertBase64ToUint8Array");function gn(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return RU(t)}s(gn,"convertUint8ArrayToBase64");var wI="AI_DownloadError",xI=`vercel.ai.error.${wI}`,DU=Symbol.for(xI),mI,gI,hr=class extends(gI=X,mI=DU,gI){static{s(this,"DownloadError")}constructor({url:e,statusCode:t,statusText:r,cause:n,message:o=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:wI,message:o,cause:n}),this[mI]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return X.hasMarker(e,xI)}},Zf=2*1024*1024*1024;async function bI({response:e,url:t,maxBytes:r=Zf}){let n=e.headers.get("content-length");if(n!=null){let m=parseInt(n,10);if(!isNaN(m)&&m>r)throw new hr({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${m}).`})}let o=e.body;if(o==null)return new Uint8Array(0);let i=o.getReader(),a=[],l=0;try{for(;;){let{done:m,value:g}=await i.read();if(m)break;if(l+=g.length,l>r)throw new hr({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});a.push(g)}}finally{try{await i.cancel()}finally{i.releaseLock()}}let d=new Uint8Array(l),f=0;for(let m of a)d.set(m,f),f+=m.length;return d}s(bI,"readResponseWithSizeLimit");function Qf(e){let t;try{t=new URL(e)}catch{throw new hr({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new hr({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});let r=t.hostname;if(!r)throw new hr({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new hr({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){let n=r.slice(1,-1);if(OU(n))throw new hr({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(EI(r)){if(Kf(r))throw new hr({url:e,message:`URL with IP address ${r} is not allowed`});return}}s(Qf,"validateDownloadUrl");function EI(e){let t=e.split(".");return t.length!==4?!1:t.every(r=>{let n=Number(r);return Number.isInteger(n)&&n>=0&&n<=255&&String(n)===r})}s(EI,"isIPv4");function Kf(e){let t=e.split(".").map(Number),[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}s(Kf,"isPrivateIPv4");function OU(e){let t=e.toLowerCase();if(t==="::1"||t==="::")return!0;if(t.startsWith("::ffff:")){let r=t.slice(7);if(EI(r))return Kf(r);let n=r.split(":");if(n.length===2){let o=parseInt(n[0],16),i=parseInt(n[1],16);if(!isNaN(o)&&!isNaN(i)){let a=o>>8&255,l=o&255,d=i>>8&255,f=i&255;return Kf(`${a}.${l}.${d}.${f}`)}}}return!!(t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80"))}s(OU,"isPrivateIPv6");var Gr=s(({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let o=s(()=>{let i=r.length,a=new Array(t);for(let l=0;l<t;l++)a[l]=r[Math.random()*i|0];return a.join("")},"generator");if(e==null)return o;if(r.includes(n))throw new my({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},"createIdGenerator"),MU=Gr();function Ga(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}s(Ga,"getErrorMessage");function mn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}s(mn,"isAbortError");var PU=["fetch failed","failed to fetch"],NU=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function LU(e){if(!(e instanceof Error))return!1;let t=e.code;return!!(typeof t=="string"&&NU.includes(t))}s(LU,"isBunNetworkError");function II({error:e,url:t,requestBodyValues:r}){if(mn(e))return e;if(e instanceof TypeError&&PU.includes(e.message.toLowerCase())){let n=e.cause;if(n!=null)return new Te({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return LU(e)?new Te({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}s(II,"handleFetchError");function Su(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}s(Su,"getRuntimeEnvironmentUserAgent");function FU(e){if(e==null)return{};let t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(let[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}s(FU,"normalizeHeaders");function hn(e,...t){let r=new Headers(FU(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}s(hn,"withUserAgentSuffix");var TI="4.0.23",jU=s(()=>globalThis.fetch,"getOriginalFetch"),Jo=s(async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:i=jU()})=>{try{let a=await i(e,{method:"GET",headers:hn(t,`ai-sdk/provider-utils/${TI}`,Su()),signal:o}),l=Wa(a);if(!a.ok){let d;try{d=await n({response:a,url:e,requestBodyValues:{}})}catch(f){throw mn(f)||Te.isInstance(f)?f:new Te({message:"Failed to process error response",cause:f,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:{}})}throw d.value}try{return await r({response:a,url:e,requestBodyValues:{}})}catch(d){throw d instanceof Error&&(mn(d)||Te.isInstance(d))?d:new Te({message:"Failed to process successful response",cause:d,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:{}})}}catch(a){throw II({error:a,url:e,requestBodyValues:{}})}},"getFromApi");function _I(e){return e!=null}s(_I,"isNonNullable");function AI({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{let i=n.toLowerCase();return i==="*"||i==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:i.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}s(AI,"isUrlSupported");function yi({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}s(yi,"loadOptionalSetting");var UU=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,qU=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function hI(e){let t=JSON.parse(e);return t===null||typeof t!="object"||UU.test(e)===!1&&qU.test(e)===!1?t:BU(t)}s(hI,"_parse");function BU(e){let t=[e];for(;t.length;){let r=t;t=[];for(let n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&n.constructor!==null&&typeof n.constructor=="object"&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(let o in n){let i=n[o];i&&typeof i=="object"&&t.push(i)}}}return e}s(BU,"filter");function kI(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return hI(e)}try{return hI(e)}finally{Error.stackTraceLimit=t}}s(kI,"secureJsonParse");function em(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;let{properties:r}=e;if(r!=null)for(let n of Object.keys(r))r[n]=Go(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Go):Go(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Go)),e.allOf!=null&&(e.allOf=e.allOf.map(Go)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Go));let{definitions:t}=e;if(t!=null)for(let r of Object.keys(t))t[r]=Go(t[r]);return e}s(em,"addAdditionalPropertiesToJsonSchema");function Go(e){return typeof e=="boolean"?e:em(e)}s(Go,"visit");var $U=Symbol("Let zodToJsonSchema decide on which parser to use"),yI={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},VU=s(e=>typeof e=="string"?{...yI,name:e}:{...yI,...e},"getDefaultOptions");function sr(){return{}}s(sr,"parseAnyDef");function HU(e,t){var r,n,o;let i={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==re.ZodAny&&(i.items=we(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(i.minItems=e.minLength.value),e.maxLength&&(i.maxItems=e.maxLength.value),e.exactLength&&(i.minItems=e.exactLength.value,i.maxItems=e.exactLength.value),i}s(HU,"parseArrayDef");function WU(e){let t={type:"integer",format:"int64"};if(!e.checks)return t;for(let r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}s(WU,"parseBigintDef");function GU(){return{type:"boolean"}}s(GU,"parseBooleanDef");function RI(e,t){return we(e.type._def,t)}s(RI,"parseBrandedDef");var JU=s((e,t)=>we(e.innerType._def,t),"parseCatchDef");function CI(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>CI(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zU(e)}}s(CI,"parseDateDef");var zU=s(e=>{let t={type:"integer",format:"unix-time"};for(let r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t},"integerDateParser");function KU(e,t){return{...we(e.innerType._def,t),default:e.defaultValue()}}s(KU,"parseDefaultDef");function YU(e,t){return t.effectStrategy==="input"?we(e.schema._def,t):sr()}s(YU,"parseEffectsDef");function XU(e){return{type:"string",enum:Array.from(e.values)}}s(XU,"parseEnumDef");var ZU=s(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function QU(e,t){let r=[we(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),we(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(ZU(o))n.push(...o.allOf);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...l}=o;i=l}n.push(i)}}),n.length?{allOf:n}:void 0}s(QU,"parseIntersectionDef");function e2(e){let t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}s(e2,"parseLiteralDef");var Jf=void 0,Ar={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:s(()=>(Jf===void 0&&(Jf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Jf),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function DI(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":kr(r,"email",n.message,t);break;case"format:idn-email":kr(r,"idn-email",n.message,t);break;case"pattern:zod":Ot(r,Ar.email,n.message,t);break}break;case"url":kr(r,"uri",n.message,t);break;case"uuid":kr(r,"uuid",n.message,t);break;case"regex":Ot(r,n.regex,n.message,t);break;case"cuid":Ot(r,Ar.cuid,n.message,t);break;case"cuid2":Ot(r,Ar.cuid2,n.message,t);break;case"startsWith":Ot(r,RegExp(`^${zf(n.value,t)}`),n.message,t);break;case"endsWith":Ot(r,RegExp(`${zf(n.value,t)}$`),n.message,t);break;case"datetime":kr(r,"date-time",n.message,t);break;case"date":kr(r,"date",n.message,t);break;case"time":kr(r,"time",n.message,t);break;case"duration":kr(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{Ot(r,RegExp(zf(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&kr(r,"ipv4",n.message,t),n.version!=="v4"&&kr(r,"ipv6",n.message,t);break}case"base64url":Ot(r,Ar.base64url,n.message,t);break;case"jwt":Ot(r,Ar.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Ot(r,Ar.ipv4Cidr,n.message,t),n.version!=="v4"&&Ot(r,Ar.ipv6Cidr,n.message,t);break}case"emoji":Ot(r,Ar.emoji(),n.message,t);break;case"ulid":{Ot(r,Ar.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{kr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Ot(r,Ar.base64,n.message,t);break}}break}case"nanoid":Ot(r,Ar.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}s(DI,"parseStringDef");function zf(e,t){return t.patternStrategy==="escape"?r2(e):e}s(zf,"escapeLiteralCheckValue");var t2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function r2(e){let t="";for(let r=0;r<e.length;r++)t2.has(e[r])||(t+="\\"),t+=e[r];return t}s(r2,"escapeNonAlphaNumeric");function kr(e,t,r,n){var o;e.format||(o=e.anyOf)!=null&&o.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}s(kr,"addFormat");function Ot(e,t,r,n){var o;e.pattern||(o=e.allOf)!=null&&o.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:vI(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=vI(t,n)}s(Ot,"addPattern");function vI(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=n.i?e.source.toLowerCase():e.source,i="",a=!1,l=!1,d=!1;for(let f=0;f<o.length;f++){if(a){i+=o[f],a=!1;continue}if(n.i){if(l){if(o[f].match(/[a-z]/)){d?(i+=o[f],i+=`${o[f-2]}-${o[f]}`.toUpperCase(),d=!1):o[f+1]==="-"&&((r=o[f+2])!=null&&r.match(/[a-z]/))?(i+=o[f],d=!0):i+=`${o[f]}${o[f].toUpperCase()}`;continue}}else if(o[f].match(/[a-z]/)){i+=`[${o[f]}${o[f].toUpperCase()}]`;continue}}if(n.m){if(o[f]==="^"){i+=`(^|(?<=[\r
729
+ ]))`;continue}else if(o[f]==="$"){i+=`($|(?=[\r
730
+ ]))`;continue}}if(n.s&&o[f]==="."){i+=l?`${o[f]}\r
731
+ `:`[${o[f]}\r
732
+ ]`;continue}i+=o[f],o[f]==="\\"?a=!0:l&&o[f]==="]"?l=!1:!l&&o[f]==="["&&(l=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}s(vI,"stringifyRegExpWithFlags");function OI(e,t){var r,n,o,i,a,l;let d={type:"object",additionalProperties:(r=we(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===re.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){let{type:f,...m}=DI(e.keyType._def,t);return{...d,propertyNames:m}}else{if(((i=e.keyType)==null?void 0:i._def.typeName)===re.ZodEnum)return{...d,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===re.ZodBranded&&e.keyType._def.type._def.typeName===re.ZodString&&((l=e.keyType._def.type._def.checks)!=null&&l.length)){let{type:f,...m}=RI(e.keyType._def,t);return{...d,propertyNames:m}}}return d}s(OI,"parseRecordDef");function n2(e,t){if(t.mapStrategy==="record")return OI(e,t);let r=we(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||sr(),n=we(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||sr();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}s(n2,"parseMapDef");function o2(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}s(o2,"parseNativeEnumDef");function s2(){return{not:sr()}}s(s2,"parseNeverDef");function i2(){return{type:"null"}}s(i2,"parseNullDef");var Yf={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function a2(e,t){let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Yf&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=Yf[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,l)=>l.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return l2(e,t)}s(a2,"parseUnionDef");var l2=s((e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>we(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0},"asAnyOf");function c2(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Yf[e.innerType._def.typeName],"null"]};let r=we(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}s(c2,"parseNullableDef");function u2(e){let t={type:"number"};if(!e.checks)return t;for(let r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}s(u2,"parseNumberDef");function d2(e,t){let r={type:"object",properties:{}},n=[],o=e.shape();for(let a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let d=f2(l),f=we(l._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});f!==void 0&&(r.properties[a]=f,d||n.push(a))}n.length&&(r.required=n);let i=p2(e,t);return i!==void 0&&(r.additionalProperties=i),r}s(d2,"parseObjectDef");function p2(e,t){if(e.catchall._def.typeName!=="ZodNever")return we(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}s(p2,"decideAdditionalProperties");function f2(e){try{return e.isOptional()}catch{return!0}}s(f2,"safeIsOptional");var m2=s((e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return we(e.innerType._def,t);let n=we(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:sr()},n]}:sr()},"parseOptionalDef"),g2=s((e,t)=>{if(t.pipeStrategy==="input")return we(e.in._def,t);if(t.pipeStrategy==="output")return we(e.out._def,t);let r=we(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=we(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}},"parsePipelineDef");function h2(e,t){return we(e.type._def,t)}s(h2,"parsePromiseDef");function y2(e,t){let n={type:"array",uniqueItems:!0,items:we(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}s(y2,"parseSetDef");function v2(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>we(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:we(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>we(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}s(v2,"parseTupleDef");function S2(){return{not:sr()}}s(S2,"parseUndefinedDef");function w2(){return sr()}s(w2,"parseUnknownDef");var x2=s((e,t)=>we(e.innerType._def,t),"parseReadonlyDef"),b2=s((e,t,r)=>{switch(t){case re.ZodString:return DI(e,r);case re.ZodNumber:return u2(e);case re.ZodObject:return d2(e,r);case re.ZodBigInt:return WU(e);case re.ZodBoolean:return GU();case re.ZodDate:return CI(e,r);case re.ZodUndefined:return S2();case re.ZodNull:return i2();case re.ZodArray:return HU(e,r);case re.ZodUnion:case re.ZodDiscriminatedUnion:return a2(e,r);case re.ZodIntersection:return QU(e,r);case re.ZodTuple:return v2(e,r);case re.ZodRecord:return OI(e,r);case re.ZodLiteral:return e2(e);case re.ZodEnum:return XU(e);case re.ZodNativeEnum:return o2(e);case re.ZodNullable:return c2(e,r);case re.ZodOptional:return m2(e,r);case re.ZodMap:return n2(e,r);case re.ZodSet:return y2(e,r);case re.ZodLazy:return()=>e.getter()._def;case re.ZodPromise:return h2(e,r);case re.ZodNaN:case re.ZodNever:return s2();case re.ZodEffects:return YU(e,r);case re.ZodAny:return sr();case re.ZodUnknown:return w2();case re.ZodDefault:return KU(e,r);case re.ZodBranded:return RI(e,r);case re.ZodReadonly:return x2(e,r);case re.ZodCatch:return JU(e,r);case re.ZodPipeline:return g2(e,r);case re.ZodFunction:case re.ZodVoid:case re.ZodSymbol:return;default:return(n=>{})(t)}},"selectParser"),E2=s((e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},"getRelativePath");function we(e,t,r=!1){var n;let o=t.seen.get(e);if(t.override){let d=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(d!==$U)return d}if(o&&!r){let d=I2(o,t);if(d!==void 0)return d}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=b2(e,e.typeName,t),l=typeof a=="function"?we(a(),t):a;if(l&&T2(e,t,l),t.postProcess){let d=t.postProcess(l,e,t);return i.jsonSchema=l,d}return i.jsonSchema=l,l}s(we,"parseDef");var I2=s((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:E2(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),sr()):t.$refStrategy==="seen"?sr():void 0}},"get$ref"),T2=s((e,t,r)=>(e.description&&(r.description=e.description),r),"addMeta"),_2=s(e=>{let t=VU(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},"getRefs"),A2=s((e,t)=>{var r;let n=_2(t),o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((f,[m,g])=>{var h;return{...f,[m]:(h=we(g._def,{...n,currentPath:[...n.basePath,n.definitionPath,m]},!0))!=null?h:sr()}},{}):void 0,i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=we(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1))!=null?r:sr(),l=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;l!==void 0&&(a.title=l);let d=i===void 0?o?{...a,[n.definitionPath]:o}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,i].join("/"),[n.definitionPath]:{...o,[i]:a}};return d.$schema="http://json-schema.org/draft-07/schema#",d},"zod3ToJsonSchema"),Xf=Symbol.for("vercel.ai.schema");function De(e){let t;return()=>(t==null&&(t=e()),t)}s(De,"lazySchema");function Ja(e,{validate:t}={}){return{[Xf]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}s(Ja,"jsonSchema");function k2(e){return typeof e=="object"&&e!==null&&Xf in e&&e[Xf]===!0&&"jsonSchema"in e&&"validate"in e}s(k2,"isSchema");function ir(e){return e==null?Ja({properties:{},additionalProperties:!1}):k2(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?xe(e):R2(e):e()}s(ir,"asSchema");function R2(e){return Ja(()=>em(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:s(async t=>{let r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new ze({value:t,cause:r.issues})}},"validate")})}s(R2,"standardSchema");function C2(e,t){var r;let n=(r=t?.useReferences)!=null?r:!1;return Ja(()=>A2(e,{$refStrategy:n?"root":"none"}),{validate:s(async o=>{let i=await e.safeParseAsync(o);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}},"validate")})}s(C2,"zod3Schema");function D2(e,t){var r;let n=(r=t?.useReferences)!=null?r:!1;return Ja(()=>em(gy(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:s(async o=>{let i=await hy(e,o);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}},"validate")})}s(D2,"zod4Schema");function O2(e){return"_zod"in e}s(O2,"isZod4Schema");function xe(e,t){return O2(e)?D2(e,t):C2(e,t)}s(xe,"zodSchema");async function za({value:e,schema:t,context:r}){let n=await st({value:e,schema:t,context:r});if(!n.success)throw ze.wrap({value:e,cause:n.error,context:r});return n.value}s(za,"validateTypes");async function st({value:e,schema:t,context:r}){let n=ir(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:ze.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:ze.wrap({value:e,cause:o,context:r}),rawValue:e}}}s(st,"safeValidateTypes");async function M2({text:e,schema:t}){try{let r=kI(e);return t==null?r:za({value:r,schema:t})}catch(r){throw Nn.isInstance(r)||ze.isInstance(r)?r:new Nn({text:e,cause:r})}}s(M2,"parseJSON");async function _t({text:e,schema:t}){try{let r=kI(e);return t==null?{success:!0,value:r,rawValue:r}:await st({value:r,schema:t})}catch(r){return{success:!1,error:Nn.isInstance(r)?r:new Nn({text:e,cause:r}),rawValue:void 0}}}s(_t,"safeParseJSON");function wu({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new yy).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await _t({text:r,schema:t}))}}))}s(wu,"parseJsonEventStream");var P2=s(()=>globalThis.fetch,"getOriginalFetch2"),Cr=s(async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:i,fetch:a})=>N2({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:i,fetch:a}),"postJsonToApi");var N2=s(async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:i,fetch:a=P2()})=>{try{let l=await a(e,{method:"POST",headers:hn(t,`ai-sdk/provider-utils/${TI}`,Su()),body:r.content,signal:i}),d=Wa(l);if(!l.ok){let f;try{f=await o({response:l,url:e,requestBodyValues:r.values})}catch(m){throw mn(m)||Te.isInstance(m)?m:new Te({message:"Failed to process error response",cause:m,statusCode:l.status,url:e,responseHeaders:d,requestBodyValues:r.values})}throw f.value}try{return await n({response:l,url:e,requestBodyValues:r.values})}catch(f){throw f instanceof Error&&(mn(f)||Te.isInstance(f))?f:new Te({message:"Failed to process successful response",cause:f,statusCode:l.status,url:e,responseHeaders:d,requestBodyValues:r.values})}}catch(l){throw II({error:l,url:e,requestBodyValues:r.values})}},"postToApi");function L2(e){return{...e,type:"dynamic"}}s(L2,"dynamicTool");function xu({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:i,toModelOutput:a,onInputStart:l,onInputDelta:d,onInputAvailable:f,...m})=>({type:"provider",id:e,args:m,inputSchema:t,outputSchema:r,execute:o,needsApproval:i,toModelOutput:a,onInputStart:l,onInputDelta:d,onInputAvailable:f,supportsDeferredResults:n})}s(xu,"createProviderToolFactoryWithOutputSchema");async function Oe(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}s(Oe,"resolve");var pt=s(({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:i})=>{let a=await n.text(),l=Wa(n);if(a.trim()==="")return{responseHeaders:l,value:new Te({message:n.statusText,url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:l,responseBody:a,isRetryable:r?.(n)})};try{let d=await M2({text:a,schema:e});return{responseHeaders:l,value:new Te({message:t(d),url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:l,responseBody:a,data:d,isRetryable:r?.(n,d)})}}catch{return{responseHeaders:l,value:new Te({message:n.statusText,url:o,requestBodyValues:i,statusCode:n.status,responseHeaders:l,responseBody:a,isRetryable:r?.(n)})}}},"createJsonErrorResponseHandler"),MI=s(e=>async({response:t})=>{let r=Wa(t);if(t.body==null)throw new ld({});return{responseHeaders:r,value:wu({stream:t.body,schema:e})}},"createEventSourceResponseHandler"),Mt=s(e=>async({response:t,url:r,requestBodyValues:n})=>{let o=await t.text(),i=await _t({text:o,schema:e}),a=Wa(t);if(!i.success)throw new Te({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:i.value,rawValue:i.rawValue}},"createJsonResponseHandler");function PI(e){return e?.replace(/\/$/,"")}s(PI,"withoutTrailingSlash");function F2(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}s(F2,"isAsyncIterable");async function*NI({execute:e,input:t,options:r}){let n=e(t,r);if(F2(n)){let o;for await(let i of n)o=i,yield{type:"preliminary",output:i};yield{type:"final",output:o}}else yield{type:"final",output:await n}}s(NI,"executeTool");var bT=wr(vy(),1),ET=wr(vy(),1);var j2="vercel.ai.gateway.error",tm=Symbol.for(j2),LI,FI,Pt=class dT extends(FI=Error,LI=tm,FI){static{s(this,"_GatewayError")}constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[LI]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return dT.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&tm in t&&t[tm]===!0}},pT="GatewayAuthenticationError",U2=`vercel.ai.gateway.error.${pT}`,jI=Symbol.for(U2),UI,qI,bu=class fT extends(qI=Pt,UI=jI,qI){static{s(this,"_GatewayAuthenticationError")}constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[UI]=!0,this.name=pT,this.type="authentication_error"}static isInstance(t){return Pt.hasMarker(t)&&jI in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:i,generationId:a}){let l;return t?l=`AI Gateway authentication failed: Invalid API key.
733
+
734
+ Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
735
+
736
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?l=`AI Gateway authentication failed: Invalid OIDC token.
737
+
738
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
739
+
740
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:l=`AI Gateway authentication failed: No authentication provided.
741
+
742
+ Option 1 - API key:
743
+ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
744
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
745
+
746
+ Option 2 - OIDC token:
747
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new fT({message:l,statusCode:o,cause:i,generationId:a})}},mT="GatewayInvalidRequestError",q2=`vercel.ai.gateway.error.${mT}`,BI=Symbol.for(q2),$I,VI,B2=class extends(VI=Pt,$I=BI,VI){static{s(this,"GatewayInvalidRequestError")}constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[$I]=!0,this.name=mT,this.type="invalid_request_error"}static isInstance(e){return Pt.hasMarker(e)&&BI in e}},gT="GatewayRateLimitError",$2=`vercel.ai.gateway.error.${gT}`,HI=Symbol.for($2),WI,GI,V2=class extends(GI=Pt,WI=HI,GI){static{s(this,"GatewayRateLimitError")}constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[WI]=!0,this.name=gT,this.type="rate_limit_exceeded"}static isInstance(e){return Pt.hasMarker(e)&&HI in e}},hT="GatewayModelNotFoundError",H2=`vercel.ai.gateway.error.${hT}`,JI=Symbol.for(H2),W2=De(()=>xe(u.object({modelId:u.string()}))),zI,KI,G2=class extends(KI=Pt,zI=JI,KI){static{s(this,"GatewayModelNotFoundError")}constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[zI]=!0,this.name=hT,this.type="model_not_found",this.modelId=r}static isInstance(e){return Pt.hasMarker(e)&&JI in e}},yT="GatewayInternalServerError",J2=`vercel.ai.gateway.error.${yT}`,YI=Symbol.for(J2),XI,ZI,QI=class extends(ZI=Pt,XI=YI,ZI){static{s(this,"GatewayInternalServerError")}constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[XI]=!0,this.name=yT,this.type="internal_server_error"}static isInstance(e){return Pt.hasMarker(e)&&YI in e}},vT="GatewayResponseError",z2=`vercel.ai.gateway.error.${vT}`,eT=Symbol.for(z2),tT,rT,K2=class extends(rT=Pt,tT=eT,rT){static{s(this,"GatewayResponseError")}constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:i}={}){super({message:e,statusCode:t,cause:o,generationId:i}),this[tT]=!0,this.name=vT,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Pt.hasMarker(e)&&eT in e}};async function nT({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var i;let a=await st({value:e,schema:Y2});if(!a.success){let g=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new K2({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:a.error,cause:n,generationId:g})}let l=a.value,d=l.error.type,f=l.error.message,m=(i=l.generationId)!=null?i:void 0;switch(d){case"authentication_error":return bu.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:m});case"invalid_request_error":return new B2({message:f,statusCode:t,cause:n,generationId:m});case"rate_limit_exceeded":return new V2({message:f,statusCode:t,cause:n,generationId:m});case"model_not_found":{let g=await st({value:l.error.param,schema:W2});return new G2({message:f,statusCode:t,modelId:g.success?g.value.modelId:void 0,cause:n,generationId:m})}case"internal_server_error":return new QI({message:f,statusCode:t,cause:n,generationId:m});default:return new QI({message:f,statusCode:t,cause:n,generationId:m})}}s(nT,"createGatewayErrorFromResponse");var Y2=De(()=>xe(u.object({error:u.object({message:u.string(),type:u.string().nullish(),param:u.unknown().nullish(),code:u.union([u.string(),u.number()]).nullish()}),generationId:u.string().nullish()}))),ST="GatewayTimeoutError",X2=`vercel.ai.gateway.error.${ST}`,oT=Symbol.for(X2),sT,iT,aT=class wT extends(iT=Pt,sT=oT,iT){static{s(this,"_GatewayTimeoutError")}constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[sT]=!0,this.name=ST,this.type="timeout_error"}static isInstance(t){return Pt.hasMarker(t)&&oT in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){let i=`Gateway request timed out: ${t}
748
+
749
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new wT({message:i,statusCode:r,cause:n,generationId:o})}};function lT(e){if(!(e instanceof Error))return!1;let t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}s(lT,"isTimeoutError");async function Gt(e,t){var r;return Pt.isInstance(e)?e:lT(e)?aT.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):Te.isInstance(e)?e.cause&&lT(e.cause)?aT.createTimeoutError({originalMessage:e.message,cause:e}):await nT({response:Z2(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await nT({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}s(Gt,"asGatewayError");function Z2(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}s(Z2,"extractApiCallResponse");var xT="ai-gateway-auth-method";async function Jr(e){let t=await st({value:e[xT],schema:Q2});return t.success?t.value:void 0}s(Jr,"parseAuthMethod");var Q2=De(()=>xe(u.union([u.literal("api-key"),u.literal("oidc")]))),eq=["embedding","image","language","reranking","video"],cT=class{static{s(this,"GatewayFetchMetadata")}constructor(e){this.config=e}async getAvailableModels(){try{let{value:e}=await Jo({url:`${this.config.baseURL}/config`,headers:await Oe(this.config.headers()),successfulResponseHandler:Mt(tq),failedResponseHandler:pt({errorSchema:u.any(),errorToMessage:s(t=>t,"errorToMessage")}),fetch:this.config.fetch});return e}catch(e){throw await Gt(e)}}async getCredits(){try{let e=new URL(this.config.baseURL),{value:t}=await Jo({url:`${e.origin}/v1/credits`,headers:await Oe(this.config.headers()),successfulResponseHandler:Mt(rq),failedResponseHandler:pt({errorSchema:u.any(),errorToMessage:s(r=>r,"errorToMessage")}),fetch:this.config.fetch});return t}catch(e){throw await Gt(e)}}},tq=De(()=>xe(u.object({models:u.array(u.object({id:u.string(),name:u.string(),description:u.string().nullish(),pricing:u.object({input:u.string(),output:u.string(),input_cache_read:u.string().nullish(),input_cache_write:u.string().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:u.object({specificationVersion:u.literal("v3"),provider:u.string(),modelId:u.string()}),modelType:u.string().nullish()})).transform(e=>e.filter(t=>t.modelType==null||eq.includes(t.modelType)))}))),rq=De(()=>xe(u.object({balance:u.string(),total_used:u.string()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),nq=class{static{s(this,"GatewaySpendReport")}constructor(e){this.config=e}async getSpendReport(e){try{let t=new URL(this.config.baseURL),r=new URLSearchParams;r.set("start_date",e.startDate),r.set("end_date",e.endDate),e.groupBy&&r.set("group_by",e.groupBy),e.datePart&&r.set("date_part",e.datePart),e.userId&&r.set("user_id",e.userId),e.model&&r.set("model",e.model),e.provider&&r.set("provider",e.provider),e.credentialType&&r.set("credential_type",e.credentialType),e.tags&&e.tags.length>0&&r.set("tags",e.tags.join(","));let{value:n}=await Jo({url:`${t.origin}/v1/report?${r.toString()}`,headers:await Oe(this.config.headers()),successfulResponseHandler:Mt(oq),failedResponseHandler:pt({errorSchema:u.any(),errorToMessage:s(o=>o,"errorToMessage")}),fetch:this.config.fetch});return n}catch(t){throw await Gt(t)}}},oq=De(()=>xe(u.object({results:u.array(u.object({day:u.string().optional(),hour:u.string().optional(),user:u.string().optional(),model:u.string().optional(),tag:u.string().optional(),provider:u.string().optional(),credential_type:u.enum(["byok","system"]).optional(),total_cost:u.number(),market_cost:u.number().optional(),input_tokens:u.number().optional(),output_tokens:u.number().optional(),cached_input_tokens:u.number().optional(),cache_creation_input_tokens:u.number().optional(),reasoning_tokens:u.number().optional(),request_count:u.number().optional()}).transform(({credential_type:e,total_cost:t,market_cost:r,input_tokens:n,output_tokens:o,cached_input_tokens:i,cache_creation_input_tokens:a,reasoning_tokens:l,request_count:d,...f})=>({...f,...e!==void 0?{credentialType:e}:{},totalCost:t,...r!==void 0?{marketCost:r}:{},...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...i!==void 0?{cachedInputTokens:i}:{},...a!==void 0?{cacheCreationInputTokens:a}:{},...l!==void 0?{reasoningTokens:l}:{},...d!==void 0?{requestCount:d}:{}})))}))),sq=class{static{s(this,"GatewayGenerationInfoFetcher")}constructor(e){this.config=e}async getGenerationInfo(e){try{let t=new URL(this.config.baseURL),{value:r}=await Jo({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await Oe(this.config.headers()),successfulResponseHandler:Mt(iq),failedResponseHandler:pt({errorSchema:u.any(),errorToMessage:s(n=>n,"errorToMessage")}),fetch:this.config.fetch});return r}catch(t){throw await Gt(t)}}},iq=De(()=>xe(u.object({data:u.object({id:u.string(),total_cost:u.number(),upstream_inference_cost:u.number(),usage:u.number(),created_at:u.string(),model:u.string(),is_byok:u.boolean(),provider_name:u.string(),streamed:u.boolean(),finish_reason:u.string(),latency:u.number(),generation_time:u.number(),native_tokens_prompt:u.number(),native_tokens_completion:u.number(),native_tokens_reasoning:u.number(),native_tokens_cached:u.number(),native_tokens_cache_creation:u.number(),billable_web_search_calls:u.number()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:r,is_byok:n,provider_name:o,finish_reason:i,generation_time:a,native_tokens_prompt:l,native_tokens_completion:d,native_tokens_reasoning:f,native_tokens_cached:m,native_tokens_cache_creation:g,billable_web_search_calls:h,...y})=>({...y,totalCost:e,upstreamInferenceCost:t,createdAt:r,isByok:n,providerName:o,finishReason:i,generationTime:a,promptTokens:l,completionTokens:d,reasoningTokens:f,cachedTokens:m,cacheCreationTokens:g,billableWebSearchCalls:h}))}).transform(({data:e})=>e))),aq=class{static{s(this,"GatewayLanguageModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){let{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){let{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Oe(this.config.headers());try{let{responseHeaders:i,value:a,rawValue:l}=await Cr({url:this.getUrl(),headers:Rr(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Oe(this.config.o11yHeaders)),body:t,successfulResponseHandler:Mt(u.any()),failedResponseHandler:pt({errorSchema:u.any(),errorToMessage:s(d=>d,"errorToMessage")}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:i,body:l},warnings:r}}catch(i){throw await Gt(i,await Jr(o))}}async doStream(e){let{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Oe(this.config.headers());try{let{value:i,responseHeaders:a}=await Cr({url:this.getUrl(),headers:Rr(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Oe(this.config.o11yHeaders)),body:t,successfulResponseHandler:MI(u.any()),failedResponseHandler:pt({errorSchema:u.any(),errorToMessage:s(l=>l,"errorToMessage")}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:i.pipeThrough(new TransformStream({start(l){r.length>0&&l.enqueue({type:"stream-start",warnings:r})},transform(l,d){if(l.success){let f=l.value;if(f.type==="raw"&&!e.includeRawChunks)return;f.type==="response-metadata"&&f.timestamp&&typeof f.timestamp=="string"&&(f.timestamp=new Date(f.timestamp)),d.enqueue(f)}else d.error(l.error)}})),request:{body:t},response:{headers:a}}}catch(i){throw await Gt(i,await Jr(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(let t of e.prompt)for(let r of t.content)if(this.isFilePart(r)){let n=r;if(n.data instanceof Uint8Array){let o=Uint8Array.from(n.data),i=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${i}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},lq=class{static{s(this,"GatewayEmbeddingModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;let i=await Oe(this.config.headers());try{let{responseHeaders:a,value:l,rawValue:d}=await Cr({url:this.getUrl(),headers:Rr(i,t??{},this.getModelConfigHeaders(),await Oe(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Mt(cq),failedResponseHandler:pt({errorSchema:u.any(),errorToMessage:s(f=>f,"errorToMessage")}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:(o=l.usage)!=null?o:void 0,providerMetadata:l.providerMetadata,response:{headers:a,body:d},warnings:[]}}catch(a){throw await Gt(a,await Jr(i))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},cq=De(()=>xe(u.object({embeddings:u.array(u.array(u.number())),usage:u.object({tokens:u.number()}).nullish(),providerMetadata:u.record(u.string(),u.record(u.string(),u.unknown())).optional()}))),uq=class{static{s(this,"GatewayImageModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,files:i,mask:a,providerOptions:l,headers:d,abortSignal:f}){var m,g,h,y;let E=await Oe(this.config.headers());try{let{responseHeaders:w,value:v,rawValue:O}=await Cr({url:this.getUrl(),headers:Rr(E,d??{},this.getModelConfigHeaders(),await Oe(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...l&&{providerOptions:l},...i&&{files:i.map(k=>uT(k))},...a&&{mask:uT(a)}},successfulResponseHandler:Mt(mq),failedResponseHandler:pt({errorSchema:u.any(),errorToMessage:s(k=>k,"errorToMessage")}),...f&&{abortSignal:f},fetch:this.config.fetch});return{images:v.images,warnings:(m=v.warnings)!=null?m:[],providerMetadata:v.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:w},...v.usage!=null&&{usage:{inputTokens:(g=v.usage.inputTokens)!=null?g:void 0,outputTokens:(h=v.usage.outputTokens)!=null?h:void 0,totalTokens:(y=v.usage.totalTokens)!=null?y:void 0}}}}catch(w){throw await Gt(w,await Jr(E))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function uT(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:gn(e.data)}:e}s(uT,"maybeEncodeImageFile");var dq=u.object({images:u.array(u.unknown()).optional()}).catchall(u.unknown()),pq=u.discriminatedUnion("type",[u.object({type:u.literal("unsupported"),feature:u.string(),details:u.string().optional()}),u.object({type:u.literal("compatibility"),feature:u.string(),details:u.string().optional()}),u.object({type:u.literal("other"),message:u.string()})]),fq=u.object({inputTokens:u.number().nullish(),outputTokens:u.number().nullish(),totalTokens:u.number().nullish()}),mq=u.object({images:u.array(u.string()),warnings:u.array(pq).optional(),providerMetadata:u.record(u.string(),dq).optional(),usage:fq.optional()}),gq=class{static{s(this,"GatewayVideoModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:n,duration:o,fps:i,seed:a,image:l,providerOptions:d,headers:f,abortSignal:m}){var g;let h=await Oe(this.config.headers());try{let{responseHeaders:y,value:E}=await Cr({url:this.getUrl(),headers:Rr(h,f??{},this.getModelConfigHeaders(),await Oe(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...i&&{fps:i},...a&&{seed:a},...d&&{providerOptions:d},...l&&{image:hq(l)}},successfulResponseHandler:s(async({response:w,url:v,requestBodyValues:O})=>{if(w.body==null)throw new Te({message:"SSE response body is empty",url:v,requestBodyValues:O,statusCode:w.status});let S=wu({stream:w.body,schema:wq}).getReader(),{done:R,value:M}=await S.read();if(S.releaseLock(),R||!M)throw new Te({message:"SSE stream ended without a data event",url:v,requestBodyValues:O,statusCode:w.status});if(!M.success)throw new Te({message:"Failed to parse video SSE event",cause:M.error,url:v,requestBodyValues:O,statusCode:w.status});let C=M.value;if(C.type==="error")throw new Te({message:C.message,statusCode:C.statusCode,url:v,requestBodyValues:O,responseHeaders:Object.fromEntries([...w.headers]),responseBody:JSON.stringify(C),data:{error:{message:C.message,type:C.errorType,param:C.param}}});return{value:{videos:C.videos,warnings:C.warnings,providerMetadata:C.providerMetadata},responseHeaders:Object.fromEntries([...w.headers])}},"successfulResponseHandler"),failedResponseHandler:pt({errorSchema:u.any(),errorToMessage:s(w=>w,"errorToMessage")}),...m&&{abortSignal:m},fetch:this.config.fetch});return{videos:E.videos,warnings:(g=E.warnings)!=null?g:[],providerMetadata:E.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:y}}}catch(y){throw await Gt(y,await Jr(h))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function hq(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:gn(e.data)}:e}s(hq,"maybeEncodeVideoFile");var yq=u.object({videos:u.array(u.unknown()).optional()}).catchall(u.unknown()),vq=u.union([u.object({type:u.literal("url"),url:u.string(),mediaType:u.string()}),u.object({type:u.literal("base64"),data:u.string(),mediaType:u.string()})]),Sq=u.discriminatedUnion("type",[u.object({type:u.literal("unsupported"),feature:u.string(),details:u.string().optional()}),u.object({type:u.literal("compatibility"),feature:u.string(),details:u.string().optional()}),u.object({type:u.literal("other"),message:u.string()})]),wq=u.discriminatedUnion("type",[u.object({type:u.literal("result"),videos:u.array(vq),warnings:u.array(Sq).optional(),providerMetadata:u.record(u.string(),yq).optional()}),u.object({type:u.literal("error"),message:u.string(),errorType:u.string(),statusCode:u.number(),param:u.unknown().nullable()})]),xq=class{static{s(this,"GatewayRerankingModel")}constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doRerank({documents:e,query:t,topN:r,headers:n,abortSignal:o,providerOptions:i}){let a=await Oe(this.config.headers());try{let{responseHeaders:l,value:d,rawValue:f}=await Cr({url:this.getUrl(),headers:Rr(a,n??{},this.getModelConfigHeaders(),await Oe(this.config.o11yHeaders)),body:{documents:e,query:t,...r!=null?{topN:r}:{},...i?{providerOptions:i}:{}},successfulResponseHandler:Mt(bq),failedResponseHandler:pt({errorSchema:u.any(),errorToMessage:s(m=>m,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{ranking:d.ranking,providerMetadata:d.providerMetadata,response:{headers:l,body:f},warnings:[]}}catch(l){throw await Gt(l,await Jr(a))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"3","ai-model-id":this.modelId}}},bq=De(()=>xe(u.object({ranking:u.array(u.object({index:u.number(),relevanceScore:u.number()})),providerMetadata:u.record(u.string(),u.record(u.string(),u.unknown())).optional()}))),Eq=De(()=>xe(u.object({objective:u.string().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:u.array(u.string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:u.enum(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:u.number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:u.object({include_domains:u.array(u.string()).optional().describe("List of domains to include in search results."),exclude_domains:u.array(u.string()).optional().describe("List of domains to exclude from search results."),after_date:u.string().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:u.object({max_chars_per_result:u.number().optional().describe("Maximum characters per result."),max_chars_total:u.number().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:u.object({max_age_seconds:u.number().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),Iq=De(()=>xe(u.union([u.object({searchId:u.string(),results:u.array(u.object({url:u.string(),title:u.string(),excerpt:u.string(),publishDate:u.string().nullable().optional(),relevanceScore:u.number().optional()}))}),u.object({error:u.enum(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:u.number().optional(),message:u.string()})]))),Tq=xu({id:"gateway.parallel_search",inputSchema:Eq,outputSchema:Iq}),_q=s((e={})=>Tq(e),"parallelSearch"),Aq=De(()=>xe(u.object({query:u.union([u.string(),u.array(u.string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:u.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:u.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:u.number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:u.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:u.array(u.string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:u.array(u.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:u.string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:u.string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:u.string().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:u.string().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:u.enum(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),kq=De(()=>xe(u.union([u.object({results:u.array(u.object({title:u.string(),url:u.string(),snippet:u.string(),date:u.string().optional(),lastUpdated:u.string().optional()})),id:u.string()}),u.object({error:u.enum(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:u.number().optional(),message:u.string()})]))),Rq=xu({id:"gateway.perplexity_search",inputSchema:Aq,outputSchema:kq}),Cq=s((e={})=>Rq(e),"perplexitySearch"),Dq={parallelSearch:_q,perplexitySearch:Cq};async function Oq(){var e;return(e=(0,bT.getContext)().headers)==null?void 0:e["x-vercel-id"]}s(Oq,"getVercelRequestId");var Mq="3.0.104",Pq="0.0.1";function Nq(e={}){var t,r;let n=null,o=null,i=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5,a=0,l=(r=PI(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",d=s(async()=>{try{let k=await Lq(e);return hn({Authorization:`Bearer ${k.token}`,"ai-gateway-protocol-version":Pq,[xT]:k.authMethod,...e.headers},`ai-sdk/gateway/${Mq}`)}catch(k){throw bu.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:k})}},"getHeaders"),f=s(()=>{let k=yi({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),S=yi({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),R=yi({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),M=yi({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{let C=await Oq();return{...k&&{"ai-o11y-deployment-id":k},...S&&{"ai-o11y-environment":S},...R&&{"ai-o11y-region":R},...C&&{"ai-o11y-request-id":C},...M&&{"ai-o11y-project-id":M}}}},"createO11yHeaders"),m=s(k=>new aq(k,{provider:"gateway",baseURL:l,headers:d,fetch:e.fetch,o11yHeaders:f()}),"createLanguageModel"),g=s(async()=>{var k,S,R;let M=(R=(S=(k=e._internal)==null?void 0:k.currentDate)==null?void 0:S.call(k).getTime())!=null?R:Date.now();return(!n||M-a>i)&&(a=M,n=new cT({baseURL:l,headers:d,fetch:e.fetch}).getAvailableModels().then(C=>(o=C,C)).catch(async C=>{throw await Gt(C,await Jr(await d()))})),o?Promise.resolve(o):n},"getAvailableModels"),h=s(async()=>new cT({baseURL:l,headers:d,fetch:e.fetch}).getCredits().catch(async k=>{throw await Gt(k,await Jr(await d()))}),"getCredits"),y=s(async k=>new nq({baseURL:l,headers:d,fetch:e.fetch}).getSpendReport(k).catch(async S=>{throw await Gt(S,await Jr(await d()))}),"getSpendReport"),E=s(async k=>new sq({baseURL:l,headers:d,fetch:e.fetch}).getGenerationInfo(k).catch(async S=>{throw await Gt(S,await Jr(await d()))}),"getGenerationInfo"),w=s(function(k){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return m(k)},"provider");w.specificationVersion="v3",w.getAvailableModels=g,w.getCredits=h,w.getSpendReport=y,w.getGenerationInfo=E,w.imageModel=k=>new uq(k,{provider:"gateway",baseURL:l,headers:d,fetch:e.fetch,o11yHeaders:f()}),w.languageModel=m;let v=s(k=>new lq(k,{provider:"gateway",baseURL:l,headers:d,fetch:e.fetch,o11yHeaders:f()}),"createEmbeddingModel");w.embeddingModel=v,w.textEmbeddingModel=v,w.videoModel=k=>new gq(k,{provider:"gateway",baseURL:l,headers:d,fetch:e.fetch,o11yHeaders:f()});let O=s(k=>new xq(k,{provider:"gateway",baseURL:l,headers:d,fetch:e.fetch,o11yHeaders:f()}),"createRerankingModel");return w.rerankingModel=O,w.reranking=O,w.chat=w.languageModel,w.embedding=w.embeddingModel,w.image=w.imageModel,w.video=w.videoModel,w.tools=Dq,w}s(Nq,"createGatewayProvider");var IT=Nq();async function Lq(e){let t=yi({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await(0,ET.getVercelOidcToken)(),authMethod:"oidc"}}s(Lq,"getGatewayAuthToken");var D_=wr(fy(),1),xi=wr(fy(),1);var Fq=Object.defineProperty,jq=s((e,t)=>{for(var r in t)Fq(e,r,{get:t[r],enumerable:!0})},"__export"),NT="AI_InvalidArgumentError",LT=`vercel.ai.error.${NT}`,Uq=Symbol.for(LT),FT,$e=class extends X{static{s(this,"InvalidArgumentError")}constructor({parameter:e,value:t,message:r}){super({name:NT,message:`Invalid argument for parameter ${e}: ${r}`}),this[FT]=!0,this.parameter=e,this.value=t}static isInstance(e){return X.hasMarker(e,LT)}};FT=Uq;var qq="AI_InvalidStreamPartError",Bq=`vercel.ai.error.${qq}`,$q=Symbol.for(Bq),Vq;Vq=$q;var jT="AI_InvalidToolApprovalError",UT=`vercel.ai.error.${jT}`,Hq=Symbol.for(UT),qT,Wq=class extends X{static{s(this,"InvalidToolApprovalError")}constructor({approvalId:e}){super({name:jT,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[qT]=!0,this.approvalId=e}static isInstance(e){return X.hasMarker(e,UT)}};qT=Hq;var BT="AI_InvalidToolInputError",$T=`vercel.ai.error.${BT}`,Gq=Symbol.for($T),VT,um=class extends X{static{s(this,"InvalidToolInputError")}constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${rn(r)}`}){super({name:BT,message:n,cause:r}),this[VT]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return X.hasMarker(e,$T)}};VT=Gq;var HT="AI_ToolCallNotFoundForApprovalError",WT=`vercel.ai.error.${HT}`,Jq=Symbol.for(WT),GT,JT=class extends X{static{s(this,"ToolCallNotFoundForApprovalError")}constructor({toolCallId:e,approvalId:t}){super({name:HT,message:`Tool call "${e}" not found for approval request "${t}".`}),this[GT]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return X.hasMarker(e,WT)}};GT=Jq;var zT="AI_MissingToolResultsError",KT=`vercel.ai.error.${zT}`,zq=Symbol.for(KT),YT,TT=class extends X{static{s(this,"MissingToolResultsError")}constructor({toolCallIds:e}){super({name:zT,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[YT]=!0,this.toolCallIds=e}static isInstance(e){return X.hasMarker(e,KT)}};YT=zq;var Kq="AI_NoImageGeneratedError",Yq=`vercel.ai.error.${Kq}`,Xq=Symbol.for(Yq),Zq;Zq=Xq;var XT="AI_NoObjectGeneratedError",ZT=`vercel.ai.error.${XT}`,Qq=Symbol.for(ZT),QT,ar=class extends X{static{s(this,"NoObjectGeneratedError")}constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:i}){super({name:XT,message:e,cause:t}),this[QT]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=i}static isInstance(e){return X.hasMarker(e,ZT)}};QT=Qq;var e_="AI_NoOutputGeneratedError",t_=`vercel.ai.error.${e_}`,eB=Symbol.for(t_),r_,tB=class extends X{static{s(this,"NoOutputGeneratedError")}constructor({message:e="No output generated.",cause:t}={}){super({name:e_,message:e,cause:t}),this[r_]=!0}static isInstance(e){return X.hasMarker(e,t_)}};r_=eB;var rB="AI_NoSpeechGeneratedError",nB=`vercel.ai.error.${rB}`,oB=Symbol.for(nB),sB;sB=oB;var iB="AI_NoTranscriptGeneratedError",aB=`vercel.ai.error.${iB}`,lB=Symbol.for(aB),cB;cB=lB;var uB="AI_NoVideoGeneratedError",dB=`vercel.ai.error.${uB}`,pB=Symbol.for(dB),fB;fB=pB;var n_="AI_NoSuchToolError",o_=`vercel.ai.error.${n_}`,mB=Symbol.for(o_),s_,im=class extends X{static{s(this,"NoSuchToolError")}constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:n_,message:r}),this[s_]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return X.hasMarker(e,o_)}};s_=mB;var i_="AI_ToolCallRepairError",a_=`vercel.ai.error.${i_}`,gB=Symbol.for(a_),l_,hB=class extends X{static{s(this,"ToolCallRepairError")}constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${rn(e)}`}){super({name:i_,message:r,cause:e}),this[l_]=!0,this.originalError=t}static isInstance(e){return X.hasMarker(e,a_)}};l_=gB;var yB=class extends X{static{s(this,"UnsupportedModelVersionError")}constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},c_="AI_UIMessageStreamError",u_=`vercel.ai.error.${c_}`,vB=Symbol.for(u_),d_,vi=class extends X{static{s(this,"UIMessageStreamError")}constructor({chunkType:e,chunkId:t,message:r}){super({name:c_,message:r}),this[d_]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return X.hasMarker(e,u_)}};d_=vB;var SB="AI_InvalidDataContentError",wB=`vercel.ai.error.${SB}`,xB=Symbol.for(wB),bB;bB=xB;var p_="AI_InvalidMessageRoleError",f_=`vercel.ai.error.${p_}`,EB=Symbol.for(f_),m_,IB=class extends X{static{s(this,"InvalidMessageRoleError")}constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:p_,message:t}),this[m_]=!0,this.role=e}static isInstance(e){return X.hasMarker(e,f_)}};m_=EB;var g_="AI_MessageConversionError",h_=`vercel.ai.error.${g_}`,TB=Symbol.for(h_),y_,_B=class extends X{static{s(this,"MessageConversionError")}constructor({originalMessage:e,message:t}){super({name:g_,message:t}),this[y_]=!0,this.originalMessage=e}static isInstance(e){return X.hasMarker(e,h_)}};y_=TB;var v_="AI_RetryError",S_=`vercel.ai.error.${v_}`,AB=Symbol.for(S_),w_,_T=class extends X{static{s(this,"RetryError")}constructor({message:e,reason:t,errors:r}){super({name:v_,message:e}),this[w_]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return X.hasMarker(e,S_)}};w_=AB;function Ko(e){return e===void 0?[]:Array.isArray(e)?e:[e]}s(Ko,"asArray");async function zo(e){for(let t of Ko(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}s(zo,"notify");function kB({warning:e,provider:t,model:r}){let n=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let o=`${n} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${n} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${n} ${e.message}`;default:return`${n} ${JSON.stringify(e,null,2)}`}}s(kB,"formatWarning");var RB="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",AT=!1,Au=s(e=>{if(e.warnings.length===0)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}AT||(AT=!0,console.info(RB));for(let r of e.warnings)console.warn(kB({warning:r,provider:e.provider,model:e.model}))}},"logWarnings");function CB({provider:e,modelId:t}){Au({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}s(CB,"logV2CompatibilityWarning");function DB(e){return e.specificationVersion==="v3"?e:(CB({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{let o=await t.doGenerate(...n);return{...o,finishReason:x_(o.finishReason),usage:b_(o.usage)}};case"doStream":return async(...n)=>{let o=await t.doStream(...n);return{...o,stream:OB(o.stream)}};default:return t[r]}}}))}s(DB,"asLanguageModelV3");function OB(e){return e.pipeThrough(new TransformStream({transform(t,r){t.type==="finish"?r.enqueue({...t,finishReason:x_(t.finishReason),usage:b_(t.usage)}):r.enqueue(t)}}))}s(OB,"convertV2StreamToV3");function x_(e){return{unified:e==="unknown"?"other":e,raw:void 0}}s(x_,"convertV2FinishReasonToV3");function b_(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}s(b_,"convertV2UsageToV3");function ku(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){let t=e;throw new yB({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return DB(e)}return MB().languageModel(e)}s(ku,"resolveLanguageModel");function MB(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:IT}s(MB,"getGlobalProvider");function E_(e){if(e!=null)return typeof e=="number"?e:e.totalMs}s(E_,"getTotalTimeoutMs");function PB(e){if(!(e==null||typeof e=="number"))return e.stepMs}s(PB,"getStepTimeoutMs");function NB(e){if(!(e==null||typeof e=="number"))return e.chunkMs}s(NB,"getChunkTimeoutMs");var LB=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}];var FB=s(e=>{let t=typeof e=="string"?hi(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)},"stripID3");function jB(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?FB(e):e}s(jB,"stripID3TagsIfPresent");function UB({data:e,signatures:t}){let r=jB(e),n=typeof r=="string"?hi(r.substring(0,Math.min(r.length,24))):r;for(let o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((i,a)=>i===null||n[a]===i))return o.mediaType}s(UB,"detectMediaType");var I_="6.0.168",T_=s(async({url:e,maxBytes:t,abortSignal:r})=>{var n;let o=e.toString();Qf(o);try{let i=await fetch(o,{headers:hn({},`ai-sdk/${I_}`,Su()),signal:r});if(i.redirected&&Qf(i.url),!i.ok)throw new hr({url:o,statusCode:i.status,statusText:i.statusText});return{data:await bI({response:i,url:o,maxBytes:t??Zf}),mediaType:(n=i.headers.get("content-type"))!=null?n:void 0}}catch(i){throw hr.isInstance(i)?i:new hr({url:o,cause:i})}},"download"),qB=s((e=T_)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r))),"createDefaultDownloadFunction");function BB(e){try{let[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}s(BB,"splitDataUrl");var __=u.union([u.string(),u.instanceof(Uint8Array),u.instanceof(ArrayBuffer),u.custom(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function A_(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){let{mediaType:t,base64Content:r}=BB(e.toString());if(t==null||r==null)throw new X({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}s(A_,"convertToLanguageModelV3DataContent");function $B(e){return typeof e=="string"?e:e instanceof ArrayBuffer?gn(new Uint8Array(e)):gn(e)}s($B,"convertDataContentToBase64String");async function dm({prompt:e,supportedUrls:t,download:r=qB()}){let n=await HB(e.messages,r,t),o=new Map;for(let f of e.messages)if(f.role==="assistant"&&Array.isArray(f.content))for(let m of f.content)m.type==="tool-approval-request"&&"approvalId"in m&&"toolCallId"in m&&o.set(m.approvalId,m.toolCallId);let i=new Set;for(let f of e.messages)if(f.role==="tool"){for(let m of f.content)if(m.type==="tool-approval-response"){let g=o.get(m.approvalId);g&&i.add(g)}}let a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Ko(e.system).map(f=>({role:"system",content:f.content,providerOptions:f.providerOptions})):[],...e.messages.map(f=>VB({message:f,downloadedAssets:n}))],l=[];for(let f of a){if(f.role!=="tool"){l.push(f);continue}let m=l.at(-1);m?.role==="tool"?m.content.push(...f.content):l.push(f)}let d=new Set;for(let f of l)switch(f.role){case"assistant":{for(let m of f.content)m.type==="tool-call"&&!m.providerExecuted&&d.add(m.toolCallId);break}case"tool":{for(let m of f.content)m.type==="tool-result"&&d.delete(m.toolCallId);break}case"user":case"system":for(let m of i)d.delete(m);if(d.size>0)throw new TT({toolCallIds:Array.from(d)});break}for(let f of i)d.delete(f);if(d.size>0)throw new TT({toolCallIds:Array.from(d)});return l.filter(f=>f.role!=="tool"||f.content.length>0)}s(dm,"convertToLanguageModelPrompt");function VB({message:e,downloadedAssets:t}){let r=e.role;switch(r){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(n=>WB(n,t)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{let o=n.providerOptions;switch(n.type){case"file":{let{data:i,mediaType:a}=A_(n.data);return{type:"file",data:i,filename:n.filename,mediaType:a??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:kT(n.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:kT(n.output),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:e.providerOptions};default:{let n=r;throw new IB({role:n})}}}s(VB,"convertToLanguageModelMessage");async function HB(e,t,r){let n=e.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").map(i=>{var a;let l=(a=i.mediaType)!=null?a:i.type==="image"?"image/*":void 0,d=i.type==="image"?i.image:i.data;if(typeof d=="string")try{d=new URL(d)}catch{}return{mediaType:l,data:d}}).filter(i=>i.data instanceof URL).map(i=>({url:i.data,isUrlSupportedByModel:i.mediaType!=null&&AI({url:i.data.toString(),mediaType:i.mediaType,supportedUrls:r})})),o=await t(n);return Object.fromEntries(o.map((i,a)=>i==null?null:[n[a].url.toString(),{data:i.data,mediaType:i.mediaType}]).filter(i=>i!=null))}s(HB,"downloadAssets");function WB(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n,o=e.type;switch(o){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}let{data:i,mediaType:a}=A_(n),l=a??e.mediaType,d=i;if(d instanceof URL){let f=t[d.toString()];f&&(d=f.data,l??(l=f.mediaType))}switch(o){case"image":return(d instanceof Uint8Array||typeof d=="string")&&(l=(r=UB({data:d,signatures:LB}))!=null?r:l),{type:"file",mediaType:l??"image/*",filename:void 0,data:d,providerOptions:e.providerOptions};case"file":{if(l==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:l,filename:e.filename,data:d,providerOptions:e.providerOptions}}}}s(WB,"convertPartToLanguageModelPart");function kT(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}s(kT,"mapToolResultOutput");async function wi({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:rn(r)}:o==="json"?{type:"error-json",value:RT(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:RT(r)}}s(wi,"createToolModelOutput");function RT(e){return e===void 0?null:e}s(RT,"toJSONValue");function Ya({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:i,seed:a,stopSequences:l}){if(e!=null){if(!Number.isInteger(e))throw new $e({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new $e({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new $e({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new $e({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new $e({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new $e({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(i!=null&&typeof i!="number")throw new $e({parameter:"frequencyPenalty",value:i,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new $e({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:i,stopSequences:l,seed:a}}s(Ya,"prepareCallSettings");function GB(e){return e!=null&&Object.keys(e).length>0}s(GB,"isNonEmptyObject");async function JB({tools:e,toolChoice:t,activeTools:r}){if(!GB(e))return{tools:void 0,toolChoice:void 0};let n=r!=null?Object.entries(e).filter(([i])=>r.includes(i)):Object.entries(e),o=[];for(let[i,a]of n){let l=a.type;switch(l){case void 0:case"dynamic":case"function":o.push({type:"function",name:i,description:a.description,inputSchema:await ir(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:i,id:a.id,args:a.args});break;default:{let d=l;throw new Error(`Unsupported tool type: ${d}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}s(JB,"prepareToolsAndToolChoice");var Xa=u.lazy(()=>u.union([u.null(),u.string(),u.number(),u.boolean(),u.record(u.string(),Xa.optional()),u.array(Xa)])),W=u.record(u.string(),u.record(u.string(),Xa.optional())),k_=u.object({type:u.literal("text"),text:u.string(),providerOptions:W.optional()}),zB=u.object({type:u.literal("image"),image:u.union([__,u.instanceof(URL)]),mediaType:u.string().optional(),providerOptions:W.optional()}),R_=u.object({type:u.literal("file"),data:u.union([__,u.instanceof(URL)]),filename:u.string().optional(),mediaType:u.string(),providerOptions:W.optional()}),KB=u.object({type:u.literal("reasoning"),text:u.string(),providerOptions:W.optional()}),YB=u.object({type:u.literal("tool-call"),toolCallId:u.string(),toolName:u.string(),input:u.unknown(),providerOptions:W.optional(),providerExecuted:u.boolean().optional()}),XB=u.discriminatedUnion("type",[u.object({type:u.literal("text"),value:u.string(),providerOptions:W.optional()}),u.object({type:u.literal("json"),value:Xa,providerOptions:W.optional()}),u.object({type:u.literal("execution-denied"),reason:u.string().optional(),providerOptions:W.optional()}),u.object({type:u.literal("error-text"),value:u.string(),providerOptions:W.optional()}),u.object({type:u.literal("error-json"),value:Xa,providerOptions:W.optional()}),u.object({type:u.literal("content"),value:u.array(u.union([u.object({type:u.literal("text"),text:u.string(),providerOptions:W.optional()}),u.object({type:u.literal("media"),data:u.string(),mediaType:u.string()}),u.object({type:u.literal("file-data"),data:u.string(),mediaType:u.string(),filename:u.string().optional(),providerOptions:W.optional()}),u.object({type:u.literal("file-url"),url:u.string(),providerOptions:W.optional()}),u.object({type:u.literal("file-id"),fileId:u.union([u.string(),u.record(u.string(),u.string())]),providerOptions:W.optional()}),u.object({type:u.literal("image-data"),data:u.string(),mediaType:u.string(),providerOptions:W.optional()}),u.object({type:u.literal("image-url"),url:u.string(),providerOptions:W.optional()}),u.object({type:u.literal("image-file-id"),fileId:u.union([u.string(),u.record(u.string(),u.string())]),providerOptions:W.optional()}),u.object({type:u.literal("custom"),providerOptions:W.optional()})]))})]),C_=u.object({type:u.literal("tool-result"),toolCallId:u.string(),toolName:u.string(),output:XB,providerOptions:W.optional()}),ZB=u.object({type:u.literal("tool-approval-request"),approvalId:u.string(),toolCallId:u.string()}),QB=u.object({type:u.literal("tool-approval-response"),approvalId:u.string(),approved:u.boolean(),reason:u.string().optional()}),e$=u.object({role:u.literal("system"),content:u.string(),providerOptions:W.optional()}),t$=u.object({role:u.literal("user"),content:u.union([u.string(),u.array(u.union([k_,zB,R_]))]),providerOptions:W.optional()}),r$=u.object({role:u.literal("assistant"),content:u.union([u.string(),u.array(u.union([k_,R_,KB,YB,C_,ZB]))]),providerOptions:W.optional()}),n$=u.object({role:u.literal("tool"),content:u.array(u.union([C_,QB])),providerOptions:W.optional()}),o$=u.union([e$,t$,r$,n$]);async function pm(e){if(e.prompt==null&&e.messages==null)throw new Pn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Pn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!Ko(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new Pn({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new Pn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Pn({prompt:e,message:"messages must not be empty"});let r=await st({value:t,schema:u.array(o$)});if(!r.success)throw new Pn({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}s(pm,"standardizePrompt");function fm(e){if(!bu.isInstance(e))return e;let t=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new X({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
750
+
751
+ To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
752
+
753
+ Alternatively, you can use a provider module instead of the AI Gateway.
754
+
755
+ Learn more: \x1B[34m${r}\x1B[0m
756
+
757
+ `),{name:"GatewayAuthenticationError"})}s(fm,"wrapGatewayError");function Yo({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}s(Yo,"assembleOperationName");function mm({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((i,[a,l])=>{if(a==="timeout"){let d=E_(l);d!=null&&(i[`ai.settings.${a}`]=d)}else i[`ai.settings.${a}`]=l;return i},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((i,[a,l])=>(i[`ai.telemetry.metadata.${a}`]=l,i),{}),...Object.entries(n??{}).reduce((i,[a,l])=>(l!==void 0&&(i[`ai.request.headers.${a}`]=l),i),{})}}s(mm,"getBaseTelemetryAttributes");var s$={startSpan(){return Eu},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Eu);if(typeof r=="function")return r(Eu);if(typeof n=="function")return n(Eu)}},Eu={spanContext(){return i$},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},i$={traceId:"",spanId:"",traceFlags:0};function gm({isEnabled:e=!1,tracer:t}={}){return e?t||D_.trace.getTracer("ai"):s$}s(gm,"getTracer");async function Xo({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async i=>{let a=xi.context.active();try{let l=await xi.context.with(a,()=>n(i));return o&&i.end(),l}catch(l){try{O_(i,l)}finally{i.end()}throw l}})}s(Xo,"recordSpan");function O_(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:xi.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:xi.SpanStatusCode.ERROR})}s(O_,"recordErrorOnSpan");async function Nt({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};let r={};for(let[n,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;let i=await o.input();i!=null&&(r[n]=i);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;let i=await o.output();i!=null&&(r[n]=i);continue}r[n]=o}return r}s(Nt,"selectTelemetryAttributes");function hm(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?$B(r.data):r.data}:r)})))}s(hm,"stringifyForTelemetry");function a$(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}s(a$,"getGlobalTelemetryIntegrations");function l$(){let e=a$();return t=>{let r=Ko(t),n=[...e,...r];function o(i){let a=n.map(i).filter(Boolean);return async l=>{for(let d of a)try{await d(l)}catch{}}}return s(o,"createTelemetryComposite"),{onStart:o(i=>i.onStart),onStepStart:o(i=>i.onStepStart),onToolCallStart:o(i=>i.onToolCallStart),onToolCallFinish:o(i=>i.onToolCallFinish),onStepFinish:o(i=>i.onStepFinish),onFinish:o(i=>i.onFinish)}}}s(l$,"getGlobalTelemetryIntegration");function Tu(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:Dr(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}s(Tu,"asLanguageModelUsage");function Iu(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}s(Iu,"createNullLanguageModelUsage");function c$(e,t){var r,n,o,i,a,l,d,f,m,g;return{inputTokens:Dr(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:Dr((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:Dr((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheReadTokens),cacheWriteTokens:Dr((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(l=t.inputTokenDetails)==null?void 0:l.cacheWriteTokens)},outputTokens:Dr(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:Dr((d=e.outputTokenDetails)==null?void 0:d.textTokens,(f=t.outputTokenDetails)==null?void 0:f.textTokens),reasoningTokens:Dr((m=e.outputTokenDetails)==null?void 0:m.reasoningTokens,(g=t.outputTokenDetails)==null?void 0:g.reasoningTokens)},totalTokens:Dr(e.totalTokens,t.totalTokens),reasoningTokens:Dr(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Dr(e.cachedInputTokens,t.cachedInputTokens)}}s(c$,"addLanguageModelUsage");function Dr(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}s(Dr,"addTokenCounts");function ym(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let o=t[n];if(o===void 0)continue;let i=n in e?e[n]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),l=i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp);a&&l?r[n]=ym(i,o):r[n]=o}return r}s(ym,"mergeObjects");function u$({error:e,exponentialBackoffDelay:t}){let r=e.responseHeaders;if(!r)return t;let n,o=r["retry-after-ms"];if(o){let a=parseFloat(o);Number.isNaN(a)||(n=a)}let i=r["retry-after"];if(i&&n===void 0){let a=parseFloat(i);Number.isNaN(a)?n=Date.parse(i)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}s(u$,"getRetryDelayInMs");var d$=s(({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>M_(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n}),"retryWithExponentialBackoffRespectingRetryHeaders");async function M_(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},i=[]){try{return await e()}catch(a){if(mn(a)||t===0)throw a;let l=Ga(a),d=[...i,a],f=d.length;if(f>t)throw new _T({message:`Failed after ${f} attempts. Last error: ${l}`,reason:"maxRetriesExceeded",errors:d});if(a instanceof Error&&Te.isInstance(a)&&a.isRetryable===!0&&f<=t)return await SI(u$({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),M_(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},d);throw f===1?a:new _T({message:`Failed after ${f} attempts with non-retryable error: '${l}'`,reason:"errorNotRetryable",errors:d})}}s(M_,"_retryWithExponentialBackoff");function vm({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new $e({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new $e({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}let r=e??2;return{maxRetries:r,retry:d$({maxRetries:r,abortSignal:t})}}s(vm,"prepareRetries");function p$({messages:e}){let t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};let r={};for(let d of e)if(d.role==="assistant"&&typeof d.content!="string"){let f=d.content;for(let m of f)m.type==="tool-call"&&(r[m.toolCallId]=m)}let n={};for(let d of e)if(d.role==="assistant"&&typeof d.content!="string"){let f=d.content;for(let m of f)m.type==="tool-approval-request"&&(n[m.approvalId]=m)}let o={};for(let d of t.content)d.type==="tool-result"&&(o[d.toolCallId]=d);let i=[],a=[],l=t.content.filter(d=>d.type==="tool-approval-response");for(let d of l){let f=n[d.approvalId];if(f==null)throw new Wq({approvalId:d.approvalId});if(o[f.toolCallId]!=null)continue;let m=r[f.toolCallId];if(m==null)throw new JT({toolCallId:f.toolCallId,approvalId:f.approvalId});let g={approvalRequest:f,approvalResponse:d,toolCall:m};d.approved?i.push(g):a.push(g)}return{approvedToolApprovals:i,deniedToolApprovals:a}}s(p$,"collectToolApprovals");function Ka(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}s(Ka,"now");async function P_({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:i,experimental_context:a,stepNumber:l,model:d,onPreliminaryToolResult:f,onToolCallStart:m,onToolCallFinish:g}){let{toolName:h,toolCallId:y,input:E}=e,w=t?.[h];if(w?.execute==null)return;let v={stepNumber:l,model:d,toolCall:e,messages:o,abortSignal:i,functionId:n?.functionId,metadata:n?.metadata,experimental_context:a};return Xo({name:"ai.toolCall",attributes:Nt({telemetry:n,attributes:{...Yo({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":h,"ai.toolCall.id":y,"ai.toolCall.args":{output:s(()=>JSON.stringify(E),"output")}}}),tracer:r,fn:s(async O=>{let k;await zo({event:v,callbacks:m});let S=Ka();try{let M=NI({execute:w.execute.bind(w),input:E,options:{toolCallId:y,messages:o,abortSignal:i,experimental_context:a}});for await(let C of M)C.type==="preliminary"?f?.({...e,type:"tool-result",output:C.output,preliminary:!0}):k=C.output}catch(M){let C=Ka()-S;return await zo({event:{...v,success:!1,error:M,durationMs:C},callbacks:g}),O_(O,M),{type:"tool-error",toolCallId:y,toolName:h,input:E,error:M,dynamic:w.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}let R=Ka()-S;await zo({event:{...v,success:!0,output:k,durationMs:R},callbacks:g});try{O.setAttributes(await Nt({telemetry:n,attributes:{"ai.toolCall.result":{output:s(()=>JSON.stringify(k),"output")}}}))}catch{}return{type:"tool-result",toolCallId:y,toolName:h,input:E,output:k,dynamic:w.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}},"fn")})}s(P_,"executeToolCall");function f$(e){let t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
758
+ `)}s(f$,"extractReasoningContent");function m$(e){let t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}s(m$,"extractTextContent");var g$=class{static{s(this,"DefaultGeneratedFile")}constructor({data:e,mediaType:t}){let r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=gn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=hi(this.base64Data)),this.uint8ArrayData}},h$=class extends g${static{s(this,"DefaultGeneratedFileWithType")}constructor(e){super(e),this.type="file"}};async function y$({tool:e,toolCall:t,messages:r,experimental_context:n}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:n})}s(y$,"isApprovalNeeded");var v$={};jq(v$,{array:s(()=>x$,"array"),choice:s(()=>b$,"choice"),json:s(()=>E$,"json"),object:s(()=>w$,"object"),text:s(()=>am,"text")});function S$(e){let t=["ROOT"],r=-1,n=null;function o(d,f,m){switch(d){case'"':{r=f,t.pop(),t.push(m),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=f,n=f,t.pop(),t.push(m),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(m),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=f,t.pop(),t.push(m),t.push("INSIDE_NUMBER");break}case"{":{r=f,t.pop(),t.push(m),t.push("INSIDE_OBJECT_START");break}case"[":{r=f,t.pop(),t.push(m),t.push("INSIDE_ARRAY_START");break}}}s(o,"processValueStart");function i(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=f,t.pop();break}}}s(i,"processAfterObjectValue");function a(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=f,t.pop();break}}}s(a,"processAfterArrayValue");for(let d=0;d<e.length;d++){let f=e[d];switch(t[t.length-1]){case"ROOT":o(f,d,"FINISH");break;case"INSIDE_OBJECT_START":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=d,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{f==='"'&&(t.pop(),t.push("INSIDE_OBJECT_KEY"));break}case"INSIDE_OBJECT_KEY":{f==='"'&&(t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY"));break}case"INSIDE_OBJECT_AFTER_KEY":{f===":"&&(t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE"));break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(f,d,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(f,d);break}case"INSIDE_STRING":{switch(f){case'"':{t.pop(),r=d;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=d}break}case"INSIDE_ARRAY_START":{f==="]"?(r=d,t.pop()):(r=d,o(f,d,"INSIDE_ARRAY_AFTER_VALUE"));break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(f){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=d,t.pop();break}default:{r=d;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(f,d,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=d;break}case"INSIDE_NUMBER":{switch(f){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=d;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(f,d),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(f,d);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(f,d);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(f,d);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{let g=e.substring(n,d+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(f,d):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(f,d)):r=d;break}}}let l=e.slice(0,r+1);for(let d=t.length-1;d>=0;d--)switch(t[d]){case"INSIDE_STRING":{l+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{l+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{l+="]";break}case"INSIDE_LITERAL":{let m=e.substring(n,e.length);"true".startsWith(m)?l+="true".slice(m.length):"false".startsWith(m)?l+="false".slice(m.length):"null".startsWith(m)&&(l+="null".slice(m.length))}}return l}s(S$,"fixJson");async function bi(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await _t({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await _t({text:S$(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}s(bi,"parsePartialJson");var am=s(()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),"text"),w$=s(({schema:e,name:t,description:r})=>{let n=ir(e);return{name:"object",responseFormat:Oe(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},i){let a=await _t({text:o});if(!a.success)throw new ar({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:i.response,usage:i.usage,finishReason:i.finishReason});let l=await st({value:a.value,schema:n});if(!l.success)throw new ar({message:"No object generated: response did not match schema.",cause:l.error,text:o,response:i.response,usage:i.usage,finishReason:i.finishReason});return l.value},async parsePartialOutput({text:o}){let i=await bi(o);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:i.value}}},createElementStreamTransform(){}}},"object"),x$=s(({element:e,name:t,description:r})=>{let n=ir(e);return{name:"array",responseFormat:Oe(n.jsonSchema).then(o=>{let{$schema:i,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},i){let a=await _t({text:o});if(!a.success)throw new ar({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:i.response,usage:i.usage,finishReason:i.finishReason});let l=a.value;if(l==null||typeof l!="object"||!("elements"in l)||!Array.isArray(l.elements))throw new ar({message:"No object generated: response did not match schema.",cause:new ze({value:l,cause:"response must be an object with an elements array"}),text:o,response:i.response,usage:i.usage,finishReason:i.finishReason});for(let d of l.elements){let f=await st({value:d,schema:n});if(!f.success)throw new ar({message:"No object generated: response did not match schema.",cause:f.error,text:o,response:i.response,usage:i.usage,finishReason:i.finishReason})}return l.elements},async parsePartialOutput({text:o}){let i=await bi(o);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let a=i.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;let l=i.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,d=[];for(let f of l){let m=await st({value:f,schema:n});m.success&&d.push(m.value)}return{partial:d}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:i},a){if(i!=null)for(;o<i.length;o++)a.enqueue(i[o])}})}}},"array"),b$=s(({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){let i=await _t({text:n});if(!i.success)throw new ar({message:"No object generated: could not parse the response.",cause:i.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});let a=i.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new ar({message:"No object generated: response did not match schema.",cause:new ze({value:a,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:n}){let o=await bi(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let i=o.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string")return;let a=e.filter(l=>l.startsWith(i.result));return o.state==="successful-parse"?a.includes(i.result)?{partial:i.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),"choice"),E$=s(({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:r},n){let o=await _t({text:r});if(!o.success)throw new ar({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){let n=await bi(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}}),"json");async function I$({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var i;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await N_(e);throw new im({toolName:e.toolName})}try{return await CT({toolCall:e,tools:t})}catch(a){if(r==null||!(im.isInstance(a)||um.isInstance(a)))throw a;let l=null;try{l=await r({toolCall:e,tools:t,inputSchema:s(async({toolName:d})=>{let{inputSchema:f}=t[d];return await ir(f).jsonSchema},"inputSchema"),system:n,messages:o,error:a})}catch(d){throw new hB({cause:d,originalError:a})}if(l==null)throw a;return await CT({toolCall:l,tools:t})}}catch(a){let l=await _t({text:e.input}),d=l.success?l.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:d,dynamic:!0,invalid:!0,error:a,title:(i=t?.[e.toolName])==null?void 0:i.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}s(I$,"parseToolCall");async function N_(e){let t=e.input.trim()===""?{success:!0,value:{}}:await _t({text:e.input});if(t.success===!1)throw new um({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}s(N_,"parseProviderExecutedDynamicToolCall");async function CT({toolCall:e,tools:t}){let r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await N_(e);throw new im({toolName:e.toolName,availableTools:Object.keys(t)})}let o=ir(n.inputSchema),i=e.input.trim()===""?await st({value:{},schema:o}):await _t({text:e.input,schema:o});if(i.success===!1)throw new um({toolName:r,toolInput:e.input,cause:i.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:n.title}}s(CT,"doParseToolCall");var T$=class{static{s(this,"DefaultStepResult")}constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:i,finishReason:a,rawFinishReason:l,usage:d,warnings:f,request:m,response:g,providerMetadata:h}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=n,this.experimental_context=o,this.content=i,this.finishReason=a,this.rawFinishReason=l,this.usage=d,this.warnings=f,this.request=m,this.response=g,this.providerMetadata=h}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function _$(e){return({steps:t})=>t.length===e}s(_$,"stepCountIs");async function A$({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}s(A$,"isStopConditionMet");async function DT({content:e,tools:t}){let r=[],n=[];for(let i of e)if(i.type!=="source"&&!((i.type==="tool-result"||i.type==="tool-error")&&!i.providerExecuted)&&!(i.type==="text"&&i.text.length===0))switch(i.type){case"text":n.push({type:"text",text:i.text,providerOptions:i.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:i.text,providerOptions:i.providerMetadata});break;case"file":n.push({type:"file",data:i.file.base64,mediaType:i.file.mediaType,providerOptions:i.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.invalid&&typeof i.input!="object"?{}:i.input,providerExecuted:i.providerExecuted,providerOptions:i.providerMetadata});break;case"tool-result":{let a=await wi({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:a,providerOptions:i.providerMetadata});break}case"tool-error":{let a=await wi({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:a,providerOptions:i.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:i.approvalId,toolCallId:i.toolCall.toolCallId});break}n.length>0&&r.push({role:"assistant",content:n});let o=[];for(let i of e){if(!(i.type==="tool-result"||i.type==="tool-error")||i.providerExecuted)continue;let a=await wi({toolCallId:i.toolCallId,input:i.input,tool:t?.[i.toolName],output:i.type==="tool-result"?i.output:i.error,errorMode:i.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:a,...i.providerMetadata!=null?{providerOptions:i.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}s(DT,"toResponseMessages");function k$(...e){let t=e.filter(n=>n!=null);if(t.length===0)return;if(t.length===1)return t[0];let r=new AbortController;for(let n of t){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}s(k$,"mergeAbortSignals");var _Q=Gr({prefix:"aitxt",size:24});function Za(e,t){let r=new Headers(e??{});for(let[n,o]of Object.entries(t))r.has(n)||r.set(n,o);return r}s(Za,"prepareHeaders");function L_({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Za(r,{"content-type":"text/plain; charset=utf-8"})})}s(L_,"createTextStreamResponse");function F_({response:e,status:t,statusText:r,headers:n,stream:o}){let i=t??200;r!==void 0?e.writeHead(i,r,n):e.writeHead(i,n);let a=o.getReader();s(async()=>{try{for(;;){let{done:d,value:f}=await a.read();if(d)break;e.write(f)||await new Promise(g=>{e.once("drain",g)})}}catch(d){throw d}finally{e.end()}},"read")()}s(F_,"writeToServerResponse");function j_({response:e,status:t,statusText:r,headers:n,textStream:o}){F_({response:e,status:t,statusText:r,headers:Object.fromEntries(Za(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}s(j_,"pipeTextStreamToResponse");var U_=class extends TransformStream{static{s(this,"JsonToSseTransformStream")}constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
759
+
760
+ `)},flush(e){e.enqueue(`data: [DONE]
761
+
762
+ `)}})}},q_={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function R$({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let i=n.pipeThrough(new U_);if(o){let[a,l]=i.tee();i=a,o({stream:l})}return new Response(i.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Za(r,q_)})}s(R$,"createUIMessageStreamResponse");function C$({originalMessages:e,responseMessageId:t}){if(e==null)return;let r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}s(C$,"getResponseUIMessageId");var OQ=De(()=>xe(u.union([u.strictObject({type:u.literal("text-start"),id:u.string(),providerMetadata:W.optional()}),u.strictObject({type:u.literal("text-delta"),id:u.string(),delta:u.string(),providerMetadata:W.optional()}),u.strictObject({type:u.literal("text-end"),id:u.string(),providerMetadata:W.optional()}),u.strictObject({type:u.literal("error"),errorText:u.string()}),u.strictObject({type:u.literal("tool-input-start"),toolCallId:u.string(),toolName:u.string(),providerExecuted:u.boolean().optional(),providerMetadata:W.optional(),dynamic:u.boolean().optional(),title:u.string().optional()}),u.strictObject({type:u.literal("tool-input-delta"),toolCallId:u.string(),inputTextDelta:u.string()}),u.strictObject({type:u.literal("tool-input-available"),toolCallId:u.string(),toolName:u.string(),input:u.unknown(),providerExecuted:u.boolean().optional(),providerMetadata:W.optional(),dynamic:u.boolean().optional(),title:u.string().optional()}),u.strictObject({type:u.literal("tool-input-error"),toolCallId:u.string(),toolName:u.string(),input:u.unknown(),providerExecuted:u.boolean().optional(),providerMetadata:W.optional(),dynamic:u.boolean().optional(),errorText:u.string(),title:u.string().optional()}),u.strictObject({type:u.literal("tool-approval-request"),approvalId:u.string(),toolCallId:u.string()}),u.strictObject({type:u.literal("tool-output-available"),toolCallId:u.string(),output:u.unknown(),providerExecuted:u.boolean().optional(),providerMetadata:W.optional(),dynamic:u.boolean().optional(),preliminary:u.boolean().optional()}),u.strictObject({type:u.literal("tool-output-error"),toolCallId:u.string(),errorText:u.string(),providerExecuted:u.boolean().optional(),providerMetadata:W.optional(),dynamic:u.boolean().optional()}),u.strictObject({type:u.literal("tool-output-denied"),toolCallId:u.string()}),u.strictObject({type:u.literal("reasoning-start"),id:u.string(),providerMetadata:W.optional()}),u.strictObject({type:u.literal("reasoning-delta"),id:u.string(),delta:u.string(),providerMetadata:W.optional()}),u.strictObject({type:u.literal("reasoning-end"),id:u.string(),providerMetadata:W.optional()}),u.strictObject({type:u.literal("source-url"),sourceId:u.string(),url:u.string(),title:u.string().optional(),providerMetadata:W.optional()}),u.strictObject({type:u.literal("source-document"),sourceId:u.string(),mediaType:u.string(),title:u.string(),filename:u.string().optional(),providerMetadata:W.optional()}),u.strictObject({type:u.literal("file"),url:u.string(),mediaType:u.string(),providerMetadata:W.optional()}),u.strictObject({type:u.custom(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:u.string().optional(),data:u.unknown(),transient:u.boolean().optional()}),u.strictObject({type:u.literal("start-step")}),u.strictObject({type:u.literal("finish-step")}),u.strictObject({type:u.literal("start"),messageId:u.string().optional(),messageMetadata:u.unknown().optional()}),u.strictObject({type:u.literal("finish"),finishReason:u.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:u.unknown().optional()}),u.strictObject({type:u.literal("abort"),reason:u.string().optional()}),u.strictObject({type:u.literal("message-metadata"),messageMetadata:u.unknown()})])));function D$(e){return e.type.startsWith("data-")}s(D$,"isDataUIMessageChunk");function rm(e){return e.type.startsWith("data-")}s(rm,"isDataUIPart");function nm(e){return e.type==="text"}s(nm,"isTextUIPart");function om(e){return e.type==="file"}s(om,"isFileUIPart");function OT(e){return e.type==="reasoning"}s(OT,"isReasoningUIPart");function lm(e){return e.type.startsWith("tool-")}s(lm,"isStaticToolUIPart");function B_(e){return e.type==="dynamic-tool"}s(B_,"isDynamicToolUIPart");function Si(e){return lm(e)||B_(e)}s(Si,"isToolUIPart");function cm(e){return e.type.split("-").slice(1).join("-")}s(cm,"getStaticToolName");function sm(e){return B_(e)?e.toolName:cm(e)}s(sm,"getToolName");function O$({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}s(O$,"createStreamingUIMessageState");function M$({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:i,onData:a}){return e.pipeThrough(new TransformStream({async transform(l,d){await n(async({state:f,write:m})=>{var g,h,y,E;function w(S){let M=f.message.parts.filter(Si).find(C=>C.toolCallId===S);if(M==null)throw new vi({chunkType:"tool-invocation",chunkId:S,message:`No tool invocation found for tool call ID "${S}".`});return M}s(w,"getToolInvocation");function v(S){var R;let M=f.message.parts.find(_=>lm(_)&&_.toolCallId===S.toolCallId),C=S,x=M;if(M!=null){M.state=S.state,x.input=C.input,x.output=C.output,x.errorText=C.errorText,x.rawInput=C.rawInput,x.preliminary=C.preliminary,S.title!==void 0&&(x.title=S.title),x.providerExecuted=(R=C.providerExecuted)!=null?R:M.providerExecuted;let _=C.providerMetadata;if(_!=null)if(S.state==="output-available"||S.state==="output-error"){let T=M;T.resultProviderMetadata=_}else M.callProviderMetadata=_}else f.message.parts.push({type:`tool-${S.toolName}`,toolCallId:S.toolCallId,state:S.state,title:S.title,input:C.input,output:C.output,rawInput:C.rawInput,errorText:C.errorText,providerExecuted:C.providerExecuted,preliminary:C.preliminary,...C.providerMetadata!=null&&(S.state==="output-available"||S.state==="output-error")?{resultProviderMetadata:C.providerMetadata}:{},...C.providerMetadata!=null&&!(S.state==="output-available"||S.state==="output-error")?{callProviderMetadata:C.providerMetadata}:{}})}s(v,"updateToolPart");function O(S){var R,M;let C=f.message.parts.find(T=>T.type==="dynamic-tool"&&T.toolCallId===S.toolCallId),x=S,_=C;if(C!=null){C.state=S.state,_.toolName=S.toolName,_.input=x.input,_.output=x.output,_.errorText=x.errorText,_.rawInput=(R=x.rawInput)!=null?R:_.rawInput,_.preliminary=x.preliminary,S.title!==void 0&&(_.title=S.title),_.providerExecuted=(M=x.providerExecuted)!=null?M:C.providerExecuted;let T=x.providerMetadata;if(T!=null)if(S.state==="output-available"||S.state==="output-error"){let b=C;b.resultProviderMetadata=T}else C.callProviderMetadata=T}else f.message.parts.push({type:"dynamic-tool",toolName:S.toolName,toolCallId:S.toolCallId,state:S.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,title:S.title,...x.providerMetadata!=null&&(S.state==="output-available"||S.state==="output-error")?{resultProviderMetadata:x.providerMetadata}:{},...x.providerMetadata!=null&&!(S.state==="output-available"||S.state==="output-error")?{callProviderMetadata:x.providerMetadata}:{}})}s(O,"updateDynamicToolPart");async function k(S){if(S!=null){let R=f.message.metadata!=null?ym(f.message.metadata,S):S;t!=null&&await za({value:R,schema:t,context:{field:"message.metadata",entityId:f.message.id}}),f.message.metadata=R}}switch(s(k,"updateMessageMetadata"),l.type){case"text-start":{let S={type:"text",text:"",providerMetadata:l.providerMetadata,state:"streaming"};f.activeTextParts[l.id]=S,f.message.parts.push(S),m();break}case"text-delta":{let S=f.activeTextParts[l.id];if(S==null)throw new vi({chunkType:"text-delta",chunkId:l.id,message:`Received text-delta for missing text part with ID "${l.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});S.text+=l.delta,S.providerMetadata=(g=l.providerMetadata)!=null?g:S.providerMetadata,m();break}case"text-end":{let S=f.activeTextParts[l.id];if(S==null)throw new vi({chunkType:"text-end",chunkId:l.id,message:`Received text-end for missing text part with ID "${l.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});S.state="done",S.providerMetadata=(h=l.providerMetadata)!=null?h:S.providerMetadata,delete f.activeTextParts[l.id],m();break}case"reasoning-start":{let S={type:"reasoning",text:"",providerMetadata:l.providerMetadata,state:"streaming"};f.activeReasoningParts[l.id]=S,f.message.parts.push(S),m();break}case"reasoning-delta":{let S=f.activeReasoningParts[l.id];if(S==null)throw new vi({chunkType:"reasoning-delta",chunkId:l.id,message:`Received reasoning-delta for missing reasoning part with ID "${l.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});S.text+=l.delta,S.providerMetadata=(y=l.providerMetadata)!=null?y:S.providerMetadata,m();break}case"reasoning-end":{let S=f.activeReasoningParts[l.id];if(S==null)throw new vi({chunkType:"reasoning-end",chunkId:l.id,message:`Received reasoning-end for missing reasoning part with ID "${l.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});S.providerMetadata=(E=l.providerMetadata)!=null?E:S.providerMetadata,S.state="done",delete f.activeReasoningParts[l.id],m();break}case"file":{f.message.parts.push({type:"file",mediaType:l.mediaType,url:l.url,...l.providerMetadata!=null?{providerMetadata:l.providerMetadata}:{}}),m();break}case"source-url":{f.message.parts.push({type:"source-url",sourceId:l.sourceId,url:l.url,title:l.title,providerMetadata:l.providerMetadata}),m();break}case"source-document":{f.message.parts.push({type:"source-document",sourceId:l.sourceId,mediaType:l.mediaType,title:l.title,filename:l.filename,providerMetadata:l.providerMetadata}),m();break}case"tool-input-start":{let S=f.message.parts.filter(lm);f.partialToolCalls[l.toolCallId]={text:"",toolName:l.toolName,index:S.length,dynamic:l.dynamic,title:l.title},l.dynamic?O({toolCallId:l.toolCallId,toolName:l.toolName,state:"input-streaming",input:void 0,providerExecuted:l.providerExecuted,title:l.title,providerMetadata:l.providerMetadata}):v({toolCallId:l.toolCallId,toolName:l.toolName,state:"input-streaming",input:void 0,providerExecuted:l.providerExecuted,title:l.title,providerMetadata:l.providerMetadata}),m();break}case"tool-input-delta":{let S=f.partialToolCalls[l.toolCallId];if(S==null)throw new vi({chunkType:"tool-input-delta",chunkId:l.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${l.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});S.text+=l.inputTextDelta;let{value:R}=await bi(S.text);S.dynamic?O({toolCallId:l.toolCallId,toolName:S.toolName,state:"input-streaming",input:R,title:S.title}):v({toolCallId:l.toolCallId,toolName:S.toolName,state:"input-streaming",input:R,title:S.title}),m();break}case"tool-input-available":{l.dynamic?O({toolCallId:l.toolCallId,toolName:l.toolName,state:"input-available",input:l.input,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,title:l.title}):v({toolCallId:l.toolCallId,toolName:l.toolName,state:"input-available",input:l.input,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,title:l.title}),m(),i&&!l.providerExecuted&&await i({toolCall:l});break}case"tool-input-error":{let S=f.message.parts.filter(Si).find(M=>M.toolCallId===l.toolCallId);(S!=null?S.type==="dynamic-tool":!!l.dynamic)?O({toolCallId:l.toolCallId,toolName:l.toolName,state:"output-error",input:l.input,errorText:l.errorText,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata}):v({toolCallId:l.toolCallId,toolName:l.toolName,state:"output-error",input:void 0,rawInput:l.input,errorText:l.errorText,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata}),m();break}case"tool-approval-request":{let S=w(l.toolCallId);S.state="approval-requested",S.approval={id:l.approvalId},m();break}case"tool-output-denied":{let S=w(l.toolCallId);S.state="output-denied",m();break}case"tool-output-available":{let S=w(l.toolCallId);S.type==="dynamic-tool"?O({toolCallId:l.toolCallId,toolName:S.toolName,state:"output-available",input:S.input,output:l.output,preliminary:l.preliminary,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,title:S.title}):v({toolCallId:l.toolCallId,toolName:cm(S),state:"output-available",input:S.input,output:l.output,providerExecuted:l.providerExecuted,preliminary:l.preliminary,providerMetadata:l.providerMetadata,title:S.title}),m();break}case"tool-output-error":{let S=w(l.toolCallId);S.type==="dynamic-tool"?O({toolCallId:l.toolCallId,toolName:S.toolName,state:"output-error",input:S.input,errorText:l.errorText,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,title:S.title}):v({toolCallId:l.toolCallId,toolName:cm(S),state:"output-error",input:S.input,rawInput:S.rawInput,errorText:l.errorText,providerExecuted:l.providerExecuted,providerMetadata:l.providerMetadata,title:S.title}),m();break}case"start-step":{f.message.parts.push({type:"step-start"});break}case"finish-step":{f.activeTextParts={},f.activeReasoningParts={};break}case"start":{l.messageId!=null&&(f.message.id=l.messageId),await k(l.messageMetadata),(l.messageId!=null||l.messageMetadata!=null)&&m();break}case"finish":{l.finishReason!=null&&(f.finishReason=l.finishReason),await k(l.messageMetadata),l.messageMetadata!=null&&m();break}case"message-metadata":{await k(l.messageMetadata),l.messageMetadata!=null&&m();break}case"error":{o?.(new Error(l.errorText));break}default:if(D$(l)){if(r?.[l.type]!=null){let M=f.message.parts.findIndex(x=>"id"in x&&"data"in x&&x.id===l.id&&x.type===l.type),C=M>=0?M:f.message.parts.length;await za({value:l.data,schema:r[l.type],context:{field:`message.parts[${C}].data`,entityName:l.type,entityId:l.id}})}let S=l;if(S.transient){a?.(S);break}let R=S.id!=null?f.message.parts.find(M=>S.type===M.type&&S.id===M.id):void 0;R!=null?R.data=S.data:f.message.parts.push(S),a?.(S),m()}}d.enqueue(l)})}}))}s(M$,"processUIMessageStream");function P$({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:i}){let a=t?.[t.length-1];a?.role!=="assistant"?a=void 0:e=a.id;let l=!1,d=i.pipeThrough(new TransformStream({transform(E,w){if(E.type==="start"){let v=E;v.messageId==null&&e!=null&&(v.messageId=e)}E.type==="abort"&&(l=!0),w.enqueue(E)}}));if(n==null&&r==null)return d;let f=O$({lastMessage:a?structuredClone(a):void 0,messageId:e??""}),m=s(async E=>{await E({state:f,write:s(()=>{},"write")})},"runUpdateMessageJob"),g=!1,h=s(async()=>{if(g||!n)return;g=!0;let E=f.message.id===a?.id;await n({isAborted:l,isContinuation:E,responseMessage:f.message,messages:[...E?t.slice(0,-1):t,f.message],finishReason:f.finishReason})},"callOnFinish"),y=s(async()=>{if(!r)return;let E=f.message.id===a?.id;try{await r({isContinuation:E,responseMessage:structuredClone(f.message),messages:[...E?t.slice(0,-1):t,structuredClone(f.message)]})}catch(w){o(w)}},"callOnStepFinish");return M$({stream:d,runUpdateMessageJob:m,onError:o}).pipeThrough(new TransformStream({async transform(E,w){E.type==="finish-step"&&await y(),w.enqueue(E)},async cancel(){await h()},async flush(){await h()}}))}s(P$,"handleUIMessageStreamFinish");function N$({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:i}){let a=o.pipeThrough(new U_);if(i){let[l,d]=a.tee();a=l,i({stream:d})}F_({response:e,status:t,statusText:r,headers:Object.fromEntries(Za(n,q_).entries()),stream:a.pipeThrough(new TextEncoderStream)})}s(N$,"pipeUIMessageStreamToResponse");function yn(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let r=this.getReader(),n=!1;async function o(i){var a;if(!n){n=!0;try{i&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}}return s(o,"cleanup"),{async next(){if(n)return{done:!0,value:void 0};let{done:i,value:a}=await r.read();return i?(await o(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(i){throw await o(!0),i}}},t}s(yn,"createAsyncIterableStream");async function L$({stream:e,onError:t}){let r=e.getReader();try{for(;;){let{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}s(L$,"consumeStream");function MT(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}s(MT,"createResolvablePromise");function $_(){let e=[],t=null,r=!1,n=MT(),o=s(()=>{r=!0,n.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},"terminate"),i=s(async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=MT(),await n.promise,i();try{let{value:a,done:l}=await e[0].read();l?(e.shift(),e.length===0&&r?t?.close():await i()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),o()}},"processPull");return{stream:new ReadableStream({start(a){t=a},pull:i,async cancel(){for(let a of e)await a.cancel();e=[],r=!0}}),addStream:s(a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),n.resolve()},"addStream"),close:s(()=>{r=!0,n.resolve(),e.length===0&&t?.close()},"close"),terminate:o}}s($_,"createStitchableStream");function F$({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:i,abortSignal:a,repairToolCall:l,experimental_context:d,generateId:f,stepNumber:m,model:g,onToolCallStart:h,onToolCallFinish:y}){let E=null,w=new ReadableStream({start(x){E=x}}),v=new Set,O=new Map,k=new Map,S=!1,R;function M(){S&&v.size===0&&(R!=null&&E.enqueue(R),E.close())}s(M,"attemptClose");let C=new TransformStream({async transform(x,_){let T=x.type;switch(T){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{_.enqueue(x);break}case"file":{_.enqueue({type:"file",file:new h$({data:x.data,mediaType:x.mediaType}),...x.providerMetadata!=null?{providerMetadata:x.providerMetadata}:{}});break}case"finish":{R={type:"finish",finishReason:x.finishReason.unified,rawFinishReason:x.finishReason.raw,usage:Tu(x.usage),providerMetadata:x.providerMetadata};break}case"tool-approval-request":{let b=k.get(x.toolCallId);if(b==null){E.enqueue({type:"error",error:new JT({toolCallId:x.toolCallId,approvalId:x.approvalId})});break}_.enqueue({type:"tool-approval-request",approvalId:x.approvalId,toolCall:b});break}case"tool-call":{try{let b=await I$({toolCall:x,tools:e,repairToolCall:l,system:o,messages:i});if(k.set(b.toolCallId,b),_.enqueue(b),b.invalid){E.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:Ga(b.error),dynamic:!0,title:b.title});break}let A=e?.[b.toolName];if(A==null)break;if(A.onInputAvailable!=null&&await A.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:i,abortSignal:a,experimental_context:d}),await y$({tool:A,toolCall:b,messages:i,experimental_context:d})){E.enqueue({type:"tool-approval-request",approvalId:f(),toolCall:b});break}if(O.set(b.toolCallId,b.input),A.execute!=null&&b.providerExecuted!==!0){let N=f();v.add(N),P_({toolCall:b,tools:e,tracer:r,telemetry:n,messages:i,abortSignal:a,experimental_context:d,stepNumber:m,model:g,onToolCallStart:h,onToolCallFinish:y,onPreliminaryToolResult:s(J=>{E.enqueue(J)},"onPreliminaryToolResult")}).then(J=>{E.enqueue(J)}).catch(J=>{E.enqueue({type:"error",error:J})}).finally(()=>{v.delete(N),M()})}}catch(b){E.enqueue({type:"error",error:b})}break}case"tool-result":{let b=x.toolName;x.isError?E.enqueue({type:"tool-error",toolCallId:x.toolCallId,toolName:b,input:O.get(x.toolCallId),providerExecuted:!0,error:x.result,dynamic:x.dynamic,...x.providerMetadata!=null?{providerMetadata:x.providerMetadata}:{}}):_.enqueue({type:"tool-result",toolCallId:x.toolCallId,toolName:b,input:O.get(x.toolCallId),output:x.result,providerExecuted:!0,dynamic:x.dynamic,...x.providerMetadata!=null?{providerMetadata:x.providerMetadata}:{}});break}default:{let b=T;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){S=!0,M()}});return new ReadableStream({async start(x){return Promise.all([t.pipeThrough(C).pipeTo(new WritableStream({write(_){x.enqueue(_)},close(){}})),w.pipeTo(new WritableStream({write(_){x.enqueue(_)},close(){x.close()}}))])}})}s(F$,"runToolsTransformation");var j$=Gr({prefix:"aitxt",size:24});function PQ({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:i,maxRetries:a,abortSignal:l,timeout:d,headers:f,stopWhen:m=_$(1),experimental_output:g,output:h=g,experimental_telemetry:y,prepareStep:E,providerOptions:w,experimental_activeTools:v,activeTools:O=v,experimental_repairToolCall:k,experimental_transform:S,experimental_download:R,includeRawChunks:M=!1,onChunk:C,onError:x=s(({error:Ze})=>{console.error(Ze)},"onError"),onFinish:_,onAbort:T,onStepFinish:b,experimental_onStart:A,experimental_onStepStart:N,experimental_onToolCallStart:J,experimental_onToolCallFinish:ne,experimental_context:de,experimental_include:he,_internal:{now:Ae=Ka,generateId:it=j$}={},...ft}){let Ze=E_(d),q=PB(d),fe=NB(d),pe=q!=null?new AbortController:void 0,L=fe!=null?new AbortController:void 0;return new q$({model:ku(e),telemetry:y,headers:f,settings:ft,maxRetries:a,abortSignal:k$(l,Ze!=null?AbortSignal.timeout(Ze):void 0,pe?.signal,L?.signal),stepTimeoutMs:q,stepAbortController:pe,chunkTimeoutMs:fe,chunkAbortController:L,system:n,prompt:o,messages:i,tools:t,toolChoice:r,transforms:Ko(S),activeTools:O,repairToolCall:k,stopConditions:Ko(m),output:h,providerOptions:w,prepareStep:E,includeRawChunks:M,timeout:d,stopWhen:m,originalAbortSignal:l,onChunk:C,onError:x,onFinish:_,onAbort:T,onStepFinish:b,onStart:A,onStepStart:N,onToolCallStart:J,onToolCallFinish:ne,now:Ae,generateId:it,experimental_context:de,download:R,include:he})}s(PQ,"streamText");function U$(e){let t,r="",n="",o,i="";function a({controller:l,partialOutput:d=void 0}){l.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:d}),n=""}return s(a,"publishTextChunk"),new TransformStream({async transform(l,d){var f;if(l.type==="finish-step"&&n.length>0&&a({controller:d}),l.type!=="text-delta"&&l.type!=="text-start"&&l.type!=="text-end"){d.enqueue({part:l,partialOutput:void 0});return}if(t==null)t=l.id;else if(l.id!==t){d.enqueue({part:l,partialOutput:void 0});return}if(l.type==="text-start"){d.enqueue({part:l,partialOutput:void 0});return}if(l.type==="text-end"){n.length>0&&a({controller:d}),d.enqueue({part:l,partialOutput:void 0});return}r+=l.text,n+=l.text,o=(f=l.providerMetadata)!=null?f:o;let m=await e.parsePartialOutput({text:r});if(m!==void 0){let g=typeof m.partial=="string"?m.partial:JSON.stringify(m.partial);g!==i&&(a({controller:d,partialOutput:m.partial}),i=g)}}})}s(U$,"createOutputTransformStream");var q$=class{static{s(this,"DefaultStreamTextResult")}constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:i,stepTimeoutMs:a,stepAbortController:l,chunkTimeoutMs:d,chunkAbortController:f,system:m,prompt:g,messages:h,tools:y,toolChoice:E,transforms:w,activeTools:v,repairToolCall:O,stopConditions:k,output:S,providerOptions:R,prepareStep:M,includeRawChunks:C,now:x,generateId:_,timeout:T,stopWhen:b,originalAbortSignal:A,onChunk:N,onError:J,onFinish:ne,onAbort:de,onStepFinish:he,onStart:Ae,onStepStart:it,onToolCallStart:ft,onToolCallFinish:Ze,experimental_context:q,download:fe,include:pe}){this._totalUsage=new Wt,this._finishReason=new Wt,this._rawFinishReason=new Wt,this._steps=new Wt,this.outputSpecification=S,this.includeRawChunks=C,this.tools=y;let $=l$()(t?.integrations),ue,Q=[],Se=[],ke,Ne,mt,Lt={},yr=[],me=[],vn=new Map,te,le={},Jt={},Zo=new TransformStream({async transform(Qe,at){var Ft,vr,wn,zr;at.enqueue(Qe);let{part:j}=Qe;if((j.type==="text-delta"||j.type==="reasoning-delta"||j.type==="source"||j.type==="tool-call"||j.type==="tool-result"||j.type==="tool-input-start"||j.type==="tool-input-delta"||j.type==="raw")&&await N?.({chunk:j}),j.type==="error"&&await J({error:fm(j.error)}),j.type==="text-start"&&(le[j.id]={type:"text",text:"",providerMetadata:j.providerMetadata},Q.push(le[j.id])),j.type==="text-delta"){let Re=le[j.id];if(Re==null){at.enqueue({part:{type:"error",error:`text part ${j.id} not found`},partialOutput:void 0});return}Re.text+=j.text,Re.providerMetadata=(Ft=j.providerMetadata)!=null?Ft:Re.providerMetadata}if(j.type==="text-end"){let Re=le[j.id];if(Re==null){at.enqueue({part:{type:"error",error:`text part ${j.id} not found`},partialOutput:void 0});return}Re.providerMetadata=(vr=j.providerMetadata)!=null?vr:Re.providerMetadata,delete le[j.id]}if(j.type==="reasoning-start"&&(Jt[j.id]={type:"reasoning",text:"",providerMetadata:j.providerMetadata},Q.push(Jt[j.id])),j.type==="reasoning-delta"){let Re=Jt[j.id];if(Re==null){at.enqueue({part:{type:"error",error:`reasoning part ${j.id} not found`},partialOutput:void 0});return}Re.text+=j.text,Re.providerMetadata=(wn=j.providerMetadata)!=null?wn:Re.providerMetadata}if(j.type==="reasoning-end"){let Re=Jt[j.id];if(Re==null){at.enqueue({part:{type:"error",error:`reasoning part ${j.id} not found`},partialOutput:void 0});return}Re.providerMetadata=(zr=j.providerMetadata)!=null?zr:Re.providerMetadata,delete Jt[j.id]}if(j.type==="file"&&Q.push({type:"file",file:j.file,...j.providerMetadata!=null?{providerMetadata:j.providerMetadata}:{}}),j.type==="source"&&Q.push(j),j.type==="tool-call"&&Q.push(j),j.type==="tool-result"&&!j.preliminary&&Q.push(j),j.type==="tool-approval-request"&&Q.push(j),j.type==="tool-error"&&Q.push(j),j.type==="start-step"&&(Q=[],Jt={},le={},Lt=j.request,yr=j.warnings),j.type==="finish-step"){let Re=await DT({content:Q,tools:y}),kt=new T$({stepNumber:me.length,model:Qo,...Ru,experimental_context:q,content:Q,finishReason:j.finishReason,rawFinishReason:j.rawFinishReason,usage:j.usage,warnings:yr,request:Lt,response:{...j.response,messages:[...Se,...Re]},providerMetadata:j.providerMetadata});await zo({event:kt,callbacks:[he,$.onStepFinish]}),Au({warnings:yr,provider:Qo.provider,model:Qo.modelId}),me.push(kt),Se.push(...Re),ue.resolve()}j.type==="finish"&&(mt=j.totalUsage,ke=j.finishReason,Ne=j.rawFinishReason)},async flush(Qe){var at,Ft,vr,wn,zr,j,Re;try{if(me.length===0){let cr=i?.aborted?i.reason:new tB({message:"No output generated. Check the stream for errors."});At._finishReason.reject(cr),At._rawFinishReason.reject(cr),At._totalUsage.reject(cr),At._steps.reject(cr);return}let kt=ke??"other",wt=mt??Iu();At._finishReason.resolve(kt),At._rawFinishReason.resolve(Ne),At._totalUsage.resolve(wt),At._steps.resolve(me);let ie=me[me.length-1];await zo({event:{stepNumber:ie.stepNumber,model:ie.model,functionId:ie.functionId,metadata:ie.metadata,experimental_context:ie.experimental_context,finishReason:ie.finishReason,rawFinishReason:ie.rawFinishReason,totalUsage:wt,usage:ie.usage,content:ie.content,text:ie.text,reasoningText:ie.reasoningText,reasoning:ie.reasoning,files:ie.files,sources:ie.sources,toolCalls:ie.toolCalls,staticToolCalls:ie.staticToolCalls,dynamicToolCalls:ie.dynamicToolCalls,toolResults:ie.toolResults,staticToolResults:ie.staticToolResults,dynamicToolResults:ie.dynamicToolResults,request:ie.request,response:ie.response,warnings:ie.warnings,providerMetadata:ie.providerMetadata,steps:me},callbacks:[ne,$.onFinish]}),te.setAttributes(await Nt({telemetry:t,attributes:{"ai.response.finishReason":kt,"ai.response.text":{output:s(()=>ie.text,"output")},"ai.response.reasoning":{output:s(()=>ie.reasoningText,"output")},"ai.response.toolCalls":{output:s(()=>{var cr;return(cr=ie.toolCalls)!=null&&cr.length?JSON.stringify(ie.toolCalls):void 0},"output")},"ai.response.providerMetadata":JSON.stringify(ie.providerMetadata),"ai.usage.inputTokens":wt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(at=wt.inputTokenDetails)==null?void 0:at.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Ft=wt.inputTokenDetails)==null?void 0:Ft.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(vr=wt.inputTokenDetails)==null?void 0:vr.cacheWriteTokens,"ai.usage.outputTokens":wt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(wn=wt.outputTokenDetails)==null?void 0:wn.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(zr=wt.outputTokenDetails)==null?void 0:zr.reasoningTokens,"ai.usage.totalTokens":wt.totalTokens,"ai.usage.reasoningTokens":(j=wt.outputTokenDetails)==null?void 0:j.reasoningTokens,"ai.usage.cachedInputTokens":(Re=wt.inputTokenDetails)==null?void 0:Re.cacheReadTokens}}))}catch(kt){Qe.error(kt)}finally{te.end()}}}),Sn=$_();this.addStream=Sn.addStream,this.closeStream=Sn.close;let lr=Sn.stream.getReader(),Ei=new ReadableStream({async start(Qe){Qe.enqueue({type:"start"})},async pull(Qe){function at(){de?.({steps:me}),Qe.enqueue({type:"abort",...i?.reason!==void 0?{reason:rn(i.reason)}:{}}),Qe.close()}s(at,"abort");try{let{done:Ft,value:vr}=await lr.read();if(Ft){Qe.close();return}if(i?.aborted){at();return}Qe.enqueue(vr)}catch(Ft){mn(Ft)&&i?.aborted?at():Qe.error(Ft)}},cancel(Qe){return Sn.stream.cancel(Qe)}});for(let Qe of w)Ei=Ei.pipeThrough(Qe({tools:y,stopStream(){Sn.terminate()}}));this.baseStream=Ei.pipeThrough(U$(S??am())).pipeThrough(Zo);let{maxRetries:eo,retry:J_}=vm({maxRetries:o,abortSignal:i}),Qa=gm(t),gt=Ya(n),Sm=mm({model:e,telemetry:t,headers:r,settings:{...gt,maxRetries:eo}}),At=this,Qo={provider:e.provider,modelId:e.modelId},Ru={functionId:t?.functionId,metadata:t?.metadata};Xo({name:"ai.streamText",attributes:Nt({telemetry:t,attributes:{...Yo({operationId:"ai.streamText",telemetry:t}),...Sm,"ai.prompt":{input:s(()=>JSON.stringify({system:m,prompt:g,messages:h}),"input")}}}),tracer:Qa,endWhenDone:!1,fn:s(async Qe=>{te=Qe;let at=await pm({system:m,prompt:g,messages:h});await zo({event:{model:Qo,system:m,prompt:g,messages:h,tools:y,toolChoice:E,activeTools:v,maxOutputTokens:gt.maxOutputTokens,temperature:gt.temperature,topP:gt.topP,topK:gt.topK,presencePenalty:gt.presencePenalty,frequencyPenalty:gt.frequencyPenalty,stopSequences:gt.stopSequences,seed:gt.seed,maxRetries:eo,timeout:T,headers:r,providerOptions:R,stopWhen:b,output:S,abortSignal:A,include:pe,...Ru,experimental_context:q},callbacks:[Ae,$.onStart]});let Ft=at.messages,vr=[],{approvedToolApprovals:wn,deniedToolApprovals:zr}=p$({messages:Ft});if(zr.length>0||wn.length>0){let Re=wn.filter(jt=>!jt.toolCall.providerExecuted),kt=zr.filter(jt=>!jt.toolCall.providerExecuted),wt=zr.filter(jt=>jt.toolCall.providerExecuted),ie,cr=new ReadableStream({start(jt){ie=jt}});At.addStream(cr);try{for(let Sr of[...kt,...wt])ie?.enqueue({type:"tool-output-denied",toolCallId:Sr.toolCall.toolCallId,toolName:Sr.toolCall.toolName});let jt=[];if(await Promise.all(Re.map(async Sr=>{let et=await P_({toolCall:Sr.toolCall,tools:y,tracer:Qa,telemetry:t,messages:Ft,abortSignal:i,experimental_context:q,stepNumber:me.length,model:Qo,onToolCallStart:[ft,$.onToolCallStart],onToolCallFinish:[Ze,$.onToolCallFinish],onPreliminaryToolResult:s(el=>{ie?.enqueue(el)},"onPreliminaryToolResult")});et!=null&&(ie?.enqueue(et),jt.push(et))})),jt.length>0||kt.length>0){let Sr=[];for(let et of jt)Sr.push({type:"tool-result",toolCallId:et.toolCallId,toolName:et.toolName,output:await wi({toolCallId:et.toolCallId,input:et.input,tool:y?.[et.toolName],output:et.type==="tool-result"?et.output:et.error,errorMode:et.type==="tool-error"?"text":"none"})});for(let et of kt)Sr.push({type:"tool-result",toolCallId:et.toolCall.toolCallId,toolName:et.toolCall.toolName,output:{type:"execution-denied",reason:et.approvalResponse.reason}});vr.push({role:"tool",content:Sr})}}finally{ie?.close()}}Se.push(...vr);async function j({currentStep:Re,responseMessages:kt,usage:wt}){var ie,cr,jt,Sr,et,el,wm,xm,bm;let Em=At.includeRawChunks,Im=a!=null?setTimeout(()=>l.abort(),a):void 0,es;function z_(){d!=null&&(es!=null&&clearTimeout(es),es=setTimeout(()=>f.abort(),d))}s(z_,"resetChunkTimeout");function Tm(){es!=null&&(clearTimeout(es),es=void 0)}s(Tm,"clearChunkTimeout");function _m(){Im!=null&&clearTimeout(Im)}s(_m,"clearStepTimeout");try{ue=new Wt;let ts=[...Ft,...kt],lt=await M?.({model:e,steps:me,stepNumber:me.length,messages:ts,experimental_context:q}),xn=ku((ie=lt?.model)!=null?ie:e),Am={provider:xn.provider,modelId:xn.modelId},km=await dm({prompt:{system:(cr=lt?.system)!=null?cr:at.system,messages:(jt=lt?.messages)!=null?jt:ts},supportedUrls:await xn.supportedUrls,download:fe}),Rm=(Sr=lt?.activeTools)!=null?Sr:v,{toolChoice:tl,tools:Cu}=await JB({tools:y,toolChoice:(et=lt?.toolChoice)!=null?et:E,activeTools:Rm});q=(el=lt?.experimental_context)!=null?el:q;let K_=(wm=lt?.messages)!=null?wm:ts,Y_=(xm=lt?.system)!=null?xm:at.system,Cm=ym(R,lt?.providerOptions);await zo({event:{stepNumber:me.length,model:Am,system:Y_,messages:K_,tools:y,toolChoice:tl,activeTools:Rm,steps:[...me],providerOptions:Cm,timeout:T,headers:r,stopWhen:b,output:S,abortSignal:A,include:pe,...Ru,experimental_context:q},callbacks:[it,$.onStepStart]});let{result:{stream:X_,response:Dm,request:Du},doStreamSpan:to,startTimestampMs:Om}=await J_(()=>Xo({name:"ai.streamText.doStream",attributes:Nt({telemetry:t,attributes:{...Yo({operationId:"ai.streamText.doStream",telemetry:t}),...Sm,"ai.model.provider":xn.provider,"ai.model.id":xn.modelId,"ai.prompt.messages":{input:s(()=>hm(km),"input")},"ai.prompt.tools":{input:s(()=>Cu?.map(K=>JSON.stringify(K)),"input")},"ai.prompt.toolChoice":{input:s(()=>tl!=null?JSON.stringify(tl):void 0,"input")},"gen_ai.system":xn.provider,"gen_ai.request.model":xn.modelId,"gen_ai.request.frequency_penalty":gt.frequencyPenalty,"gen_ai.request.max_tokens":gt.maxOutputTokens,"gen_ai.request.presence_penalty":gt.presencePenalty,"gen_ai.request.stop_sequences":gt.stopSequences,"gen_ai.request.temperature":gt.temperature,"gen_ai.request.top_k":gt.topK,"gen_ai.request.top_p":gt.topP}}),tracer:Qa,endWhenDone:!1,fn:s(async K=>({startTimestampMs:x(),doStreamSpan:K,result:await xn.doStream({...gt,tools:Cu,toolChoice:tl,responseFormat:await S?.responseFormat,prompt:km,providerOptions:Cm,abortSignal:i,headers:r,includeRawChunks:Em})}),"fn")})),Z_=F$({tools:y,generatorStream:X_,tracer:Qa,telemetry:t,system:m,messages:ts,repairToolCall:O,abortSignal:i,experimental_context:q,generateId:_,stepNumber:me.length,model:Am,onToolCallStart:[ft,$.onToolCallStart],onToolCallFinish:[Ze,$.onToolCallFinish]}),Q_=(bm=pe?.requestBody)==null||bm?Du??{}:{...Du,body:void 0},Ii=[],Ti=[],Ou,Mu={},rs="other",Pu,xt=Iu(),Mm,Pm=!0,Or={id:_(),timestamp:new Date,modelId:Qo.modelId},eA="";At.addStream(Z_.pipeThrough(new TransformStream({async transform(K,ct){var _i,Ai,ki,Ri,Ci;if(z_(),K.type==="stream-start"){Ou=K.warnings;return}if(Pm){let nt=x()-Om;Pm=!1,to.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":nt}),to.setAttributes({"ai.response.msToFirstChunk":nt}),ct.enqueue({type:"start-step",request:Q_,warnings:Ou??[]})}let Di=K.type;switch(Di){case"tool-approval-request":case"text-start":case"text-end":{ct.enqueue(K);break}case"text-delta":{K.delta.length>0&&(ct.enqueue({type:"text-delta",id:K.id,text:K.delta,providerMetadata:K.providerMetadata}),eA+=K.delta);break}case"reasoning-start":case"reasoning-end":{ct.enqueue(K);break}case"reasoning-delta":{ct.enqueue({type:"reasoning-delta",id:K.id,text:K.delta,providerMetadata:K.providerMetadata});break}case"tool-call":{ct.enqueue(K),Ii.push(K);break}case"tool-result":{ct.enqueue(K),K.preliminary||Ti.push(K);break}case"tool-error":{ct.enqueue(K),Ti.push(K);break}case"response-metadata":{Or={id:(_i=K.id)!=null?_i:Or.id,timestamp:(Ai=K.timestamp)!=null?Ai:Or.timestamp,modelId:(ki=K.modelId)!=null?ki:Or.modelId};break}case"finish":{xt=K.usage,rs=K.finishReason,Pu=K.rawFinishReason,Mm=K.providerMetadata;let nt=x()-Om;to.addEvent("ai.stream.finish"),to.setAttributes({"ai.response.msToFinish":nt,"ai.response.avgOutputTokensPerSecond":1e3*((Ri=xt.outputTokens)!=null?Ri:0)/nt});break}case"file":{ct.enqueue(K);break}case"source":{ct.enqueue(K);break}case"tool-input-start":{Mu[K.id]=K.toolName;let nt=y?.[K.toolName];nt?.onInputStart!=null&&await nt.onInputStart({toolCallId:K.id,messages:ts,abortSignal:i,experimental_context:q}),ct.enqueue({...K,dynamic:(Ci=K.dynamic)!=null?Ci:nt?.type==="dynamic",title:nt?.title});break}case"tool-input-end":{delete Mu[K.id],ct.enqueue(K);break}case"tool-input-delta":{let nt=Mu[K.id],ns=y?.[nt];ns?.onInputDelta!=null&&await ns.onInputDelta({inputTextDelta:K.delta,toolCallId:K.id,messages:ts,abortSignal:i,experimental_context:q}),ct.enqueue(K);break}case"error":{ct.enqueue(K),rs="error";break}case"raw":{Em&&ct.enqueue(K);break}default:{let nt=Di;throw new Error(`Unknown chunk type: ${nt}`)}}},async flush(K){var ct,_i,Ai,ki,Ri,Ci,Di;let nt=Ii.length>0?JSON.stringify(Ii):void 0;try{to.setAttributes(await Nt({telemetry:t,attributes:{"ai.response.finishReason":rs,"ai.response.toolCalls":{output:s(()=>nt,"output")},"ai.response.id":Or.id,"ai.response.model":Or.modelId,"ai.response.timestamp":Or.timestamp.toISOString(),"ai.usage.inputTokens":xt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(ct=xt.inputTokenDetails)==null?void 0:ct.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(_i=xt.inputTokenDetails)==null?void 0:_i.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Ai=xt.inputTokenDetails)==null?void 0:Ai.cacheWriteTokens,"ai.usage.outputTokens":xt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(ki=xt.outputTokenDetails)==null?void 0:ki.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Ri=xt.outputTokenDetails)==null?void 0:Ri.reasoningTokens,"ai.usage.totalTokens":xt.totalTokens,"ai.usage.reasoningTokens":(Ci=xt.outputTokenDetails)==null?void 0:Ci.reasoningTokens,"ai.usage.cachedInputTokens":(Di=xt.inputTokenDetails)==null?void 0:Di.cacheReadTokens,"gen_ai.response.finish_reasons":[rs],"gen_ai.response.id":Or.id,"gen_ai.response.model":Or.modelId,"gen_ai.usage.input_tokens":xt.inputTokens,"gen_ai.usage.output_tokens":xt.outputTokens}}))}catch{}K.enqueue({type:"finish-step",finishReason:rs,rawFinishReason:Pu,usage:xt,providerMetadata:Mm,response:{...Or,headers:Dm?.headers}});let ns=c$(wt,xt);await ue.promise;let Nu=me[me.length-1];try{to.setAttributes(await Nt({telemetry:t,attributes:{"ai.response.text":{output:s(()=>Nu.text,"output")},"ai.response.reasoning":{output:s(()=>Nu.reasoningText,"output")},"ai.response.providerMetadata":JSON.stringify(Nu.providerMetadata)}}))}catch{}finally{to.end()}let Nm=Ii.filter(ht=>ht.providerExecuted!==!0),tA=Ti.filter(ht=>ht.providerExecuted!==!0);for(let ht of Ii){if(ht.providerExecuted!==!0)continue;let Lu=y?.[ht.toolName];Lu?.type==="provider"&&Lu.supportsDeferredResults&&(Ti.some(Fu=>(Fu.type==="tool-result"||Fu.type==="tool-error")&&Fu.toolCallId===ht.toolCallId)||vn.set(ht.toolCallId,{toolName:ht.toolName}))}for(let ht of Ti)(ht.type==="tool-result"||ht.type==="tool-error")&&vn.delete(ht.toolCallId);if(_m(),Tm(),(Nm.length>0&&tA.length===Nm.length||vn.size>0)&&!await A$({stopConditions:k,steps:me})){kt.push(...await DT({content:me[me.length-1].content,tools:y}));try{await j({currentStep:Re+1,responseMessages:kt,usage:ns})}catch(ht){K.enqueue({type:"error",error:ht}),At.closeStream()}}else K.enqueue({type:"finish",finishReason:rs,rawFinishReason:Pu,totalUsage:ns}),At.closeStream()}})))}finally{_m(),Tm()}}s(j,"streamStep"),await j({currentStep:0,responseMessages:vr,usage:Iu()})},"fn")}).catch(Qe=>{At.addStream(new ReadableStream({start(at){at.enqueue({type:"error",error:Qe}),at.close()}})),At.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return yn(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return yn(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await L$({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return yn(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;let n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new oo({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return yn(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:am()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:i=!1,sendStart:a=!0,sendFinish:l=!0,onError:d=rn}={}){let f=t!=null?C$({originalMessages:e,responseMessageId:t}):void 0,m=s(h=>{var y;let E=(y=this.tools)==null?void 0:y[h.toolName];return E==null?h.dynamic:E?.type==="dynamic"?!0:void 0},"isDynamic"),g=this.fullStream.pipeThrough(new TransformStream({transform:s(async(h,y)=>{let E=n?.({part:h}),w=h.type;switch(w){case"text-start":{y.enqueue({type:"text-start",id:h.id,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"text-delta":{y.enqueue({type:"text-delta",id:h.id,delta:h.text,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"text-end":{y.enqueue({type:"text-end",id:h.id,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"reasoning-start":case"reasoning-end":{o&&y.enqueue({type:w,id:h.id,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"reasoning-delta":{o&&y.enqueue({type:"reasoning-delta",id:h.id,delta:h.text,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"file":{y.enqueue({type:"file",mediaType:h.file.mediaType,url:`data:${h.file.mediaType};base64,${h.file.base64}`,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"source":{i&&h.sourceType==="url"&&y.enqueue({type:"source-url",sourceId:h.id,url:h.url,title:h.title,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}}),i&&h.sourceType==="document"&&y.enqueue({type:"source-document",sourceId:h.id,mediaType:h.mediaType,title:h.title,filename:h.filename,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"tool-input-start":{let v=m(h);y.enqueue({type:"tool-input-start",toolCallId:h.id,toolName:h.toolName,...h.providerExecuted!=null?{providerExecuted:h.providerExecuted}:{},...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{},...v!=null?{dynamic:v}:{},...h.title!=null?{title:h.title}:{}});break}case"tool-input-delta":{y.enqueue({type:"tool-input-delta",toolCallId:h.id,inputTextDelta:h.delta});break}case"tool-call":{let v=m(h);h.invalid?y.enqueue({type:"tool-input-error",toolCallId:h.toolCallId,toolName:h.toolName,input:h.input,...h.providerExecuted!=null?{providerExecuted:h.providerExecuted}:{},...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{},...v!=null?{dynamic:v}:{},errorText:d(h.error),...h.title!=null?{title:h.title}:{}}):y.enqueue({type:"tool-input-available",toolCallId:h.toolCallId,toolName:h.toolName,input:h.input,...h.providerExecuted!=null?{providerExecuted:h.providerExecuted}:{},...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{},...v!=null?{dynamic:v}:{},...h.title!=null?{title:h.title}:{}});break}case"tool-approval-request":{y.enqueue({type:"tool-approval-request",approvalId:h.approvalId,toolCallId:h.toolCall.toolCallId});break}case"tool-result":{let v=m(h);y.enqueue({type:"tool-output-available",toolCallId:h.toolCallId,output:h.output,...h.providerExecuted!=null?{providerExecuted:h.providerExecuted}:{},...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{},...h.preliminary!=null?{preliminary:h.preliminary}:{},...v!=null?{dynamic:v}:{}});break}case"tool-error":{let v=m(h);y.enqueue({type:"tool-output-error",toolCallId:h.toolCallId,errorText:h.providerExecuted?typeof h.error=="string"?h.error:JSON.stringify(h.error):d(h.error),...h.providerExecuted!=null?{providerExecuted:h.providerExecuted}:{},...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{},...v!=null?{dynamic:v}:{}});break}case"tool-output-denied":{y.enqueue({type:"tool-output-denied",toolCallId:h.toolCallId});break}case"error":{y.enqueue({type:"error",errorText:d(h.error)});break}case"start-step":{y.enqueue({type:"start-step"});break}case"finish-step":{y.enqueue({type:"finish-step"});break}case"start":{a&&y.enqueue({type:"start",...E!=null?{messageMetadata:E}:{},...f!=null?{messageId:f}:{}});break}case"finish":{l&&y.enqueue({type:"finish",finishReason:h.finishReason,...E!=null?{messageMetadata:E}:{}});break}case"abort":{y.enqueue(h);break}case"tool-input-end":break;case"raw":break;default:{let v=w;throw new Error(`Unknown chunk type: ${v}`)}}E!=null&&w!=="start"&&w!=="finish"&&y.enqueue({type:"message-metadata",messageMetadata:E})},"transform")}));return yn(P$({stream:g,messageId:f??t?.(),originalMessages:e,onFinish:r,onError:d}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:i,sendSources:a,sendFinish:l,sendStart:d,onError:f,...m}={}){N$({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:i,sendSources:a,sendFinish:l,sendStart:d,onError:f}),...m})}pipeTextStreamToResponse(e,t){j_({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:i,sendFinish:a,sendStart:l,onError:d,...f}={}){return R$({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:i,sendFinish:a,sendStart:l,onError:d}),...f})}toTextStreamResponse(e){return L_({textStream:this.textStream,...e})}};async function LQ(e,t){let r=[];t?.ignoreIncompleteToolCalls&&(e=e.map(n=>({...n,parts:n.parts.filter(o=>!Si(o)||o.state!=="input-streaming"&&o.state!=="input-available")})));for(let n of e)switch(n.role){case"system":{let o=n.parts.filter(a=>a.type==="text"),i=o.reduce((a,l)=>l.providerMetadata!=null?{...a,...l.providerMetadata}:a,{});r.push({role:"system",content:o.map(a=>a.text).join(""),...Object.keys(i).length>0?{providerOptions:i}:{}});break}case"user":{r.push({role:"user",content:n.parts.map(o=>{var i;if(nm(o))return{type:"text",text:o.text,...o.providerMetadata!=null?{providerOptions:o.providerMetadata}:{}};if(om(o))return{type:"file",mediaType:o.mediaType,filename:o.filename,data:o.url,...o.providerMetadata!=null?{providerOptions:o.providerMetadata}:{}};if(rm(o))return(i=t?.convertDataPart)==null?void 0:i.call(t,o)}).filter(_I)});break}case"assistant":{if(n.parts!=null){let o=[];async function i(){var a,l,d,f,m,g,h;if(o.length===0)return;let y=[];for(let w of o)if(nm(w))y.push({type:"text",text:w.text,...w.providerMetadata!=null?{providerOptions:w.providerMetadata}:{}});else if(om(w))y.push({type:"file",mediaType:w.mediaType,filename:w.filename,data:w.url,...w.providerMetadata!=null?{providerOptions:w.providerMetadata}:{}});else if(OT(w))y.push({type:"reasoning",text:w.text,providerOptions:w.providerMetadata});else if(Si(w)){let v=sm(w);if(w.state!=="input-streaming"&&(y.push({type:"tool-call",toolCallId:w.toolCallId,toolName:v,input:w.state==="output-error"?(a=w.input)!=null?a:"rawInput"in w?w.rawInput:void 0:w.input,providerExecuted:w.providerExecuted,...w.callProviderMetadata!=null?{providerOptions:w.callProviderMetadata}:{}}),w.approval!=null&&y.push({type:"tool-approval-request",approvalId:w.approval.id,toolCallId:w.toolCallId}),w.providerExecuted===!0&&w.state!=="approval-responded"&&(w.state==="output-available"||w.state==="output-error"))){let O=(l=w.resultProviderMetadata)!=null?l:w.callProviderMetadata;y.push({type:"tool-result",toolCallId:w.toolCallId,toolName:v,output:await wi({toolCallId:w.toolCallId,input:w.input,output:w.state==="output-error"?w.errorText:w.output,tool:(d=t?.tools)==null?void 0:d[v],errorMode:w.state==="output-error"?"json":"none"}),...O!=null?{providerOptions:O}:{}})}}else if(rm(w)){let v=(f=t?.convertDataPart)==null?void 0:f.call(t,w);v!=null&&y.push(v)}else{let v=w;throw new Error(`Unsupported part: ${v}`)}r.push({role:"assistant",content:y});let E=o.filter(w=>{var v;return Si(w)&&(w.providerExecuted!==!0||((v=w.approval)==null?void 0:v.approved)!=null)});if(E.length>0){let w=[];for(let v of E)if(((m=v.approval)==null?void 0:m.approved)!=null&&w.push({type:"tool-approval-response",approvalId:v.approval.id,approved:v.approval.approved,reason:v.approval.reason,providerExecuted:v.providerExecuted}),v.providerExecuted!==!0)switch(v.state){case"output-denied":{w.push({type:"tool-result",toolCallId:v.toolCallId,toolName:sm(v),output:{type:"error-text",value:(g=v.approval.reason)!=null?g:"Tool execution denied."},...v.callProviderMetadata!=null?{providerOptions:v.callProviderMetadata}:{}});break}case"output-error":case"output-available":{let O=sm(v);w.push({type:"tool-result",toolCallId:v.toolCallId,toolName:O,output:await wi({toolCallId:v.toolCallId,input:v.input,output:v.state==="output-error"?v.errorText:v.output,tool:(h=t?.tools)==null?void 0:h[O],errorMode:v.state==="output-error"?"text":"none"}),...v.callProviderMetadata!=null?{providerOptions:v.callProviderMetadata}:{}});break}}w.length>0&&r.push({role:"tool",content:w})}o=[]}s(i,"processBlock");for(let a of n.parts)nm(a)||OT(a)||om(a)||Si(a)||rm(a)?o.push(a):a.type==="step-start"&&await i();await i();break}break}default:{let o=n.role;throw new _B({originalMessage:n,message:`Unsupported role: ${o}`})}}return r}s(LQ,"convertToModelMessages");var UQ=De(()=>xe(u.array(u.object({id:u.string(),role:u.enum(["system","user","assistant"]),metadata:u.unknown().optional(),parts:u.array(u.union([u.object({type:u.literal("text"),text:u.string(),state:u.enum(["streaming","done"]).optional(),providerMetadata:W.optional()}),u.object({type:u.literal("reasoning"),text:u.string(),state:u.enum(["streaming","done"]).optional(),providerMetadata:W.optional()}),u.object({type:u.literal("source-url"),sourceId:u.string(),url:u.string(),title:u.string().optional(),providerMetadata:W.optional()}),u.object({type:u.literal("source-document"),sourceId:u.string(),mediaType:u.string(),title:u.string(),filename:u.string().optional(),providerMetadata:W.optional()}),u.object({type:u.literal("file"),mediaType:u.string(),filename:u.string().optional(),url:u.string(),providerMetadata:W.optional()}),u.object({type:u.literal("step-start")}),u.object({type:u.string().startsWith("data-"),id:u.string().optional(),data:u.unknown()}),u.object({type:u.literal("dynamic-tool"),toolName:u.string(),toolCallId:u.string(),state:u.literal("input-streaming"),input:u.unknown().optional(),providerExecuted:u.boolean().optional(),callProviderMetadata:W.optional(),output:u.never().optional(),errorText:u.never().optional(),approval:u.never().optional()}),u.object({type:u.literal("dynamic-tool"),toolName:u.string(),toolCallId:u.string(),state:u.literal("input-available"),input:u.unknown(),providerExecuted:u.boolean().optional(),output:u.never().optional(),errorText:u.never().optional(),callProviderMetadata:W.optional(),approval:u.never().optional()}),u.object({type:u.literal("dynamic-tool"),toolName:u.string(),toolCallId:u.string(),state:u.literal("approval-requested"),input:u.unknown(),providerExecuted:u.boolean().optional(),output:u.never().optional(),errorText:u.never().optional(),callProviderMetadata:W.optional(),approval:u.object({id:u.string(),approved:u.never().optional(),reason:u.never().optional()})}),u.object({type:u.literal("dynamic-tool"),toolName:u.string(),toolCallId:u.string(),state:u.literal("approval-responded"),input:u.unknown(),providerExecuted:u.boolean().optional(),output:u.never().optional(),errorText:u.never().optional(),callProviderMetadata:W.optional(),approval:u.object({id:u.string(),approved:u.boolean(),reason:u.string().optional()})}),u.object({type:u.literal("dynamic-tool"),toolName:u.string(),toolCallId:u.string(),state:u.literal("output-available"),input:u.unknown(),providerExecuted:u.boolean().optional(),output:u.unknown(),errorText:u.never().optional(),callProviderMetadata:W.optional(),resultProviderMetadata:W.optional(),preliminary:u.boolean().optional(),approval:u.object({id:u.string(),approved:u.literal(!0),reason:u.string().optional()}).optional()}),u.object({type:u.literal("dynamic-tool"),toolName:u.string(),toolCallId:u.string(),state:u.literal("output-error"),input:u.unknown(),rawInput:u.unknown().optional(),providerExecuted:u.boolean().optional(),output:u.never().optional(),errorText:u.string(),callProviderMetadata:W.optional(),resultProviderMetadata:W.optional(),approval:u.object({id:u.string(),approved:u.literal(!0),reason:u.string().optional()}).optional()}),u.object({type:u.literal("dynamic-tool"),toolName:u.string(),toolCallId:u.string(),state:u.literal("output-denied"),input:u.unknown(),providerExecuted:u.boolean().optional(),output:u.never().optional(),errorText:u.never().optional(),callProviderMetadata:W.optional(),approval:u.object({id:u.string(),approved:u.literal(!1),reason:u.string().optional()})}),u.object({type:u.string().startsWith("tool-"),toolCallId:u.string(),state:u.literal("input-streaming"),providerExecuted:u.boolean().optional(),callProviderMetadata:W.optional(),input:u.unknown().optional(),output:u.never().optional(),errorText:u.never().optional(),approval:u.never().optional()}),u.object({type:u.string().startsWith("tool-"),toolCallId:u.string(),state:u.literal("input-available"),providerExecuted:u.boolean().optional(),input:u.unknown(),output:u.never().optional(),errorText:u.never().optional(),callProviderMetadata:W.optional(),approval:u.never().optional()}),u.object({type:u.string().startsWith("tool-"),toolCallId:u.string(),state:u.literal("approval-requested"),input:u.unknown(),providerExecuted:u.boolean().optional(),output:u.never().optional(),errorText:u.never().optional(),callProviderMetadata:W.optional(),approval:u.object({id:u.string(),approved:u.never().optional(),reason:u.never().optional()})}),u.object({type:u.string().startsWith("tool-"),toolCallId:u.string(),state:u.literal("approval-responded"),input:u.unknown(),providerExecuted:u.boolean().optional(),output:u.never().optional(),errorText:u.never().optional(),callProviderMetadata:W.optional(),approval:u.object({id:u.string(),approved:u.boolean(),reason:u.string().optional()})}),u.object({type:u.string().startsWith("tool-"),toolCallId:u.string(),state:u.literal("output-available"),providerExecuted:u.boolean().optional(),input:u.unknown(),output:u.unknown(),errorText:u.never().optional(),callProviderMetadata:W.optional(),resultProviderMetadata:W.optional(),preliminary:u.boolean().optional(),approval:u.object({id:u.string(),approved:u.literal(!0),reason:u.string().optional()}).optional()}),u.object({type:u.string().startsWith("tool-"),toolCallId:u.string(),state:u.literal("output-error"),providerExecuted:u.boolean().optional(),input:u.unknown(),rawInput:u.unknown().optional(),output:u.never().optional(),errorText:u.string(),callProviderMetadata:W.optional(),resultProviderMetadata:W.optional(),approval:u.object({id:u.string(),approved:u.literal(!0),reason:u.string().optional()}).optional()}),u.object({type:u.string().startsWith("tool-"),toolCallId:u.string(),state:u.literal("output-denied"),providerExecuted:u.boolean().optional(),input:u.unknown(),output:u.never().optional(),errorText:u.never().optional(),callProviderMetadata:W.optional(),approval:u.object({id:u.string(),approved:u.literal(!1),reason:u.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var B$={type:"no-schema",jsonSchema:s(async()=>{},"jsonSchema"),async validatePartialResult({value:e,textDelta:t}){return{success:!0,value:{partial:e,textDelta:t}}},async validateFinalResult(e,t){return e===void 0?{success:!1,error:new ar({message:"No object generated: response did not match schema.",text:t.text,response:t.response,usage:t.usage,finishReason:t.finishReason})}:{success:!0,value:e}},createElementStream(){throw new oo({functionality:"element streams in no-schema mode"})}},$$=s(e=>({type:"object",jsonSchema:s(async()=>await e.jsonSchema,"jsonSchema"),async validatePartialResult({value:t,textDelta:r}){return{success:!0,value:{partial:t,textDelta:r}}},async validateFinalResult(t){return st({value:t,schema:e})},createElementStream(){throw new oo({functionality:"element streams in object mode"})}}),"objectOutputStrategy"),V$=s(e=>({type:"array",jsonSchema:s(async()=>{let{$schema:t,...r}=await e.jsonSchema;return{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:r}},required:["elements"],additionalProperties:!1}},"jsonSchema"),async validatePartialResult({value:t,latestObject:r,isFirstDelta:n,isFinalDelta:o}){var i;if(!$i(t)||!cd(t.elements))return{success:!1,error:new ze({value:t,cause:"value must be an object that contains an array of elements"})};let a=t.elements,l=[];for(let m=0;m<a.length;m++){let g=a[m],h=await st({value:g,schema:e});if(!(m===a.length-1&&!o)){if(!h.success)return h;l.push(h.value)}}let d=(i=r?.length)!=null?i:0,f="";return n&&(f+="["),d>0&&(f+=","),f+=l.slice(d).map(m=>JSON.stringify(m)).join(","),o&&(f+="]"),{success:!0,value:{partial:l,textDelta:f}}},async validateFinalResult(t){if(!$i(t)||!cd(t.elements))return{success:!1,error:new ze({value:t,cause:"value must be an object that contains an array of elements"})};let r=t.elements;for(let n of r){let o=await st({value:n,schema:e});if(!o.success)return o}return{success:!0,value:r}},createElementStream(t){let r=0;return yn(t.pipeThrough(new TransformStream({transform(n,o){switch(n.type){case"object":{let i=n.object;for(;r<i.length;r++)o.enqueue(i[r]);break}case"text-delta":case"finish":case"error":break;default:{let i=n;throw new Error(`Unsupported chunk type: ${i}`)}}}})))}}),"arrayOutputStrategy"),H$=s(e=>({type:"enum",jsonSchema:s(async()=>({$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1}),"jsonSchema"),async validateFinalResult(t){if(!$i(t)||typeof t.result!="string")return{success:!1,error:new ze({value:t,cause:'value must be an object that contains a string in the "result" property.'})};let r=t.result;return e.includes(r)?{success:!0,value:r}:{success:!1,error:new ze({value:t,cause:"value must be a string in the enum"})}},async validatePartialResult({value:t,textDelta:r}){if(!$i(t)||typeof t.result!="string")return{success:!1,error:new ze({value:t,cause:'value must be an object that contains a string in the "result" property.'})};let n=t.result,o=e.filter(i=>i.startsWith(n));return t.result.length===0||o.length===0?{success:!1,error:new ze({value:t,cause:"value must be a string in the enum"})}:{success:!0,value:{partial:o.length>1?n:o[0],textDelta:r}}},createElementStream(){throw new oo({functionality:"element streams in enum mode"})}}),"enumOutputStrategy");function V_({output:e,schema:t,enumValues:r}){switch(e){case"object":return $$(ir(t));case"array":return V$(ir(t));case"enum":return H$(r);case"no-schema":return B$;default:{let n=e;throw new Error(`Unsupported output: ${n}`)}}}s(V_,"getOutputStrategy");async function PT(e,t,r){let n=await _t({text:e});if(!n.success)throw new ar({message:"No object generated: could not parse the response.",cause:n.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let o=await t.validateFinalResult(n.value,{text:e,response:r.response,usage:r.usage});if(!o.success)throw new ar({message:"No object generated: response did not match schema.",cause:o.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}s(PT,"parseAndValidateObjectResult");async function H_(e,t,r,n){try{return await PT(e,t,n)}catch(o){if(r!=null&&ar.isInstance(o)&&(Nn.isInstance(o.cause)||ze.isInstance(o.cause))){let i=await r({text:e,error:o.cause});if(i===null)throw o;return await PT(i,t,n)}throw o}}s(H_,"parseAndValidateObjectResultWithRepair");function W_({output:e,schema:t,schemaName:r,schemaDescription:n,enumValues:o}){if(e!=null&&e!=="object"&&e!=="array"&&e!=="enum"&&e!=="no-schema")throw new $e({parameter:"output",value:e,message:"Invalid output type."});if(e==="no-schema"){if(t!=null)throw new $e({parameter:"schema",value:t,message:"Schema is not supported for no-schema output."});if(n!=null)throw new $e({parameter:"schemaDescription",value:n,message:"Schema description is not supported for no-schema output."});if(r!=null)throw new $e({parameter:"schemaName",value:r,message:"Schema name is not supported for no-schema output."});if(o!=null)throw new $e({parameter:"enumValues",value:o,message:"Enum values are not supported for no-schema output."})}if(e==="object"){if(t==null)throw new $e({parameter:"schema",value:t,message:"Schema is required for object output."});if(o!=null)throw new $e({parameter:"enumValues",value:o,message:"Enum values are not supported for object output."})}if(e==="array"){if(t==null)throw new $e({parameter:"schema",value:t,message:"Element schema is required for array output."});if(o!=null)throw new $e({parameter:"enumValues",value:o,message:"Enum values are not supported for array output."})}if(e==="enum"){if(t!=null)throw new $e({parameter:"schema",value:t,message:"Schema is not supported for enum output."});if(n!=null)throw new $e({parameter:"schemaDescription",value:n,message:"Schema description is not supported for enum output."});if(r!=null)throw new $e({parameter:"schemaName",value:r,message:"Schema name is not supported for enum output."});if(o==null)throw new $e({parameter:"enumValues",value:o,message:"Enum values are required for enum output."});for(let i of o)if(typeof i!="string")throw new $e({parameter:"enumValues",value:i,message:"Enum values must be strings."})}}s(W_,"validateObjectGenerationInput");var W$=Gr({prefix:"aiobj",size:24});async function WQ(e){let{model:t,output:r="object",system:n,prompt:o,messages:i,maxRetries:a,abortSignal:l,headers:d,experimental_repairText:f,experimental_telemetry:m,experimental_download:g,providerOptions:h,_internal:{generateId:y=W$,currentDate:E=s(()=>new Date,"currentDate")}={},...w}=e,v=ku(t),O="enum"in e?e.enum:void 0,{schema:k,schemaDescription:S,schemaName:R}="schema"in e?e:{};W_({output:r,schema:k,schemaName:R,schemaDescription:S,enumValues:O});let{maxRetries:M,retry:C}=vm({maxRetries:a,abortSignal:l}),x=V_({output:r,schema:k,enumValues:O}),_=Ya(w),T=hn(d??{},`ai/${I_}`),b=mm({model:v,telemetry:m,headers:T,settings:{..._,maxRetries:M}}),A=gm(m),N=await x.jsonSchema();try{return await Xo({name:"ai.generateObject",attributes:Nt({telemetry:m,attributes:{...Yo({operationId:"ai.generateObject",telemetry:m}),...b,"ai.prompt":{input:s(()=>JSON.stringify({system:n,prompt:o,messages:i}),"input")},"ai.schema":N!=null?{input:s(()=>JSON.stringify(N),"input")}:void 0,"ai.schema.name":R,"ai.schema.description":S,"ai.settings.output":x.type}}),tracer:A,fn:s(async J=>{var ne;let de,he,Ae,it,ft,Ze,q,fe,pe=await pm({system:n,prompt:o,messages:i}),L=await dm({prompt:pe,supportedUrls:await v.supportedUrls,download:g}),$=await C(()=>Xo({name:"ai.generateObject.doGenerate",attributes:Nt({telemetry:m,attributes:{...Yo({operationId:"ai.generateObject.doGenerate",telemetry:m}),...b,"ai.prompt.messages":{input:s(()=>hm(L),"input")},"gen_ai.system":v.provider,"gen_ai.request.model":v.modelId,"gen_ai.request.frequency_penalty":_.frequencyPenalty,"gen_ai.request.max_tokens":_.maxOutputTokens,"gen_ai.request.presence_penalty":_.presencePenalty,"gen_ai.request.temperature":_.temperature,"gen_ai.request.top_k":_.topK,"gen_ai.request.top_p":_.topP}}),tracer:A,fn:s(async Q=>{var Se,ke,Ne,mt,Lt,yr,me,vn;let te=await v.doGenerate({responseFormat:{type:"json",schema:N,name:R,description:S},...Ya(w),prompt:L,providerOptions:h,abortSignal:l,headers:T}),le={id:(ke=(Se=te.response)==null?void 0:Se.id)!=null?ke:y(),timestamp:(mt=(Ne=te.response)==null?void 0:Ne.timestamp)!=null?mt:E(),modelId:(yr=(Lt=te.response)==null?void 0:Lt.modelId)!=null?yr:v.modelId,headers:(me=te.response)==null?void 0:me.headers,body:(vn=te.response)==null?void 0:vn.body},Jt=m$(te.content),Zo=f$(te.content);if(Jt===void 0)throw new ar({message:"No object generated: the model did not return a response.",response:le,usage:Tu(te.usage),finishReason:te.finishReason.unified});return Q.setAttributes(await Nt({telemetry:m,attributes:{"ai.response.finishReason":te.finishReason.unified,"ai.response.object":{output:s(()=>Jt,"output")},"ai.response.id":le.id,"ai.response.model":le.modelId,"ai.response.timestamp":le.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(te.providerMetadata),"ai.usage.promptTokens":te.usage.inputTokens.total,"ai.usage.completionTokens":te.usage.outputTokens.total,"gen_ai.response.finish_reasons":[te.finishReason.unified],"gen_ai.response.id":le.id,"gen_ai.response.model":le.modelId,"gen_ai.usage.input_tokens":te.usage.inputTokens.total,"gen_ai.usage.output_tokens":te.usage.outputTokens.total}})),{...te,objectText:Jt,reasoning:Zo,responseData:le}},"fn")}));de=$.objectText,he=$.finishReason.unified,Ae=Tu($.usage),it=$.warnings,q=$.providerMetadata,Ze=(ne=$.request)!=null?ne:{},ft=$.responseData,fe=$.reasoning,Au({warnings:it,provider:v.provider,model:v.modelId});let ue=await H_(de,x,f,{response:ft,usage:Ae,finishReason:he});return J.setAttributes(await Nt({telemetry:m,attributes:{"ai.response.finishReason":he,"ai.response.object":{output:s(()=>JSON.stringify(ue),"output")},"ai.response.providerMetadata":JSON.stringify(q),"ai.usage.promptTokens":Ae.inputTokens,"ai.usage.completionTokens":Ae.outputTokens}})),new G$({object:ue,reasoning:fe,finishReason:he,usage:Ae,warnings:it,request:Ze,response:ft,providerMetadata:q})},"fn")})}catch(J){throw fm(J)}}s(WQ,"generateObject");var G$=class{static{s(this,"DefaultGenerateObjectResult")}constructor(e){this.object=e.object,this.finishReason=e.finishReason,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.response=e.response,this.request=e.request,this.reasoning=e.reasoning}toJsonResponse(e){var t;return new Response(JSON.stringify(this.object),{status:(t=e?.status)!=null?t:200,headers:Za(e?.headers,{"content-type":"application/json; charset=utf-8"})})}};function G_(e){return({url:t,abortSignal:r})=>T_({url:t,maxBytes:e?.maxBytes,abortSignal:r})}s(G_,"createDownload");function _u(e,t){if(e===t)return!0;if(e==null||t==null)return!1;if(typeof e!="object"&&typeof t!="object")return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)){if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(!_u(e[o],t[o]))return!1;return!0}let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let o of r)if(!n.includes(o)||!_u(e[o],t[o]))return!1;return!0}s(_u,"isDeepEqualData");var J$=Gr({prefix:"aiobj",size:24});function JQ(e){let{model:t,output:r="object",system:n,prompt:o,messages:i,maxRetries:a,abortSignal:l,headers:d,experimental_repairText:f,experimental_telemetry:m,experimental_download:g,providerOptions:h,onError:y=s(({error:_})=>{console.error(_)},"onError"),onFinish:E,_internal:{generateId:w=J$,currentDate:v=s(()=>new Date,"currentDate"),now:O=Ka}={},...k}=e,S="enum"in e&&e.enum?e.enum:void 0,{schema:R,schemaDescription:M,schemaName:C}="schema"in e?e:{};W_({output:r,schema:R,schemaName:C,schemaDescription:M,enumValues:S});let x=V_({output:r,schema:R,enumValues:S});return new z$({model:t,telemetry:m,headers:d,settings:k,maxRetries:a,abortSignal:l,outputStrategy:x,system:n,prompt:o,messages:i,schemaName:C,schemaDescription:M,providerOptions:h,repairText:f,onError:y,onFinish:E,download:g,generateId:w,currentDate:v,now:O})}s(JQ,"streamObject");var z$=class{static{s(this,"DefaultStreamObjectResult")}constructor({model:e,headers:t,telemetry:r,settings:n,maxRetries:o,abortSignal:i,outputStrategy:a,system:l,prompt:d,messages:f,schemaName:m,schemaDescription:g,providerOptions:h,repairText:y,onError:E,onFinish:w,download:v,generateId:O,currentDate:k,now:S}){this._object=new Wt,this._usage=new Wt,this._providerMetadata=new Wt,this._warnings=new Wt,this._request=new Wt,this._response=new Wt,this._finishReason=new Wt;let R=ku(e),{maxRetries:M,retry:C}=vm({maxRetries:o,abortSignal:i}),x=Ya(n),_=mm({model:R,telemetry:r,headers:t,settings:{...x,maxRetries:M}}),T=gm(r),b=this,A=$_(),N=new TransformStream({transform(J,ne){ne.enqueue(J),J.type==="error"&&E({error:fm(J.error)})}});this.baseStream=A.stream.pipeThrough(N),Xo({name:"ai.streamObject",attributes:Nt({telemetry:r,attributes:{...Yo({operationId:"ai.streamObject",telemetry:r}),..._,"ai.prompt":{input:s(()=>JSON.stringify({system:l,prompt:d,messages:f}),"input")},"ai.schema":{input:s(async()=>JSON.stringify(await a.jsonSchema()),"input")},"ai.schema.name":m,"ai.schema.description":g,"ai.settings.output":a.type}}),tracer:T,endWhenDone:!1,fn:s(async J=>{let ne=await pm({system:l,prompt:d,messages:f}),de={responseFormat:{type:"json",schema:await a.jsonSchema(),name:m,description:g},...Ya(n),prompt:await dm({prompt:ne,supportedUrls:await R.supportedUrls,download:v}),providerOptions:h,abortSignal:i,headers:t,includeRawChunks:!1},he={transform:s((te,le)=>{switch(te.type){case"text-delta":le.enqueue(te.delta);break;case"response-metadata":case"finish":case"error":case"stream-start":le.enqueue(te);break}},"transform")},{result:{stream:Ae,response:it,request:ft},doStreamSpan:Ze,startTimestampMs:q}=await C(()=>Xo({name:"ai.streamObject.doStream",attributes:Nt({telemetry:r,attributes:{...Yo({operationId:"ai.streamObject.doStream",telemetry:r}),..._,"ai.prompt.messages":{input:s(()=>hm(de.prompt),"input")},"gen_ai.system":R.provider,"gen_ai.request.model":R.modelId,"gen_ai.request.frequency_penalty":x.frequencyPenalty,"gen_ai.request.max_tokens":x.maxOutputTokens,"gen_ai.request.presence_penalty":x.presencePenalty,"gen_ai.request.temperature":x.temperature,"gen_ai.request.top_k":x.topK,"gen_ai.request.top_p":x.topP}}),tracer:T,endWhenDone:!1,fn:s(async te=>({startTimestampMs:S(),doStreamSpan:te,result:await R.doStream(de)}),"fn")}));b._request.resolve(ft??{});let fe,pe=Iu(),L,$,ue,Q,Se="",ke="",Ne={id:O(),timestamp:k(),modelId:R.modelId},mt,Lt,yr=!0,me=!0,vn=Ae.pipeThrough(new TransformStream(he)).pipeThrough(new TransformStream({async transform(te,le){var Jt,Zo,Sn;if(typeof te=="object"&&te.type==="stream-start"){fe=te.warnings;return}if(yr){let lr=S()-q;yr=!1,Ze.addEvent("ai.stream.firstChunk",{"ai.stream.msToFirstChunk":lr}),Ze.setAttributes({"ai.stream.msToFirstChunk":lr})}if(typeof te=="string"){Se+=te,ke+=te;let{value:lr,state:Ei}=await bi(Se);if(lr!==void 0&&!_u(mt,lr)){let eo=await a.validatePartialResult({value:lr,textDelta:ke,latestObject:Lt,isFirstDelta:me,isFinalDelta:Ei==="successful-parse"});eo.success&&!_u(Lt,eo.value.partial)&&(mt=lr,Lt=eo.value.partial,le.enqueue({type:"object",object:Lt}),le.enqueue({type:"text-delta",textDelta:eo.value.textDelta}),ke="",me=!1)}return}switch(te.type){case"response-metadata":{Ne={id:(Jt=te.id)!=null?Jt:Ne.id,timestamp:(Zo=te.timestamp)!=null?Zo:Ne.timestamp,modelId:(Sn=te.modelId)!=null?Sn:Ne.modelId};break}case"finish":{ke!==""&&le.enqueue({type:"text-delta",textDelta:ke}),L=te.finishReason.unified,pe=Tu(te.usage),$=te.providerMetadata,le.enqueue({...te,finishReason:te.finishReason.unified,usage:pe,response:Ne}),Au({warnings:fe??[],provider:R.provider,model:R.modelId}),b._usage.resolve(pe),b._providerMetadata.resolve($),b._warnings.resolve(fe),b._response.resolve({...Ne,headers:it?.headers}),b._finishReason.resolve(L??"other");try{ue=await H_(Se,a,y,{response:Ne,usage:pe,finishReason:L}),b._object.resolve(ue)}catch(lr){Q=lr,b._object.reject(lr)}break}default:{le.enqueue(te);break}}},async flush(te){try{let le=pe??{promptTokens:NaN,completionTokens:NaN,totalTokens:NaN};Ze.setAttributes(await Nt({telemetry:r,attributes:{"ai.response.finishReason":L,"ai.response.object":{output:s(()=>JSON.stringify(ue),"output")},"ai.response.id":Ne.id,"ai.response.model":Ne.modelId,"ai.response.timestamp":Ne.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify($),"ai.usage.inputTokens":le.inputTokens,"ai.usage.outputTokens":le.outputTokens,"ai.usage.totalTokens":le.totalTokens,"ai.usage.reasoningTokens":le.reasoningTokens,"ai.usage.cachedInputTokens":le.cachedInputTokens,"gen_ai.response.finish_reasons":[L],"gen_ai.response.id":Ne.id,"gen_ai.response.model":Ne.modelId,"gen_ai.usage.input_tokens":le.inputTokens,"gen_ai.usage.output_tokens":le.outputTokens}})),Ze.end(),J.setAttributes(await Nt({telemetry:r,attributes:{"ai.usage.inputTokens":le.inputTokens,"ai.usage.outputTokens":le.outputTokens,"ai.usage.totalTokens":le.totalTokens,"ai.usage.reasoningTokens":le.reasoningTokens,"ai.usage.cachedInputTokens":le.cachedInputTokens,"ai.response.object":{output:s(()=>JSON.stringify(ue),"output")},"ai.response.providerMetadata":JSON.stringify($)}})),await w?.({usage:le,object:ue,error:Q,response:{...Ne,headers:it?.headers},warnings:fe,providerMetadata:$})}catch(le){te.enqueue({type:"error",error:le})}finally{J.end()}}}));A.addStream(vn)},"fn")}).catch(J=>{A.addStream(new ReadableStream({start(ne){ne.enqueue({type:"error",error:J}),ne.close()}}))}).finally(()=>{A.close()}),this.outputStrategy=a}get object(){return this._object.promise}get usage(){return this._usage.promise}get providerMetadata(){return this._providerMetadata.promise}get warnings(){return this._warnings.promise}get request(){return this._request.promise}get response(){return this._response.promise}get finishReason(){return this._finishReason.promise}get partialObjectStream(){return yn(this.baseStream.pipeThrough(new TransformStream({transform(e,t){switch(e.type){case"object":t.enqueue(e.object);break;case"text-delta":case"finish":case"error":break;default:{let r=e;throw new Error(`Unsupported chunk type: ${r}`)}}}})))}get elementStream(){return this.outputStrategy.createElementStream(this.baseStream)}get textStream(){return yn(this.baseStream.pipeThrough(new TransformStream({transform(e,t){switch(e.type){case"text-delta":t.enqueue(e.textDelta);break;case"object":case"finish":case"error":break;default:{let r=e;throw new Error(`Unsupported chunk type: ${r}`)}}}})))}get fullStream(){return yn(this.baseStream)}pipeTextStreamToResponse(e,t){j_({response:e,textStream:this.textStream,...t})}toTextStreamResponse(e){return L_({textStream:this.textStream,...e})}};var zQ=G_();var KQ=s(({model:e,middleware:t,modelId:r,providerId:n})=>[...Ko(t)].reverse().reduce((o,i)=>K$({model:o,middleware:i,modelId:r,providerId:n}),e),"wrapLanguageModel"),K$=s(({model:e,middleware:{transformParams:t,wrapGenerate:r,wrapStream:n,overrideProvider:o,overrideModelId:i,overrideSupportedUrls:a},modelId:l,providerId:d})=>{var f,m,g;async function h({params:y,type:E}){return t?await t({params:y,type:E,model:e}):y}return s(h,"doTransform"),{specificationVersion:"v3",provider:(f=d??o?.({model:e}))!=null?f:e.provider,modelId:(m=l??i?.({model:e}))!=null?m:e.modelId,supportedUrls:(g=a?.({model:e}))!=null?g:e.supportedUrls,async doGenerate(y){let E=await h({params:y,type:"generate"}),w=s(async()=>e.doGenerate(E),"doGenerate");return r?r({doGenerate:w,doStream:s(async()=>e.doStream(E),"doStream"),params:E,model:e}):w()},async doStream(y){let E=await h({params:y,type:"stream"}),w=s(async()=>e.doGenerate(E),"doGenerate"),v=s(async()=>e.doStream(E),"doStream");return n?n({doGenerate:w,doStream:v,params:E,model:e}):v()}}},"doWrap");var Y$="AI_NoSuchProviderError",X$=`vercel.ai.error.${Y$}`,Z$=Symbol.for(X$),Q$;Q$=Z$;var YQ=G_();export{nn as a,Gi as b,ai as c,xs as d,Pe as e,Vi as f,Hi as g,Fr as h,Z as i,Vf as j,vt as k,HA as l,WA as m,GA as n,JA as o,KA as p,YA as q,qt as r,gd as s,Rd as t,md as u,ee as v,so as w,Bt as x,GV as y,Cl as z,jr as A,bs as B,Cd as C,fn as D,tu as E,ru as F,AL as G,xE as H,bE as I,EE as J,se as K,Ba as L,Gn as M,Ge as N,jE as O,RF as P,Ff as Q,SY as R,VE as S,rI as T,FY as U,qf as V,Bf as W,$f as X,hu as Y,pi as Z,mi as _,di as $,Gf as aa,ac as ba,Lo as ca,tv as da,wv as ea,xv as fa,ua as ga,$n as ha,dc as ia,pa as ja,pc as ka,js as la,Ac as ma,Tp as na,AC as oa,CC as pa,OC as qa,mr as ra,PC as sa,LC as ta,fC as ua,qs as va,ga as wa,ha as xa,qS as ya,oJ as za,BS as Aa,Ep as Ba,vC as Ca,Et as Da,Bs as Ea,He as Fa,YS as Ga,kc as Ha,Dp as Ia,St as Ja,Ca as Ka,Ma as La,va as Ma,wJ as Na,lf as Oa,Na as Pa,pK as Qa,Qb as Ra,eE as Sa,fK as Ta,mK as Ua,gK as Va,hK as Wa,yK as Xa,vK as Ya,jo as Za,wf as _a,Ja as $a,ir as ab,L2 as bb,PQ as cb,LQ as db,WQ as eb,JQ as fb,KQ as gb,qa as hb,ja as ib,If as jb,Tf as kb,Af as lb,kf as mb};
763
+ /*! Bundled license information:
764
+
765
+ is-extendable/index.js:
766
+ (*!
767
+ * is-extendable <https://github.com/jonschlinkert/is-extendable>
768
+ *
769
+ * Copyright (c) 2015, Jon Schlinkert.
770
+ * Licensed under the MIT License.
771
+ *)
772
+
773
+ strip-bom-string/index.js:
774
+ (*!
775
+ * strip-bom-string <https://github.com/jonschlinkert/strip-bom-string>
776
+ *
777
+ * Copyright (c) 2015, 2017, Jon Schlinkert.
778
+ * Released under the MIT License.
779
+ *)
780
+ */