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
@@ -1,1455 +0,0 @@
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
-
14
- import{a as ii}from"./chunk-VURLSDCB.js";import{A as Tt,B as cs,D as rd,E as dt,F as yt,G as Nt,b as $o,h as li,l as di,m as ql,n as Vl,o as zl,p as Ta,q as Gl,r as Hl,t as Ql,v as Ke,w as ed,x as td,y as Pn,z as We}from"./chunk-MKEMZFJI.js";import{N as ce,a as Ca,b as Kl,c as Tn,d as mi,e as La,f as Et,g as it,h as Ce,i as _a,j as Jl,k as Xl,l as Qe,m as lo}from"./chunk-Z5TLIUAI.js";import{b as yi,c as ir,d as od,e as nd,g as ar}from"./chunk-OWMG4NNF.js";import{A as Zl,B as gi,D as uo,i as Bl,s as Yt,u as Ye,w as an,x as hi}from"./chunk-4FEBIOI5.js";import{b as X,c as on,e as Sn}from"./chunk-QRABYJKL.js";import{Ba as le,C as Cl,Ca as Ra,Da as rt,E as Ml,Ea as vo,F as Ol,Fa as sn,G as Ll,Ga as Aa,H as _l,Ha as st,I as Ul,J as jl,K as xt,L as Nl,M as ci,N as rr,O as ka,P as Fl,Q as Da,R as En,S as rn,Sa as De,T as Wo,U as Ea,Ua as Ma,Va as sr,Wa as we,Xa as Oa,Ya as Me,c as nn,f as Sa,fa as $l,ga as Wl,h as kn,ha as jt,ia as ui,k as Mo,la as Pa,na as eo,oa as Yl,pa as pi,r as ct,s as Ht,u as ai,v as Dt,va as B,xa as lt,y as Dn,ya as fi}from"./chunk-OMDJ6ZZ2.js";import{$ as va,Aa as ri,Cc as Al,Da as or,E as co,Ea as kl,F as xn,Fa as Ao,Ga as In,Ja as Co,K as rs,Ka as Dl,L as me,M as ss,Ma as Se,N as is,Na as si,P as Xe,Q as vn,Qa as nr,R as Fo,S as fl,T as xa,U as Gt,V as ml,W as at,Z as hl,_ as ni,a as ge,b as ti,ca as Ia,da as gl,f as bo,fa as yl,ga as wl,h as ll,ha as bl,i as xo,ia as xl,j as dl,ka as vl,l as ul,na as Il,oa as Bo,pa as nt,qa as gt,r as oi,ra as as,s as pl,sa as tn,t as kt,tb as El,wa as Ie,xa as tr,xb as Tl,y as No,ya as Sl,yb as Pl,zc as Rl}from"./chunk-BM2C7NHL.js";import{a as s,d as ae}from"./chunk-RHIWAYN5.js";var Rn={};ae(Rn,{AppNodeBuilder:()=>Rn,build:()=>Um});function Um(e,t=[]){let o=t;if(ge.hasUnbound(e,nn.node)&&!jm(t,nn.node)){let n=Gl(t),r=ti({service:nn.Service,layer:n,deps:[]});o=t.concat([[nn.node,r]])}return ge.compile(e,o)}s(Um,"build");function jm(e,t){return e.some(([o])=>o.name===t.name)}s(jm,"hasReplacement");var ja={};ae(ja,{Authorization:()=>Ua,AuthorizeInput:()=>zm,CallbackInput:()=>Gm,Method:()=>wi,Methods:()=>cd,OauthCallbackFailed:()=>vi,OauthCodeMissing:()=>xi,OauthMissing:()=>bi,ProviderAuth:()=>ja,Service:()=>Cn,ValidationFailed:()=>Ii,node:()=>Km,use:()=>Hm});import{Array as Nm,Effect as An,Layer as Fm,Record as sd,Result as id,Context as Bm,Schema as be}from"effect";var ad=be.Struct({key:be.String,op:be.Literals(["eq","neq"]),value:be.String}),$m=be.Struct({type:be.Literal("text"),key:be.String,message:be.String,placeholder:xo(be.String),when:xo(ad)}),Wm=be.Struct({label:be.String,value:be.String,hint:xo(be.String)}),qm=be.Struct({type:be.Literal("select"),key:be.String,message:be.String,options:be.Array(Wm),when:xo(ad)}),Vm=be.Union([$m,qm]),wi=class extends be.Class("ProviderAuthMethod")({type:be.Literals(["oauth","api"]),label:be.String,prompts:xo(be.Array(Vm))}){static{s(this,"Method")}},cd=be.Record(be.String,be.Array(wi)),Ua=class extends be.Class("ProviderAuthAuthorization")({url:be.String,method:be.Literals(["auto","code"]),instructions:be.String}){static{s(this,"Authorization")}},zm=be.Struct({method:be.Finite.annotate({description:"Auth method index"}),inputs:be.optional(be.Record(be.String,be.String)).annotate({description:"Prompt inputs"})}),Gm=be.Struct({method:be.Finite.annotate({description:"Auth method index"}),code:be.optional(be.String).annotate({description:"OAuth authorization code"})}),bi=class extends be.TaggedErrorClass()("ProviderAuthOauthMissing",{providerID:co.ID}){static{s(this,"OauthMissing")}},xi=class extends be.TaggedErrorClass()("ProviderAuthOauthCodeMissing",{providerID:co.ID}){static{s(this,"OauthCodeMissing")}},vi=class extends be.TaggedErrorClass()("ProviderAuthOauthCallbackFailed",{}){static{s(this,"OauthCallbackFailed")}},Ii=class extends be.TaggedErrorClass()("ProviderAuthValidationFailed",{field:be.String,message:be.String}){static{s(this,"ValidationFailed")}},Cn=class extends Bm.Service()("@opencode/ProviderAuth"){static{s(this,"Service")}},Hm=Gt(Cn),Ym=Fm.effect(Cn,An.gen(function*(){let e=yield*eo.Service,t=yield*dt.Service,o=yield*B.make(An.fn("ProviderAuth.state")(function*(){let c=yield*t.list();return{hooks:sd.fromEntries(Nm.filterMap(c,d=>d.auth?.provider!==void 0?id.succeed([co.ID.make(d.auth.provider),d.auth]):id.failVoid)),pending:new Map}})),n=be.decodeUnknownSync(cd),r=An.fn("ProviderAuth.methods")(function*(){let c=(yield*B.get(o)).hooks;return n(sd.map(c,d=>d.methods.map(u=>({type:u.type,label:u.label,...u.prompts&&{prompts:u.prompts.map(l=>l.type==="select"?{type:"select",key:l.key,message:l.message,options:l.options,...l.when&&{when:l.when}}:{type:"text",key:l.key,message:l.message,...l.placeholder&&{placeholder:l.placeholder},...l.when&&{when:l.when}})}}))))}),i=An.fn("ProviderAuth.authorize")(function*(c){let{hooks:d,pending:u}=yield*B.get(o),l=d[c.providerID].methods[c.method];if(l.type!=="oauth")return;if(l.prompts&&c.inputs){for(let h of l.prompts)if(h.type==="text"&&h.validate&&c.inputs[h.key]!==void 0){let g=h.validate(c.inputs[h.key]);if(g)return yield*new Ii({field:h.key,message:g})}}let m=yield*An.promise(()=>l.authorize(c.inputs));return u.set(c.providerID,m),{url:m.url,method:m.method,instructions:m.instructions}}),a=An.fn("ProviderAuth.callback")(function*(c){let u=(yield*B.get(o)).pending.get(c.providerID);if(!u)return yield*new bi({providerID:c.providerID});if(u.method==="code"&&!c.code)return yield*new xi({providerID:c.providerID});let l=yield*An.promise(()=>u.method==="code"?u.callback(c.code):u.callback());if(!l||l.type!=="success")return yield*new vi({});if("key"in l&&(yield*e.set(c.providerID,{type:"api",key:l.key,...l.metadata?{metadata:l.metadata}:{}})),"refresh"in l){let{type:m,provider:h,refresh:g,access:w,expires:k,...p}=l;yield*e.set(c.providerID,{type:"oauth",access:w,refresh:g,expires:k,...p})}});return Cn.of({methods:r,authorize:i,callback:a})})),Km=ge.make({service:Cn,layer:Ym,deps:[eo.node,dt.node]});var to={};ae(to,{Answer:()=>ih,Event:()=>ki,Info:()=>oh,NotFoundError:()=>us,Option:()=>th,Prompt:()=>nh,Question:()=>to,Rejected:()=>lh,RejectedError:()=>ds,Replied:()=>ch,Reply:()=>ah,Request:()=>sh,Service:()=>cr,Tool:()=>rh,node:()=>uh});import{Deferred as ls,Effect as Ft,Layer as Zm,Schema as bd,Context as eh}from"effect";var Lt={};ae(Lt,{Answer:()=>Na,Event:()=>Qm,ID:()=>Si,Info:()=>md,Option:()=>pd,Prompt:()=>Jm,QuestionV1:()=>Lt,Rejected:()=>wd,Replied:()=>yd,Reply:()=>Xm,Request:()=>gd,Tool:()=>hd});import{Schema as Ze}from"effect";var Si=Ze.String.check(Ze.isStartsWith("que")).pipe(Ze.brand("QuestionID"),dl(e=>({ascending:s(t=>e.make(t??"que_"+ul()),"ascending")}))),pd=Ze.Struct({label:Ze.String.annotate({description:"Display text (1-5 words, concise)"}),description:Ze.String.annotate({description:"Explanation of choice"})}).annotate({identifier:"QuestionOption"}),fd={question:Ze.String.annotate({description:"Complete question"}),header:Ze.String.annotate({description:"Very short label (max 30 chars)"}),options:Ze.Array(pd).annotate({description:"Available choices"}),multiple:Ze.optional(Ze.Boolean).annotate({description:"Allow selecting multiple choices"})},md=Ze.Struct({...fd,custom:Ze.optional(Ze.Boolean).annotate({description:"Allow typing a custom answer (default: true)"})}).annotate({identifier:"QuestionInfo"}),Jm=Ze.Struct(fd).annotate({identifier:"QuestionPrompt"}),hd=Ze.Struct({messageID:Rl.MessageID,callID:Ze.String}).annotate({identifier:"QuestionTool"}),gd=Ze.Struct({id:Si,sessionID:No,questions:Ze.Array(md).annotate({description:"Questions to ask"}),tool:Ze.optional(hd)}).annotate({identifier:"QuestionRequest"}),Na=Ze.Array(Ze.String).annotate({identifier:"QuestionAnswer"}),Xm=Ze.Struct({answers:Ze.Array(Na).annotate({description:"User answers in order of questions (each answer is an array of selected labels)"})}).annotate({identifier:"QuestionReply"}),yd=Ze.Struct({sessionID:No,requestID:Si,answers:Ze.Array(Na)}).annotate({identifier:"QuestionReplied"}),wd=Ze.Struct({sessionID:No,requestID:Si}).annotate({identifier:"QuestionRejected"}),ld=oi({type:"question.asked",schema:gd.fields}),dd=oi({type:"question.replied",schema:yd.fields}),ud=oi({type:"question.rejected",schema:wd.fields}),Qm={Asked:ld,Replied:dd,Rejected:ud,Definitions:pl(ld,dd,ud)};var Fa=Lt.ID;var th=Lt.Option,oh=Lt.Info,nh=Lt.Prompt,rh=Lt.Tool,sh=Lt.Request,ih=Lt.Answer,ah=Lt.Reply,ch=Lt.Replied,lh=Lt.Rejected,ki=Lt.Event,ds=class extends bd.TaggedErrorClass()("QuestionRejectedError",{}){static{s(this,"RejectedError")}get message(){return"The user dismissed this question"}},us=class extends bd.TaggedErrorClass()("Question.NotFoundError",{requestID:Fa}){static{s(this,"NotFoundError")}},cr=class extends eh.Service()("@opencode/Question"){static{s(this,"Service")}},dh=Zm.effect(cr,Ft.gen(function*(){let e=yield*we.Service,t=yield*B.make(Ft.fn("Question.state")(function*(){let a={pending:new Map};return yield*Ft.addFinalizer(()=>Ft.gen(function*(){for(let c of a.pending.values())yield*ls.fail(c.deferred,new ds);a.pending.clear()})),a})),o=Ft.fn("Question.ask")(function*(a){let c=(yield*B.get(t)).pending,d=Fa.ascending();yield*Ft.logInfo("asking",{id:d,questions:a.questions.length});let u=yield*ls.make(),l={id:d,sessionID:a.sessionID,questions:a.questions,tool:a.tool};return c.set(d,{info:l,deferred:u}),yield*e.publish(ki.Asked,l),yield*Ft.ensuring(ls.await(u),Ft.sync(()=>{c.delete(d)}))}),n=Ft.fn("Question.reply")(function*(a){let c=(yield*B.get(t)).pending,d=c.get(a.requestID);if(!d)return yield*Ft.logWarning("reply for unknown request",{requestID:a.requestID}),yield*new us({requestID:a.requestID});c.delete(a.requestID),yield*Ft.logInfo("replied",{requestID:a.requestID,answers:a.answers}),yield*e.publish(ki.Replied,{sessionID:d.info.sessionID,requestID:d.info.id,answers:a.answers.map(u=>[...u])}),yield*ls.succeed(d.deferred,a.answers)}),r=Ft.fn("Question.reject")(function*(a){let c=(yield*B.get(t)).pending,d=c.get(a);if(!d)return yield*Ft.logWarning("reject for unknown request",{requestID:a}),yield*new us({requestID:a});c.delete(a),yield*Ft.logInfo("rejected",{requestID:a}),yield*e.publish(ki.Rejected,{sessionID:d.info.sessionID,requestID:d.info.id}),yield*ls.fail(d.deferred,new ds)}),i=Ft.fn("Question.list")(function*(){let a=(yield*B.get(t)).pending;return Array.from(a.values(),c=>c.info)});return cr.of({ask:o,reply:n,reject:r,list:i})})),uh=ge.make({service:cr,layer:dh,deps:[we.node]});var cn={};ae(cn,{Event:()=>vd,Info:()=>hh,Service:()=>dr,Todo:()=>cn,node:()=>yh});import{Effect as lr,Layer as ph,Context as fh}from"effect";import{eq as xd}from"drizzle-orm";import{asc as mh}from"drizzle-orm";var hh=Ta.Info,vd=Ta.Event,dr=class extends fh.Service()("@opencode/SessionTodo"){static{s(this,"Service")}},gh=ph.effect(dr,lr.gen(function*(){let e=yield*we.Service,{db:t}=yield*Xe.Service,o=lr.fn("Todo.update")(function*(r){yield*t.transaction(i=>lr.gen(function*(){yield*i.delete(Dn).where(xd(Dn.session_id,r.sessionID)).run(),r.todos.length!==0&&(yield*i.insert(Dn).values(r.todos.map((a,c)=>({session_id:r.sessionID,content:a.content,status:a.status,priority:a.priority,position:c}))).run())})).pipe(lr.orDie),yield*e.publish(vd.Updated,r)}),n=lr.fn("Todo.get")(function*(r){return(yield*t.select().from(Dn).where(xd(Dn.session_id,r)).orderBy(mh(Dn.position)).all().pipe(lr.orDie)).map(a=>({content:a.content,status:a.status,priority:a.priority}))});return dr.of({update:o,get:n})})),yh=ge.make({service:dr,layer:gh,deps:[we.node,Xe.node]});var po={};ae(po,{Event:()=>Ba,Info:()=>vh,Service:()=>fr,SessionStatus:()=>po,node:()=>Sh});import{Effect as pr,Layer as bh,Context as xh}from"effect";var ur={};ae(ur,{Definitions:()=>wh,Idle:()=>kd,Info:()=>Id,SessionStatusEvent:()=>ur,Status:()=>Sd});import{Schema as Bt}from"effect";var Id=Bt.Union([Bt.Struct({type:Bt.Literal("idle")}),Bt.Struct({type:Bt.Literal("retry"),attempt:bo,message:Bt.String,action:xo(Bt.Struct({reason:Bt.String,provider:Bt.String,title:Bt.String,message:Bt.String,label:Bt.String,link:xo(Bt.String)})),next:bo}),Bt.Struct({type:Bt.Literal("busy")})]).annotate({identifier:"SessionStatus"}),Sd=kt.define({type:"session.status",schema:{sessionID:No,status:Id}}),kd=kt.define({type:"session.idle",schema:{sessionID:No}}),wh=kt.inventory(Sd,kd);var vh=ur.Info,Ba=ur,fr=class extends xh.Service()("@opencode/SessionStatus"){static{s(this,"Service")}},Ih=bh.effect(fr,pr.gen(function*(){let e=yield*we.Service,t=yield*B.make(pr.fn("SessionStatus.state")(()=>pr.succeed(new Map))),o=pr.fn("SessionStatus.get")(function*(i){return(yield*B.get(t)).get(i)??{type:"idle"}}),n=pr.fn("SessionStatus.list")(function*(){return new Map(yield*B.get(t))}),r=pr.fn("SessionStatus.set")(function*(i,a){let c=yield*B.get(t);if(yield*e.publish(Ba.Status,{sessionID:i,status:a}),a.type==="idle"){yield*e.publish(Ba.Idle,{sessionID:i}),c.delete(i);return}c.set(i,a)});return fr.of({get:o,list:n,set:r})})),Sh=ge.make({service:fr,layer:Ih,deps:[we.node]});var qo={};ae(qo,{Service:()=>mr,SessionRunState:()=>qo,node:()=>Ah});var ps={};ae(ps,{Busy:()=>Ei,Cancelled:()=>Mn,Runner:()=>ps,make:()=>kh});import{Cause as Di,Deferred as Oo,Effect as Pe,Exit as Dd,Fiber as $a,Schema as Ed,SynchronizedRef as ln}from"effect";var Mn=class extends Ed.TaggedErrorClass()("RunnerCancelled",{}){static{s(this,"Cancelled")}},Ei=class extends Ed.TaggedErrorClass()("RunnerBusy",{}){static{s(this,"Busy")}},kh=s((e,t)=>{let o=ln.makeUnsafe({_tag:"Idle"}),n=t?.onIdle??Pe.void,r=t?.onBusy??Pe.void,i=t?.onInterrupt,a=0,c=s(()=>ln.getUnsafe(o),"state"),d=s(()=>(a+=1,a),"next"),u=s((y,v)=>Dd.isFailure(v)&&Di.hasInterruptsOnly(v.cause)?Oo.fail(y,new Mn).pipe(Pe.asVoid):Oo.done(y,v).pipe(Pe.asVoid),"complete"),l=s(y=>Oo.await(y).pipe(Pe.catchTag("RunnerCancelled",v=>i??Pe.die(v))),"awaitDone"),m=s(()=>ln.modify(o,y=>[y._tag==="Idle"?n:Pe.void,y]).pipe(Pe.flatten),"idleIfCurrent"),h=s((y,v,P)=>ln.modify(o,b=>[Pe.gen(function*(){b._tag==="Running"&&b.run.id===y&&(yield*n),yield*u(v,P)}),b._tag==="Running"&&b.run.id===y?{_tag:"Idle"}:b]).pipe(Pe.flatten),"finishRun"),g=s((y,v)=>Pe.gen(function*(){let P=d(),b=yield*y.pipe(Pe.onExit(T=>h(P,v,T)),Pe.forkIn(e));return{id:P,done:v,fiber:b}}),"startRun"),w=s(y=>ln.modifyEffect(o,Pe.fnUntraced(function*(v){if(v._tag==="Shell"&&v.shell.id===y)return[n,{_tag:"Idle"}];if(v._tag==="ShellThenRun"&&v.shell.id===y){let P=yield*g(v.run.work,v.run.done);return[Pe.void,{_tag:"Running",run:P}]}return[Pe.void,v]})).pipe(Pe.flatten),"finishShell"),k=s(y=>Pe.gen(function*(){y.ready&&(yield*y.ready.await.pipe(Pe.exit,Pe.asVoid)),yield*Oo.succeed(y.cancelled,void 0).pipe(Pe.asVoid),yield*$a.interrupt(y.fiber)}),"stopShell"),p=s(y=>ln.modifyEffect(o,Pe.fnUntraced(function*(v){switch(v._tag){case"Running":case"ShellThenRun":return[l(v.run.done),v];case"Shell":{let P={id:d(),done:yield*Oo.make(),work:y};return[l(P.done),{_tag:"ShellThenRun",shell:v.shell,run:P}]}case"Idle":{let P=yield*Oo.make(),b=yield*g(y,P);return[l(P),{_tag:"Running",run:b}]}}})).pipe(Pe.flatten),"ensureRunning"),f=s((y,v)=>ln.modifyEffect(o,Pe.fnUntraced(function*(P){if(P._tag!=="Idle")return[Pe.fail(new Ei),P];yield*r;let b=d(),T=yield*Oo.make(),E=yield*y.pipe(Pe.ensuring(w(b)),Pe.forkChild),j={id:b,cancelled:T,ready:v,fiber:E};return[Pe.gen(function*(){let _=yield*$a.await(E);return Dd.isSuccess(_)?_.value:Di.hasInterruptsOnly(_.cause)||(yield*Oo.isDone(T))&&Di.hasInterrupts(_.cause)&&!Di.hasDies(_.cause)?i?yield*i:yield*Pe.die(new Mn):yield*Pe.failCause(_.cause)}),{_tag:"Shell",shell:j}]})).pipe(Pe.flatten),"startShell"),S=ln.modify(o,y=>{switch(y._tag){case"Idle":return[Pe.void,y];case"Running":return[Pe.gen(function*(){yield*$a.interrupt(y.run.fiber),yield*Oo.fail(y.run.done,new Mn).pipe(Pe.asVoid),yield*m()}),{_tag:"Idle"}];case"Shell":return[Pe.gen(function*(){yield*k(y.shell),yield*m()}),{_tag:"Idle"}];case"ShellThenRun":return[Pe.gen(function*(){yield*k(y.shell),yield*Oo.fail(y.run.done,new Mn).pipe(Pe.asVoid),yield*m()}),{_tag:"Idle"}]}}).pipe(Pe.flatten);return{get state(){return c()},get busy(){return c()._tag!=="Idle"},ensureRunning:p,startShell:f,cancel:S}},"make");import{Effect as vt,Layer as Dh,Scope as Eh,Context as Th}from"effect";var mr=class extends Th.Service()("@opencode/SessionRunState"){static{s(this,"Service")}},Ph=Dh.effect(mr,vt.gen(function*(){let e=yield*Tn.Service,t=yield*po.Service,o=yield*B.make(vt.fn("SessionRunState.state")(function*(){let u=yield*Eh.Scope,l=new Map;return yield*vt.addFinalizer(vt.fnUntraced(function*(){yield*vt.forEach(l.values(),m=>m.cancel,{concurrency:"unbounded",discard:!0}),l.clear()})),{runners:l,scope:u}})),n=vt.fn("SessionRunState.runner")(function*(u,l){let m=yield*B.get(o),h=m.runners.get(u);if(h)return h;let g=ps.make(m.scope,{onIdle:vt.gen(function*(){m.runners.delete(u),yield*t.set(u,{type:"idle"})}),onBusy:t.set(u,{type:"busy"}),onInterrupt:l});return m.runners.set(u,g),g}),r=vt.fn("SessionRunState.assertNotBusy")(function*(u){(yield*B.get(o)).runners.get(u)?.busy&&(yield*Td(u))}),i=vt.fn("SessionRunState.cancel")(function*(u){yield*Rh(e,u);let m=(yield*B.get(o)).runners.get(u);if(!m){yield*t.set(u,{type:"idle"});return}yield*m.cancel}),a=vt.fn("SessionRunState.busy")(function*(){return[...(yield*B.get(o)).runners.entries()].filter(([,l])=>l.busy).map(([l])=>l)}),c=vt.fn("SessionRunState.ensureRunning")(function*(u,l,m){return yield*(yield*n(u,l)).ensureRunning(m)}),d=vt.fn("SessionRunState.startShell")(function*(u,l,m,h){return yield*(yield*n(u,l)).startShell(m,h).pipe(vt.catchTag("RunnerBusy",()=>vt.fail(Td(u))))});return mr.of({assertNotBusy:r,cancel:i,busy:a,ensureRunning:c,startShell:d})})),Rh=vt.fn("SessionRunState.cancelBackgroundJobs")(function*(e,t){let o=yield*e.list(),n=new Set([t]),r=new Set,i=s(c=>c.status!=="running"||r.has(c.id)?!1:n.has(c.id)||typeof c.metadata?.sessionId=="string"&&n.has(c.metadata.sessionId)?!0:typeof c.metadata?.parentSessionId=="string"&&n.has(c.metadata.parentSessionId),"matches"),a=o.filter(i);for(;a.length>0;)yield*vt.forEach(a,c=>e.cancel(c.id).pipe(vt.tap(()=>vt.sync(()=>{r.add(c.id),n.add(c.id),typeof c.metadata?.sessionId=="string"&&n.add(c.metadata.sessionId)}))),{concurrency:"unbounded",discard:!0}),a=o.filter(i)});function Td(e){return new ce.BusyError({sessionID:e})}s(Td,"busyError");var Ah=ge.make({service:mr,layer:Ph,deps:[Tn.node,po.node]});var mo={};ae(mo,{LLM:()=>mo,OUTPUT_TOKEN_MAX:()=>Ww,Service:()=>_n,hasToolCalls:()=>zw,node:()=>Gw,use:()=>qw});import{Context as Nw,Effect as Pt,Layer as Fw}from"effect";import*as fo from"effect/Stream";import{streamText as Bw,wrapLanguageModel as $w}from"ai";import{GitLabWorkflowLanguageModel as Uu}from"gitlab-ai-provider";var fs={};ae(fs,{Wildcard:()=>fs,all:()=>Ch,allStructured:()=>Mh,match:()=>Ti});import{sortBy as Pd,pipe as Rd}from"remeda";function Ti(e,t){e&&(e=e.replaceAll("\\","/")),t&&(t=t.replaceAll("\\","/"));let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");o.endsWith(" .*")&&(o=o.slice(0,-3)+"( .*)?");let n=process.platform==="win32"?"si":"s";return new RegExp("^"+o+"$",n).test(e)}s(Ti,"match");function Ch(e,t){let o=Rd(t,Object.entries,Pd([([r])=>r.length,"asc"],[([r])=>r,"asc"])),n;for(let[r,i]of o)if(Ti(e,r)){n=i;continue}return n}s(Ch,"all");function Mh(e,t){let o=Rd(t,Object.entries,Pd([([r])=>r.length,"asc"],[([r])=>r,"asc"])),n;for(let[r,i]of o){let a=r.split(/\s+/);if(Ti(e.head,a[0])&&(a.length===1||Wa(e.tail,a.slice(1)))){n=i;continue}}return n}s(Mh,"allStructured");function Wa(e,t){if(t.length===0)return!0;let[o,...n]=t;if(o==="*")return Wa(e,n);for(let r=0;r<e.length;r++)if(Ti(e[r],o)&&Wa(e.slice(r+1),n))return!0;return!1}s(Wa,"matchSequence");import*as ju from"effect/Option";import*as Nu from"@effect/opentelemetry/Tracer";var hr={};ae(hr,{LLMAISDK:()=>hr,adapterState:()=>Od,toLLMEvents:()=>Lh});import{Effect as wt,Schema as Md}from"effect";import"ai";function Od(){return{step:0,text:0,reasoning:0,currentTextID:void 0,currentReasoningID:void 0,toolNames:{},copilotTotalNanoAiu:void 0}}s(Od,"adapterState");function Ad(e){return Md.is(hl)(e)?e:"unknown"}s(Ad,"finishReason");function oo(e){if(e!=null)return Md.is(ml)(e)?e:void 0}s(oo,"providerMetadata");function Oh(e){if(!e||typeof e!="object")return;let t=e,o=t.response&&typeof t.response=="object"?t.response:void 0,n=t.copilot_usage??o?.copilot_usage;if(!n||typeof n!="object")return;let r=n.total_nano_aiu;if(!(typeof r!="number"||!Number.isFinite(r)||r<0))return r}s(Oh,"copilotTotalNanoAiu");function Cd(e){if(!e||typeof e!="object")return;let t=e,o=Object.entries({inputTokens:t.inputTokens,outputTokens:t.outputTokens,totalTokens:t.totalTokens,reasoningTokens:t.outputTokenDetails?.reasoningTokens??t.reasoningTokens,cacheReadInputTokens:t.inputTokenDetails?.cacheReadTokens??t.cachedInputTokens,cacheWriteInputTokens:t.inputTokenDetails?.cacheWriteTokens}).filter(n=>n[1]!==void 0);return o.length===0?void 0:Object.fromEntries(o)}s(Cd,"usage");function qa(e,t){return e.currentTextID=t??e.currentTextID??`text-${e.text++}`,e.currentTextID}s(qa,"currentTextID");function Va(e,t){return e.currentReasoningID=t??e.currentReasoningID??`reasoning-${e.reasoning++}`,e.currentReasoningID}s(Va,"currentReasoningID");function Lh(e,t){switch(t.type){case"start":return wt.succeed([]);case"start-step":return wt.succeed([nt.stepStart({index:e.step})]);case"finish-step":return t.rawFinishReason==="network_error"?wt.fail(new Kl.ResponseStreamError("Provider finish_reason: network_error")):wt.sync(()=>{let o=oo(t.providerMetadata),n=e.copilotTotalNanoAiu===void 0?o:{...o,copilot:{...o?.copilot,totalNanoAiu:e.copilotTotalNanoAiu}};return e.copilotTotalNanoAiu=void 0,[nt.stepFinish({index:e.step++,reason:Ad(t.finishReason),usage:Cd(t.usage),providerMetadata:n,...typeof t.response?.modelId=="string"?{responseModelID:t.response.modelId}:{}})]});case"finish":return wt.sync(()=>{let o=[nt.finish({reason:Ad(t.finishReason),usage:Cd(t.totalUsage),providerMetadata:"providerMetadata"in t?oo(t.providerMetadata):void 0})];return Object.assign(e,Od()),o});case"text-start":return wt.sync(()=>(e.currentTextID=qa(e,t.id),[nt.textStart({id:e.currentTextID,providerMetadata:oo(t.providerMetadata)})]));case"text-delta":return wt.succeed([nt.textDelta({id:qa(e,t.id),text:t.text,providerMetadata:oo(t.providerMetadata)})]);case"text-end":return wt.sync(()=>{let o=qa(e,t.id);return e.currentTextID=void 0,[nt.textEnd({id:o,providerMetadata:oo(t.providerMetadata)})]});case"reasoning-start":return wt.sync(()=>(e.currentReasoningID=Va(e,t.id),[nt.reasoningStart({id:e.currentReasoningID,providerMetadata:oo(t.providerMetadata)})]));case"reasoning-delta":return wt.succeed([nt.reasoningDelta({id:Va(e,t.id),text:t.text,providerMetadata:oo(t.providerMetadata)})]);case"reasoning-end":return wt.sync(()=>{let o=Va(e,t.id);return e.currentReasoningID=void 0,[nt.reasoningEnd({id:o,providerMetadata:oo(t.providerMetadata)})]});case"tool-input-start":return wt.sync(()=>(e.toolNames[t.id]=t.toolName,[nt.toolInputStart({id:t.id,name:t.toolName,providerMetadata:oo(t.providerMetadata)})]));case"tool-input-delta":return wt.succeed([nt.toolInputDelta({id:t.id,name:e.toolNames[t.id]??"unknown",text:t.delta??""})]);case"tool-input-end":return wt.succeed([nt.toolInputEnd({id:t.id,name:e.toolNames[t.id]??"unknown",providerMetadata:oo(t.providerMetadata)})]);case"tool-call":return wt.sync(()=>(e.toolNames[t.toolCallId]=t.toolName,[nt.toolCall({id:t.toolCallId,name:t.toolName,input:t.input,providerExecuted:"providerExecuted"in t?t.providerExecuted:void 0,providerMetadata:oo(t.providerMetadata)})]));case"tool-result":return wt.sync(()=>{let o=e.toolNames[t.toolCallId]??"unknown";return delete e.toolNames[t.toolCallId],[nt.toolResult({id:t.toolCallId,name:o,result:gl.make(t.output),providerExecuted:"providerExecuted"in t?t.providerExecuted:void 0,providerMetadata:oo(t.providerMetadata)})]});case"tool-error":return wt.sync(()=>{let o=e.toolNames[t.toolCallId]??("toolName"in t?t.toolName:"unknown");return delete e.toolNames[t.toolCallId],[nt.toolError({id:t.toolCallId,name:o,message:vo(t.error),error:t.error,providerMetadata:oo(t.providerMetadata)})]});case"error":return wt.fail(t.error);case"abort":case"source":case"file":case"tool-output-denied":case"tool-approval-request":return wt.succeed([]);case"raw":return wt.sync(()=>(e.copilotTotalNanoAiu=Oh(t.rawValue)??e.copilotTotalNanoAiu,[]));default:{let o=t;return wt.succeed([])}}}s(Lh,"toLLMEvents");var ks={};ae(ks,{LLMNativeRuntime:()=>ks,nativeTools:()=>vu,status:()=>Iw,stream:()=>Sw});import{asSchema as xw}from"ai";import{Effect as Ln,FiberSet as ac,Queue as Ni}from"effect";import*as bt from"effect/Stream";import{FetchHttpClient as vw}from"effect/unstable/http";var Ss={};ae(Ss,{LLMNative:()=>Ss,model:()=>wu,request:()=>bw});var Pi={};ae(Pi,{configure:()=>za,id:()=>Ld,model:()=>Nh,provider:()=>_d,routes:()=>_h});var Ld=at.make("anthropic"),_h=[ka],Uh=s(e=>"auth"in e&&e.auth?e.auth:gt.optional("apiKey"in e?e.apiKey:void 0,"apiKey").orElse(gt.config("ANTHROPIC_API_KEY")).pipe(gt.header("x-api-key")),"auth"),jh=s(e=>{let{apiKey:t,auth:o,baseURL:n,...r}=e;return ka.with({...r,endpoint:{baseURL:n},auth:Uh(e)})},"configuredRoute"),za=s((e={})=>{let t=jh(e);return{id:Ld,model:s(o=>t.model({id:o}),"model"),configure:za}},"configure"),_d=za(),Nh=_d.model;var Ai={};ae(Ai,{configure:()=>Ka,id:()=>Ya,model:()=>qg,provider:()=>Hd,routes:()=>Bg});import{Effect as yr,Schema as L}from"effect";var ms={};ae(ms,{BedrockEventStream:()=>ms,framing:()=>Yh});import{EventStreamCodec as Fh}from"@smithy/eventstream-codec";import{fromUtf8 as Bh,toUtf8 as $h}from"@smithy/util-utf8";import{Effect as Ud,Stream as Wh}from"effect";var qh=new Fh($h,Bh),Vh=new TextDecoder,zh={buffer:new Uint8Array(0),offset:0},Gh=s((e,t)=>{let o=e.buffer.length-e.offset,n=new Uint8Array(o+t.length);return n.set(e.buffer.subarray(e.offset),0),n.set(t,o),{buffer:n,offset:0}},"appendChunk"),Hh=s(e=>(t,o)=>Ud.gen(function*(){let n=Gh(t,o),r=[];for(;n.buffer.length-n.offset>=4;){let i=n.buffer.subarray(n.offset),a=new DataView(i.buffer,i.byteOffset,i.byteLength).getUint32(0,!1);if(i.length<a)break;let c=yield*Ud.try({try:s(()=>qh.decode(i.subarray(0,a)),"try"),catch:s(m=>Ie.eventError(e,`Failed to decode Bedrock Converse event-stream frame: ${m instanceof Error?m.message:String(m)}`),"catch")});if(n={buffer:n.buffer,offset:n.offset+a},c.headers[":message-type"]?.value!=="event")continue;let d=c.headers[":event-type"]?.value;if(typeof d!="string")continue;let u=Vh.decode(c.body);if(!u)continue;let l=yield*Ie.parseJson(e,u,"Failed to parse Bedrock Converse event-stream payload");delete l.p,r.push({[d]:l})}return[n,r]}),"consumeFrames"),Yh=s(e=>({id:"aws-event-stream",frame:s(t=>t.pipe(Wh.mapAccumEffect(()=>zh,Hh(e))),"frame")}),"framing");var gr={};ae(gr,{BedrockAuth:()=>gr,auth:()=>Xh,sigV4:()=>Fd});import{AwsV4Signer as Kh}from"aws4fetch";import{Effect as Nd}from"effect";import{Headers as jd}from"effect/unstable/http";var Jh=s(e=>Nd.tryPromise({try:s(async()=>{let t=await new Kh({url:e.url,method:"POST",headers:Object.entries(e.headers),body:e.body,region:e.credentials.region,accessKeyId:e.credentials.accessKeyId,secretAccessKey:e.credentials.secretAccessKey,sessionToken:e.credentials.sessionToken,service:"bedrock"}).sign();return Object.fromEntries(t.headers.entries())},"try"),catch:s(t=>Ie.invalidRequest(`Bedrock Converse SigV4 signing failed: ${t instanceof Error?t.message:String(t)}`),"catch")}),"signRequest"),Fd=s(e=>gt.custom(t=>Nd.gen(function*(){if(!e)return yield*Ie.invalidRequest("Bedrock Converse requires either route bearer auth or AWS credentials configured on the route");let o=jd.set(t.headers,"content-type","application/json"),n=yield*Jh({url:t.url,body:t.body,headers:o,credentials:e});return jd.setAll(o,n)})),"sigV4"),Xh=Fd(void 0);var no={};ae(no,{BEDROCK_BREAKPOINT_CAP:()=>Bd,BedrockCache:()=>no,CachePointBlock:()=>Qh,block:()=>og,breakpoints:()=>Zh});import{Schema as hs}from"effect";var Qh=hs.Struct({cachePoint:hs.Struct({type:hs.tag("default"),ttl:hs.optional(hs.Literals(["5m","1h"]))})}),Bd=4,Zh=s(()=>Ul(Bd),"breakpoints"),eg={cachePoint:{type:"default"}},tg={cachePoint:{type:"default",ttl:"1h"}},og=s((e,t)=>{if(!(t?.type!=="ephemeral"&&t?.type!=="persistent")){if(e.remaining<=0){e.dropped+=1;return}return e.remaining-=1,jl(t.ttlSeconds)==="1h"?tg:eg}},"block");var Vo={};ae(Vo,{BedrockMedia:()=>Vo,DocumentBlock:()=>sg,DocumentFormat:()=>Vd,ImageBlock:()=>rg,ImageFormat:()=>qd,lower:()=>ag});import{Effect as ng,Schema as Io}from"effect";var qd=Io.Literals(["png","jpeg","gif","webp"]),rg=Io.Struct({image:Io.Struct({format:qd,source:Io.Struct({bytes:Io.String})})}),Vd=Io.Literals(["pdf","csv","doc","docx","xls","xlsx","html","txt","md"]),sg=Io.Struct({document:Io.Struct({format:Vd,name:Io.String,source:Io.Struct({bytes:Io.String})})}),$d={"image/png":"png","image/jpeg":"jpeg","image/jpg":"jpeg","image/gif":"gif","image/webp":"webp"},Wd={"application/pdf":"pdf","text/csv":"csv","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","text/html":"html","text/plain":"txt","text/markdown":"md"},ig=s((e,t,o)=>({document:{format:t,name:e.filename??`document.${t}`,source:{bytes:o}}}),"documentBlock"),ag=ng.fn("BedrockMedia.lower")(function*(e){let t=e.mediaType.toLowerCase(),o=$d[t];if(o){let r=yield*Ie.validateMedia("Bedrock Converse",e,new Set(Object.keys($d)));return{image:{format:o,source:{bytes:r.base64}}}}if(t.startsWith("image/"))return yield*Ie.invalidRequest(`Bedrock Converse does not support image media type ${e.mediaType}`);let n=Wd[t];if(n){let r=yield*Ie.validateMedia("Bedrock Converse",e,new Set(Object.keys(Wd)));return ig(e,n,r.base64)}return yield*Ie.invalidRequest(`Bedrock Converse does not support media type ${e.mediaType}`)});var gs="bedrock-converse",Ga=L.Struct({text:L.String}),cg=L.Struct({toolUse:L.Struct({toolUseId:L.String,name:L.String,input:L.Unknown})}),lg=L.Union([L.Struct({text:L.String}),L.Struct({json:L.Unknown}),Vo.ImageBlock]),dg=L.Struct({toolResult:L.Struct({toolUseId:L.String,content:L.Array(lg),status:L.optional(L.Literals(["success","error"]))})}),ug=L.Struct({reasoningContent:L.Struct({reasoningText:L.optional(L.Struct({text:L.String,signature:L.optional(L.String)}))})}),pg=L.Union([Ga,Vo.ImageBlock,Vo.DocumentBlock,dg,no.CachePointBlock]),fg=L.Union([Ga,ug,cg,no.CachePointBlock]),mg=L.Union([L.Struct({role:L.Literal("user"),content:L.Array(pg)}),L.Struct({role:L.Literal("assistant"),content:L.Array(fg)})]).pipe(L.toTaggedUnion("role")),hg=L.Union([Ga,no.CachePointBlock]),gg=L.Struct({toolSpec:L.Struct({name:L.String,description:L.String,inputSchema:L.Struct({json:as})})}),yg=L.Union([gg,no.CachePointBlock]),wg=L.Union([L.Struct({auto:L.Struct({})}),L.Struct({any:L.Struct({})}),L.Struct({tool:L.Struct({name:L.String})})]),bg={modelId:L.String,messages:L.Array(mg),system:tn(hg),inferenceConfig:L.optional(L.Struct({maxTokens:L.optional(L.Number),temperature:L.optional(L.Number),topP:L.optional(L.Number),stopSequences:tn(L.String)})),toolConfig:L.optional(L.Struct({tools:L.Array(yg),toolChoice:L.optional(wg)})),additionalModelRequestFields:L.optional(as)},xg=L.Struct(bg),vg=L.Struct({inputTokens:L.optional(L.Number),outputTokens:L.optional(L.Number),totalTokens:L.optional(L.Number),cacheReadInputTokens:L.optional(L.Number),cacheWriteInputTokens:L.optional(L.Number)}),Ig=L.Struct({messageStart:L.optional(L.Struct({role:L.String})),contentBlockStart:L.optional(L.Struct({contentBlockIndex:L.Number,start:L.optional(L.Struct({toolUse:L.optional(L.Struct({toolUseId:L.String,name:L.String}))}))})),contentBlockDelta:L.optional(L.Struct({contentBlockIndex:L.Number,delta:L.optional(L.Struct({text:L.optional(L.String),toolUse:L.optional(L.Struct({input:L.String})),reasoningContent:L.optional(L.Struct({text:L.optional(L.String),signature:L.optional(L.String)}))}))})),contentBlockStop:L.optional(L.Struct({contentBlockIndex:L.Number})),messageStop:L.optional(L.Struct({stopReason:L.String,additionalModelResponseFields:L.optional(L.Unknown)})),metadata:L.optional(L.Struct({usage:L.optional(vg),metrics:L.optional(L.Unknown)})),internalServerException:L.optional(L.Struct({message:L.String})),modelStreamErrorException:L.optional(L.Struct({message:L.String})),validationException:L.optional(L.Struct({message:L.String})),throttlingException:L.optional(L.Struct({message:L.String})),serviceUnavailableException:L.optional(L.Struct({message:L.String}))}),Sg=s((e,t)=>({toolSpec:{name:e.name,description:e.description,inputSchema:{json:t}}}),"lowerToolSpec"),kg=s((e,t,o)=>{let n=[];for(let r of o){n.push(Sg(r,ci.modelCompatibility(r.inputSchema,e)));let i=no.block(t,r.cache);i&&n.push(i)}return n},"lowerTools"),Ri=s((e,t,o)=>{let n=no.block(e,o);return n?[{text:t},n]:[{text:t}]},"textWithCache"),Dg=s(e=>Ie.matchToolChoice("Bedrock Converse",e,{auto:s(()=>({auto:{}}),"auto"),none:s(()=>{},"none"),required:s(()=>({any:{}}),"required"),tool:s(t=>({tool:{name:t}}),"tool")}),"lowerToolChoice"),Eg=s(e=>({bedrock:e}),"bedrockMetadata"),Tg=s(e=>{let t=e.providerMetadata?.bedrock;return e.encrypted??(Ie.isRecord(t)&&typeof t.signature=="string"?t.signature:void 0)},"reasoningSignature"),Pg=s(e=>({toolUse:{toolUseId:e.id,name:e.name,input:e.input}}),"lowerToolCall"),Rg=yr.fn("BedrockConverse.lowerToolResultContent")(function*(e){if(e.result.type==="text"||e.result.type==="error")return[{text:Ie.toolResultText(e)}];if(e.result.type==="json")return[{json:e.result.value}];let t=[];for(let o of e.result.value){if(o.type==="text"){t.push({text:o.text});continue}let n=yield*Vo.lower({type:"media",mediaType:o.mime,data:o.uri,filename:o.name});if(!("image"in n))return yield*Ie.invalidRequest("Bedrock Converse only supports image media in tool results");t.push(n)}return t}),Ag=yr.fn("BedrockConverse.lowerToolResult")(function*(e){return{toolResult:{toolUseId:e.id,content:yield*Rg(e),status:e.result.type==="error"?"error":"success"}}}),Cg=yr.fn("BedrockConverse.lowerMessages")(function*(e,t){let o=[];for(let n of e.messages){if(n.role==="system"){let i=yield*Ie.wrappedSystemUpdate("Bedrock Converse",n),a=Ri(t,i.text,i.cache),c=o.at(-1);c?.role==="user"?o[o.length-1]={role:"user",content:[...c.content,...a]}:o.push({role:"user",content:a});continue}if(n.role==="user"){let i=[];for(let a of n.content){if(!Ie.supportsContent(a,["text","media"]))return yield*Ie.unsupportedContent("Bedrock Converse","user",["text","media"]);if(a.type==="text"){i.push(...Ri(t,a.text,a.cache));continue}if(a.type==="media"){i.push(yield*Vo.lower(a));continue}}o.push({role:"user",content:i});continue}if(n.role==="assistant"){let i=[];for(let a of n.content){if(!Ie.supportsContent(a,["text","reasoning","tool-call"]))return yield*Ie.unsupportedContent("Bedrock Converse","assistant",["text","reasoning","tool-call"]);if(a.type==="text"){i.push(...Ri(t,a.text,a.cache));continue}if(a.type==="reasoning"){i.push({reasoningContent:{reasoningText:{text:a.text,signature:Tg(a)}}});continue}if(a.type==="tool-call"){i.push(Pg(a));continue}}o.push({role:"assistant",content:i});continue}let r=[];for(let i of n.content){if(!Ie.supportsContent(i,["tool-result"]))return yield*Ie.unsupportedContent("Bedrock Converse","tool",["tool-result"]);r.push(yield*Ag(i));let a=no.block(t,i.cache);a&&r.push(a)}o.push({role:"user",content:r})}return o}),Mg=s((e,t)=>t.flatMap(o=>Ri(e,o.text,o.cache)),"lowerSystem"),Og=yr.fn("BedrockConverse.fromRequest")(function*(e){let t=e.toolChoice?yield*Dg(e.toolChoice):void 0,o=e.generation,n=no.breakpoints(),r=e.tools.length>0&&e.toolChoice?.type!=="none"?{tools:kg(e.model.compatibility?.toolSchema,n,e.tools),toolChoice:t}:void 0,i=e.system.length===0?void 0:Mg(n,e.system),a=yield*Cg(e,n);return n.dropped>0&&(yield*yr.logWarning(`Bedrock Converse: dropped ${n.dropped} cache breakpoint(s); the API allows at most ${no.BEDROCK_BREAKPOINT_CAP} per request.`)),{modelId:e.model.id,messages:a,system:i,inferenceConfig:o?.maxTokens===void 0&&o?.temperature===void 0&&o?.topP===void 0&&(o?.stop===void 0||o.stop.length===0)?void 0:{maxTokens:o?.maxTokens,temperature:o?.temperature,topP:o?.topP,stopSequences:o?.stop},toolConfig:r,additionalModelRequestFields:o?.topK===void 0?void 0:{top_k:o.topK}}}),Lg=s(e=>e==="end_turn"||e==="stop_sequence"?"stop":e==="max_tokens"?"length":e==="tool_use"?"tool-calls":e==="content_filtered"||e==="guardrail_intervened"?"content-filter":"unknown","mapFinishReason"),_g=s(e=>{if(!e)return;let t=(e.cacheReadInputTokens??0)+(e.cacheWriteInputTokens??0),o=Ie.subtractTokens(e.inputTokens,t);return new Bo({inputTokens:e.inputTokens,outputTokens:e.outputTokens,nonCachedInputTokens:o,cacheReadInputTokens:e.cacheReadInputTokens,cacheWriteInputTokens:e.cacheWriteInputTokens,totalTokens:Ie.totalTokens(e.inputTokens,e.outputTokens,e.totalTokens),providerMetadata:{bedrock:e}})},"mapUsage"),Ug=s((e,t)=>yr.gen(function*(){if(t.contentBlockStart?.start?.toolUse){let o=t.contentBlockStart.contentBlockIndex,n=[],r=xt.stepStart(e.lifecycle,n);return[{...e,lifecycle:r,tools:rr.start(e.tools,o,{id:t.contentBlockStart.start.toolUse.toolUseId,name:t.contentBlockStart.start.toolUse.name})},[...n,nt.toolInputStart({id:t.contentBlockStart.start.toolUse.toolUseId,name:t.contentBlockStart.start.toolUse.name})]]}if(t.contentBlockDelta?.delta?.text){let o=[];return[{...e,lifecycle:xt.textDelta(e.lifecycle,o,`text-${t.contentBlockDelta.contentBlockIndex}`,t.contentBlockDelta.delta.text)},o]}if(t.contentBlockDelta?.delta?.reasoningContent){let o=t.contentBlockDelta.contentBlockIndex,n=t.contentBlockDelta.delta.reasoningContent,r=[];return[{...e,lifecycle:n.text?xt.reasoningDelta(e.lifecycle,r,`reasoning-${o}`,n.text):e.lifecycle,reasoningSignatures:n.signature?{...e.reasoningSignatures,[o]:n.signature}:e.reasoningSignatures},r]}if(t.contentBlockDelta?.delta?.toolUse){let o=t.contentBlockDelta.contentBlockIndex,n=rr.appendExisting(gs,e.tools,o,t.contentBlockDelta.delta.toolUse.input,"Bedrock Converse tool delta is missing its tool call");if(rr.isError(n))return yield*n;let r=[],i=n.events.length?xt.stepStart(e.lifecycle,r):e.lifecycle;return r.push(...n.events),[{...e,lifecycle:i,tools:n.tools},r]}if(t.contentBlockStop){let o=t.contentBlockStop.contentBlockIndex,n=yield*rr.finish(gs,e.tools,o),r=[],i=n.events??[],a=i.length?xt.stepStart(e.lifecycle,r):xt.reasoningEnd(xt.textEnd(e.lifecycle,r,`text-${o}`),r,`reasoning-${o}`,e.reasoningSignatures[o]?Eg({signature:e.reasoningSignatures[o]}):void 0);return r.push(...i),[{...e,hasToolCalls:i.some(nt.is.toolCall)?!0:e.hasToolCalls,lifecycle:a,tools:n.tools,reasoningSignatures:Object.fromEntries(Object.entries(e.reasoningSignatures).filter(([c])=>c!==String(o)))},r]}if(t.messageStop)return[{...e,pendingFinish:{reason:Lg(t.messageStop.stopReason),usage:e.pendingFinish?.usage}},[]];if(t.metadata){let o=_g(t.metadata.usage);return[{...e,pendingFinish:{reason:e.pendingFinish?.reason??"stop",usage:o}},[]]}if(t.internalServerException||t.modelStreamErrorException||t.serviceUnavailableException){let o=t.internalServerException?.message??t.modelStreamErrorException?.message??t.serviceUnavailableException?.message??"Bedrock Converse stream error";return[e,[nt.providerError({message:o,retryable:!0})]]}if(t.validationException||t.throttlingException){let o=t.validationException?.message??t.throttlingException?.message??"Bedrock Converse error";return[e,[nt.providerError({message:o,classification:t.validationException&&Sl(o)?"context-overflow":void 0,retryable:t.throttlingException!==void 0})]]}return[e,[]]}),"step"),jg=ms.framing(gs),Ng=s(e=>e.pendingFinish?(()=>{let t=[];return xt.finish(e.lifecycle,t,{reason:e.pendingFinish.reason==="stop"&&e.hasToolCalls?"tool-calls":e.pendingFinish.reason,usage:e.pendingFinish.usage}),t})():[],"onHalt"),Fg=In.make({id:gs,body:{schema:xg,from:Og},stream:{event:Ig,initial:s(()=>({tools:rr.empty(),pendingFinish:void 0,hasToolCalls:!1,lifecycle:xt.initial(),reasoningSignatures:{}}),"initial"),step:Ug,onHalt:Ng}}),Ha=or.make({id:gs,provider:"bedrock",protocol:Fg,endpoint:tr.path(({body:e})=>`/model/${encodeURIComponent(e.modelId)}/converse-stream`),auth:gr.auth,framing:jg}),zd=gr.sigV4;var Ya=at.make("amazon-bedrock"),Bg=[Ha],$g=s(e=>`https://bedrock-runtime.${e}.amazonaws.com`,"bedrockBaseURL"),Wg=s(e=>{let{apiKey:t,credentials:o,region:n,baseURL:r,...i}=e,a=n??o?.region??"us-east-1";return Ha.with({...i,provider:Ya,endpoint:{baseURL:r??$g(a)},auth:t===void 0?zd(o):gt.bearer(t)})},"configuredRoute"),Ka=s((e={})=>{let t=Wg(e);return{id:Ya,model:s(o=>t.model({id:o}),"model"),configure:Ka}},"configure"),Hd=Ka(),qg=Hd.model;var Ci={};ae(Ci,{configure:()=>Qa,id:()=>ys,provider:()=>Qg,routes:()=>Kg});var Vg=s(e=>Object.entries(e).filter(t=>t[1]!==void 0),"definedEntries"),Yd=s(e=>{let t=Object.fromEntries(Vg({store:e?.store,promptCacheKey:e?.promptCacheKey,reasoningEffort:e?.reasoningEffort,reasoningSummary:e?.reasoningSummary,include:e?.include,textVerbosity:e?.textVerbosity,serviceTier:e?.serviceTier}));if(Object.keys(t).length!==0)return{openai:t}},"openAIProviderOptions"),zg=s((e,t={})=>{let o=e.toLowerCase();if(!(!o.includes("gpt-5")||o.includes("gpt-5-chat")||o.includes("gpt-5-pro")))return Yd({reasoningEffort:"medium",reasoningSummary:"auto",include:["reasoning.encrypted_content"],textVerbosity:t.textVerbosity===!0&&o.includes("gpt-5.")&&!o.includes("codex")&&!o.includes("-chat")?"low":void 0})},"gpt5DefaultOptions"),Gg=s((e,t={})=>va(Yd({store:!1}),zg(e,t)),"openAIDefaultOptions"),dn=s((e,t,o={})=>({...t,providerOptions:va(Gg(e,o),t.providerOptions)}),"withOpenAIOptions");var ys=at.make("azure"),Jd=gt.remove("authorization"),Yg=s(e=>`https://${e.trim()}.openai.azure.com/openai/v1`,"resourceBaseURL"),Xd=Wo.with({id:"azure-openai-responses",provider:ys,auth:Jd,endpoint:{query:{"api-version":"v1"}}}),Qd=En.with({id:"azure-openai-chat",provider:ys,auth:Jd,endpoint:{query:{"api-version":"v1"}}}),Kg=[Xd,Qd],Jg=s(e=>{let{apiKey:t,apiVersion:o,resourceName:n,useCompletionUrls:r,baseURL:i,queryParams:a,...c}=e;if("auth"in c){let{auth:d,...u}=c;return u}return c},"defaults"),Xg=s(e=>"auth"in e&&e.auth?e.auth:gt.remove("authorization").andThen(gt.optional("apiKey"in e?e.apiKey:void 0,"apiKey").orElse(gt.config("AZURE_OPENAI_API_KEY")).pipe(gt.header("api-key"))),"auth"),Kd=s((e,t)=>e.with({auth:Xg(t),endpoint:{baseURL:t.baseURL??Yg(t.resourceName),query:{...t.apiVersion?{"api-version":t.apiVersion}:{},...t.queryParams}}}),"configuredRoute"),Qa=s(e=>{let t=Kd(Xd,e),o=Kd(Qd,e),n=Jg(e),r=s(a=>t.with(dn(a,n)).model({id:a}),"responses"),i=s(a=>o.with(dn(a,n)).model({id:a}),"chat");return{id:ys,model:s(a=>e.useCompletionUrls===!0?i(a):r(a),"model"),responses:r,chat:i,configure:Qa}},"configure"),Qg={id:ys,configure:Qa};var Zg=at.make("cloudflare-ai-gateway"),ey=at.make("cloudflare-workers-ai");var kP=rn.with({id:"cloudflare-ai-gateway",provider:Zg}),DP=rn.with({id:"cloudflare-workers-ai",provider:ey});var eu=at.make("github-copilot");var AP=En.with({provider:eu}),CP=Wo.with({provider:eu});var Mi={};ae(Mi,{configure:()=>ec,id:()=>iu,model:()=>Uy,provider:()=>au,routes:()=>Oy});import{Effect as bs,Schema as K}from"effect";var tu="gemini",ou=new Set(Ie.MEDIA_MIMES),ny="https://generativelanguage.googleapis.com/v1beta",ry=K.Struct({text:K.String,thought:K.optional(K.Boolean),thoughtSignature:K.optional(K.String)}),sy=K.Struct({inlineData:K.Struct({mimeType:K.String,data:K.String})}),iy=K.Struct({functionCall:K.Struct({name:K.String,args:K.Unknown}),thoughtSignature:K.optional(K.String)}),ay=K.Struct({functionResponse:K.Struct({name:K.String,response:K.Unknown})}),cy=K.Union([ry,sy,iy,ay]),nu=K.Struct({role:K.Literals(["user","model"]),parts:K.Array(cy)}),ly=K.Struct({parts:K.Array(K.Struct({text:K.String}))}),dy=K.Struct({name:K.String,description:K.String,parameters:K.optional(as)}),uy=K.Struct({functionDeclarations:K.Array(dy)}),py=K.Struct({functionCallingConfig:K.Struct({mode:K.Literals(["AUTO","NONE","ANY"]),allowedFunctionNames:tn(K.String)})}),fy=K.Struct({thinkingBudget:K.optional(K.Number),includeThoughts:K.optional(K.Boolean)}),my=K.Struct({maxOutputTokens:K.optional(K.Number),temperature:K.optional(K.Number),topP:K.optional(K.Number),topK:K.optional(K.Number),stopSequences:tn(K.String),thinkingConfig:K.optional(fy)}),hy={contents:K.Array(nu),systemInstruction:K.optional(ly),tools:tn(uy),toolConfig:K.optional(py),generationConfig:K.optional(my)},gy=K.Struct(hy),yy=K.Struct({cachedContentTokenCount:K.optional(K.Number),thoughtsTokenCount:K.optional(K.Number),promptTokenCount:K.optional(K.Number),candidatesTokenCount:K.optional(K.Number),totalTokenCount:K.optional(K.Number)}),wy=K.Struct({content:K.optional(nu),finishReason:K.optional(K.String)}),by=K.Struct({candidates:tn(wy),usageMetadata:K.optional(yy)}),xy=s((e,t)=>({name:e.name,description:e.description,parameters:Nl.convert(t)}),"lowerTool"),vy=s(e=>Ie.matchToolChoice("Gemini",e,{auto:s(()=>({functionCallingConfig:{mode:"AUTO"}}),"auto"),none:s(()=>({functionCallingConfig:{mode:"NONE"}}),"none"),required:s(()=>({functionCallingConfig:{mode:"ANY"}}),"required"),tool:s(t=>({functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t]}}),"tool")}),"lowerToolConfig"),Iy=bs.fn("Gemini.lowerUserPart")(function*(e){if(e.type==="text")return{text:e.text};let t=yield*Ie.validateMedia("Gemini",e,ou);return{inlineData:{mimeType:t.mime,data:t.base64}}}),ws=s(e=>({google:e}),"googleMetadata"),ru=s(e=>{let t=e?.google;return Ie.isRecord(t)&&typeof t.thoughtSignature=="string"?t.thoughtSignature:void 0},"thoughtSignature"),Sy=s(e=>({functionCall:{name:e.name,args:e.input},thoughtSignature:ru(e.providerMetadata)}),"lowerToolCall"),ky=bs.fn("Gemini.lowerMessages")(function*(e){let t=[];for(let o of e.messages){if(o.role==="system"){let r=yield*Ie.wrappedSystemUpdate("Gemini",o),i=t.at(-1);i?.role==="user"?t[t.length-1]={role:"user",parts:[...i.parts,{text:r.text}]}:t.push({role:"user",parts:[{text:r.text}]});continue}if(o.role==="user"){let r=[];for(let i of o.content){if(!Ie.supportsContent(i,["text","media"]))return yield*Ie.unsupportedContent("Gemini","user",["text","media"]);r.push(yield*Iy(i))}t.push({role:"user",parts:r});continue}if(o.role==="assistant"){let r=[];for(let i of o.content){if(!Ie.supportsContent(i,["text","reasoning","tool-call"]))return yield*Ie.unsupportedContent("Gemini","assistant",["text","reasoning","tool-call"]);if(i.type==="text"){r.push({text:i.text});continue}if(i.type==="reasoning"){r.push({text:i.text,thought:!0,thoughtSignature:ru(i.providerMetadata)});continue}if(i.type==="tool-call"){r.push(Sy(i));continue}}t.push({role:"model",parts:r});continue}let n=[];for(let r of o.content){if(!Ie.supportsContent(r,["tool-result"]))return yield*Ie.unsupportedContent("Gemini","tool",["tool-result"]);if(r.result.type!=="content"){n.push({functionResponse:{name:r.name,response:{name:r.name,content:Ie.toolResultText(r)}}});continue}let i=r.result.value,a=i.filter(c=>c.type==="text").map(c=>c.text);n.push({functionResponse:{name:r.name,response:{name:r.name,content:a.join(`
15
- `)}}});for(let c of i){if(c.type==="text")continue;let d=yield*Ie.validateToolFile("Gemini",c,ou);n.push({inlineData:{mimeType:d.mime,data:d.base64}})}}t.push({role:"user",parts:n})}return t}),Dy=s(e=>e.providerOptions?.gemini,"geminiOptions"),Ey=s(e=>{let t=Dy(e)?.thinkingConfig;if(!Ie.isRecord(t))return;let o={thinkingBudget:typeof t.thinkingBudget=="number"?t.thinkingBudget:void 0,includeThoughts:typeof t.includeThoughts=="boolean"?t.includeThoughts:void 0};return Object.values(o).some(n=>n!==void 0)?o:void 0},"thinkingConfig"),Ty=bs.fn("Gemini.fromRequest")(function*(e){let t=e.tools.length>0&&e.toolChoice?.type!=="none",o=e.generation,n=e.model.compatibility?.toolSchema,r={maxOutputTokens:o?.maxTokens,temperature:o?.temperature,topP:o?.topP,topK:o?.topK,stopSequences:o?.stop,thinkingConfig:Ey(e)};return{contents:yield*ky(e),systemInstruction:e.system.length===0?void 0:{parts:[{text:Ie.joinText(e.system)}]},tools:t?[{functionDeclarations:e.tools.map(i=>xy(i,ci.modelCompatibility(i.inputSchema,n)))}]:void 0,toolConfig:t&&e.toolChoice?yield*vy(e.toolChoice):void 0,generationConfig:Object.values(r).some(i=>i!==void 0)?r:void 0}}),Py=s(e=>{if(!e)return;let t=e.cachedContentTokenCount,o=Ie.subtractTokens(e.promptTokenCount,t),n=e.candidatesTokenCount!==void 0?e.candidatesTokenCount+(e.thoughtsTokenCount??0):void 0;return new Bo({inputTokens:e.promptTokenCount,outputTokens:n,nonCachedInputTokens:o,cacheReadInputTokens:t,reasoningTokens:e.thoughtsTokenCount,totalTokens:Ie.totalTokens(e.promptTokenCount,n,e.totalTokenCount),providerMetadata:{google:e}})},"mapUsage"),Ry=s((e,t)=>e==="STOP"?t?"tool-calls":"stop":e==="MAX_TOKENS"?"length":e==="IMAGE_SAFETY"||e==="RECITATION"||e==="SAFETY"||e==="BLOCKLIST"||e==="PROHIBITED_CONTENT"||e==="SPII"?"content-filter":e==="MALFORMED_FUNCTION_CALL"?"error":"unknown","mapFinishReason"),Ay=s(e=>e.finishReason||e.usage?(()=>{let t=[],o=e.reasoningSignature?xt.reasoningEnd(e.lifecycle,t,"reasoning-0",ws({thoughtSignature:e.reasoningSignature})):e.lifecycle;return xt.finish(o,t,{reason:Ry(e.finishReason,e.hasToolCalls),usage:e.usage}),t})():[],"finish"),Cy=s((e,t)=>{let o={...e,usage:t.usageMetadata?Py(t.usageMetadata)??e.usage:e.usage},n=t.candidates?.[0];if(!n?.content)return bs.succeed([{...o,finishReason:n?.finishReason??o.finishReason},[]]);let r=[],i=o.hasToolCalls,a=o.lifecycle,c=o.nextToolCallId,d=o.reasoningSignature;for(let u of n.content.parts){if("thoughtSignature"in u&&u.thoughtSignature&&"thought"in u&&u.thought&&(d=u.thoughtSignature),"text"in u&&u.text.length>0){if(u.thought){a=xt.reasoningDelta(a,r,"reasoning-0",u.text,u.thoughtSignature?ws({thoughtSignature:u.thoughtSignature}):void 0);continue}a=xt.reasoningEnd(a,r,"reasoning-0",d?ws({thoughtSignature:d}):void 0),a=xt.textDelta(a,r,"text-0",u.text);continue}if("functionCall"in u){let l=u.functionCall.args,m=`tool_${c++}`;a=xt.reasoningEnd(a,r,"reasoning-0",d?ws({thoughtSignature:d}):void 0),a=xt.stepStart(a,r),r.push(nt.toolCall({id:m,name:u.functionCall.name,input:l,providerMetadata:u.thoughtSignature?ws({thoughtSignature:u.thoughtSignature}):void 0})),i=!0}}return bs.succeed([{...o,hasToolCalls:i,lifecycle:a,nextToolCallId:c,reasoningSignature:d,finishReason:n.finishReason??o.finishReason},r])},"step"),My=In.make({id:tu,body:{schema:gy,from:Ty},stream:{event:In.jsonEvent(by),initial:s(()=>({hasToolCalls:!1,nextToolCallId:0,lifecycle:xt.initial()}),"initial"),step:Cy,onHalt:Ay}}),Za=or.make({id:tu,provider:"google",protocol:My,endpoint:tr.path(({request:e})=>`/models/${e.model.id}:streamGenerateContent?alt=sse`,{baseURL:ny}),auth:gt.none,framing:ri.sse});var iu=at.make("google"),Oy=[Za],Ly=s(e=>"auth"in e&&e.auth?e.auth:gt.optional("apiKey"in e?e.apiKey:void 0,"apiKey").orElse(gt.config("GOOGLE_GENERATIVE_AI_API_KEY")).pipe(gt.header("x-goog-api-key")),"auth"),_y=s(e=>{let{apiKey:t,auth:o,baseURL:n,...r}=e;return Za.with({...r,endpoint:{baseURL:n},auth:Ly(e)})},"configuredRoute"),ec=s((e={})=>{let t=_y(e);return{id:iu,model:s(o=>t.model({id:o}),"model"),configure:ec}},"configure"),au=ec(),Uy=au.model;var Oi={};ae(Oi,{chat:()=>qy,configure:()=>oc,id:()=>cu,model:()=>By,provider:()=>xs,responses:()=>$y,responsesWebSocket:()=>Wy,routes:()=>jy});var cu=at.make("openai"),jy=[Wo,Ea,En],Ny=s(e=>Ao.bearer(e,"OPENAI_API_KEY"),"auth"),Fy=s(e=>{let{apiKey:t,auth:o,baseURL:n,queryParams:r,...i}=e;return i},"defaults"),tc=s((e,t)=>e.with({auth:Ny(t),endpoint:{baseURL:t.baseURL,query:t.queryParams}}),"configuredRoute"),oc=s((e={})=>{let t=tc(Wo,e),o=tc(Ea,e),n=tc(En,e),r=Fy(e),i=s(d=>t.with(dn(d,r,{textVerbosity:!0})).model({id:d}),"responses");return{id:cu,model:i,responses:i,responsesWebSocket:s(d=>o.with(dn(d,r,{textVerbosity:!0})).model({id:d}),"responsesWebSocket"),chat:s(d=>n.with(dn(d,r)).model({id:d}),"chat"),configure:oc}},"configure"),xs=oc(),By=xs.model,$y=xs.responses,Wy=xs.responsesWebSocket,qy=xs.chat;var _i={};ae(_i,{baseten:()=>Gy,cerebras:()=>Hy,configure:()=>Li,deepinfra:()=>Yy,deepseek:()=>Ky,fireworks:()=>Jy,groq:()=>Xy,id:()=>du,provider:()=>zy,routes:()=>Vy,togetherai:()=>Qy});var Kt={baseten:{provider:"baseten",baseURL:"https://inference.baseten.co/v1"},cerebras:{provider:"cerebras",baseURL:"https://api.cerebras.ai/v1"},deepinfra:{provider:"deepinfra",baseURL:"https://api.deepinfra.com/v1/openai"},deepseek:{provider:"deepseek",baseURL:"https://api.deepseek.com/v1"},fireworks:{provider:"fireworks",baseURL:"https://api.fireworks.ai/inference/v1"},groq:{provider:"groq",baseURL:"https://api.groq.com/openai/v1"},openrouter:{provider:"openrouter",baseURL:"https://openrouter.ai/api/v1"},togetherai:{provider:"togetherai",baseURL:"https://api.together.xyz/v1"},xai:{provider:"xai",baseURL:"https://api.x.ai/v1"}},QP=Object.fromEntries(Object.values(Kt).map(e=>[e.provider,e]));var du=at.make("openai-compatible"),Vy=[rn],Li=s(e=>{let t=e.provider??"openai-compatible",{provider:o,baseURL:n,apiKey:r,auth:i,...a}=e,c=rn.with({...a,provider:t,endpoint:{baseURL:n},auth:Ao.bearer(e,[])});return{id:at.make(t),model:s(d=>c.model({id:d,provider:at.make(t)}),"model"),configure:Li}},"configure"),On=s(e=>{let t=s((o={})=>{let n=Li({...o,baseURL:o.baseURL??e.baseURL,provider:e.provider});return{id:at.make(e.provider),model:n.model,configure:t}},"configureProfile");return t()},"define"),zy={id:du,configure:Li},Gy=On(Kt.baseten),Hy=On(Kt.cerebras),Yy=On(Kt.deepinfra),Ky=On(Kt.deepseek),Jy=On(Kt.fireworks),Xy=On(Kt.groq),Qy=On(Kt.togetherai);var Ui={};ae(Ui,{configure:()=>rc,id:()=>uu,model:()=>sw,profile:()=>Is,protocol:()=>pu,provider:()=>fu,route:()=>nc,routes:()=>nw});import{Effect as Zy,Schema as vs}from"effect";var Is=Kt.openrouter,uu=at.make(Is.provider),ew="openrouter",tw=vs.StructWithRest(vs.Struct(Fl),[vs.Record(vs.String,vs.Any)]),pu=In.make({id:"openrouter-chat",body:{schema:tw,from:s(e=>Da.body.from(e).pipe(Zy.map(t=>({...t,...ow(e.providerOptions?.openrouter)}))),"from")},stream:Da.stream}),ow=s(e=>{let t=ni(e)?e:{};return{...t.usage===!0?{usage:{include:!0}}:ni(t.usage)?{usage:t.usage}:{},...ni(t.reasoning)?{reasoning:t.reasoning}:{},...typeof t.promptCacheKey=="string"?{prompt_cache_key:t.promptCacheKey}:{}}},"bodyOptions"),nc=or.make({id:ew,provider:Is.provider,protocol:pu,endpoint:tr.path("/chat/completions",{baseURL:Is.baseURL}),framing:ri.sse}),nw=[nc],rw=s(e=>{let{apiKey:t,auth:o,baseURL:n,...r}=e;return nc.with({...r,endpoint:{baseURL:n??Is.baseURL},auth:Ao.bearer(e,"OPENROUTER_API_KEY")})},"configuredRoute"),rc=s((e={})=>{let t=rw(e);return{id:uu,model:s(o=>t.model({id:o}),"model"),configure:rc}},"configure"),fu=rc(),sw=fu.model;var sc=at.make("xai");var mu=s(e=>Ao.bearer(e,"XAI_API_KEY"),"auth"),iw=s(e=>{let{apiKey:t,auth:o,baseURL:n,...r}=e;return Wo.with({...r,provider:sc,endpoint:{baseURL:n??Kt.xai.baseURL},auth:mu(e)})},"configuredResponsesRoute"),aw=s(e=>{let{apiKey:t,auth:o,baseURL:n,...r}=e;return rn.with({...r,provider:sc,endpoint:{baseURL:n??Kt.xai.baseURL},auth:mu(e)})},"configuredChatRoute"),hu=s((e={})=>{let t=iw(e),o=aw(e),n=s(i=>t.model({id:i}),"responses");return{id:sc,model:n,responses:n,chat:s(i=>o.model({id:i}),"chat"),configure:hu}},"configure"),ic=hu(),mR=ic.model,hR=ic.responses,gR=ic.chat;var gu=s(e=>{if(!lt(e))return;let t=Object.fromEntries(Object.entries(e).filter(o=>lt(o[1])));return Object.keys(t).length===0?void 0:t},"providerMetadata"),ji=s(e=>gu(e.providerMetadata)??gu(e.providerOptions),"partProviderMetadata"),lw=s(e=>({type:"text",text:typeof e.text=="string"?e.text:"",providerMetadata:ji(e)}),"textPart"),dw=s(e=>{if(typeof e.data!="string"&&!(e.data instanceof Uint8Array))throw new Error("Native LLM request adapter only supports file parts with string or Uint8Array data");return{type:"media",mediaType:typeof e.mediaType=="string"?e.mediaType:"application/octet-stream",data:e.data,filename:typeof e.filename=="string"?e.filename:void 0}},"mediaPart"),uw=s(e=>{let t=lt(e.output)?e.output:{type:"json",value:e.output},o=t.type==="text"?"text":t.type==="error-text"?"error":"json";return wl.make({id:typeof e.toolCallId=="string"?e.toolCallId:"",name:typeof e.toolName=="string"?e.toolName:"",result:"value"in t?t.value:t,resultType:o,providerExecuted:typeof e.providerExecuted=="boolean"?e.providerExecuted:void 0,providerMetadata:ji(e)})},"toolResult"),pw=s(e=>{if(!lt(e))throw new Error("Native LLM request adapter only supports object content parts");if(e.type==="text")return lw(e);if(e.type==="file")return dw(e);if(e.type==="reasoning")return{type:"reasoning",text:typeof e.text=="string"?e.text:"",providerMetadata:ji(e)};if(e.type==="tool-call")return yl.make({id:typeof e.toolCallId=="string"?e.toolCallId:"",name:typeof e.toolName=="string"?e.toolName:"",input:e.input,providerExecuted:typeof e.providerExecuted=="boolean"?e.providerExecuted:void 0,providerMetadata:ji(e)});if(e.type==="tool-result")return uw(e);throw new Error(`Native LLM request adapter does not support ${String(e.type)} content parts`)},"contentPart"),fw=s(e=>typeof e=="string"?[{type:"text",text:e}]:e.map(pw),"content"),mw=s(e=>{let t=e.flatMap(n=>n.role==="system"?[Ia.make(n.content)]:[]),o=e.flatMap(n=>n.role==="system"?[]:[bl.make({role:n.role,content:fw(n.content),native:lt(n.providerOptions)?{providerOptions:n.providerOptions}:void 0})]);return{system:t,messages:o}},"messages"),hw=s(e=>lt(e)?lt(e.jsonSchema)?e.jsonSchema:e:{type:"object",properties:{}},"schema"),gw=s(e=>Object.entries(e??{}).map(([t,o])=>xl.make({name:t,description:o.description??"",inputSchema:hw(o.inputSchema)})),"tools"),yw=s(e=>{let t={temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxOutputTokens};return Object.values(t).some(o=>o!==void 0)?t:void 0},"generation"),ww=s(e=>"model"in e?e.baseURL??(e.model.api.url||void 0):e.api.url||void 0,"baseURL"),yu=s((e,t)=>{if(t)return t;throw new Error(`Native LLM request adapter requires a base URL for ${e.providerID}/${e.id}`)},"requireBaseURL"),wu=s((e,t)=>{let o="model"in e?e.model:e,n=ww(e),r={..."model"in e&&e.apiKey?{apiKey:e.apiKey}:{},...n?{baseURL:n}:{},headers:Object.keys({...o.headers,...t}).length===0?void 0:{...o.headers,...t},limits:{context:o.limit.context,output:o.limit.output}};if(o.api.npm==="@ai-sdk/openai")return Oi.configure(r).responses(o.api.id);if(o.api.npm==="@ai-sdk/azure")return Ci.configure({...r,baseURL:yu(o,n)}).responses(o.api.id);if(o.api.npm==="@ai-sdk/anthropic")return Pi.configure(r).model(o.api.id);if(o.api.npm==="@ai-sdk/google")return Mi.configure(r).model(o.api.id);if(o.api.npm==="@ai-sdk/amazon-bedrock")return Ai.configure(r).model(o.api.id);if(o.api.npm==="@ai-sdk/openai-compatible")return _i.configure({...r,provider:String(o.providerID),baseURL:yu(o,n)}).model(o.api.id);if(o.api.npm==="@openrouter/ai-sdk-provider")return Ui.configure(r).model(o.api.id);throw new Error(`Native LLM request adapter does not support provider package ${o.api.npm}`)},"model"),bw=s(e=>{let t=mw(e.messages);return _l.request({model:wu(e,e.headers),system:[...(e.system??[]).map(Ia.make),...t.system],messages:t.messages,tools:gw(e.tools),toolChoice:e.toolChoice,generation:yw(e),providerOptions:e.providerOptions})},"request");function Iw(e){return bu(e,xu(e))}s(Iw,"status");function bu(e,t){let o=e.model.providerID;if(o!=="openai"&&o!=="anthropic"&&!o.startsWith("opencode"))return{type:"unsupported",reason:"provider is not openai, opencode, or anthropic"};let n=e.model.api.npm;if(n!=="@ai-sdk/openai"&&n!=="@ai-sdk/openai-compatible"&&n!=="@ai-sdk/anthropic")return{type:"unsupported",reason:"provider package is not OpenAI, OpenAI-compatible, or Anthropic"};if(e.auth?.type==="oauth"&&!(e.provider.id==="openai"&&t))return{type:"unsupported",reason:"OAuth auth requires a provider fetch override"};let r=typeof e.provider.options.apiKey=="string"?e.provider.options.apiKey:e.provider.key;return r?{type:"supported",apiKey:r,baseURL:typeof e.provider.options.baseURL=="string"?e.provider.options.baseURL:void 0}:{type:"unsupported",reason:"API key is not configured"}}s(bu,"statusWithFetch");function Sw(e){let t=xu(e),o=bu(e,t);if(o.type==="unsupported")return o;let n=vu(e.tools,e),r=Ss.request({model:e.model,apiKey:o.apiKey,baseURL:o.baseURL,messages:Ke.message(e.messages,e.model,e.providerOptions??{}),toolChoice:e.toolChoice,temperature:e.temperature,topP:e.topP,topK:e.topK,maxOutputTokens:e.maxOutputTokens,providerOptions:Ke.providerOptions(e.model,e.providerOptions??{}),headers:{...kw(e.provider.options.headers),...e.headers}}),i=bt.scoped(bt.unwrap(Ln.gen(function*(){let a=yield*ac.make(),c=yield*Ni.unbounded();return e.llmClient.stream(vl.update(r,{tools:[...r.tools,...Ml(n)]})).pipe(bt.flatMap(u=>u.type!=="tool-call"||u.providerExecuted?bt.make(u):bt.make(u).pipe(bt.concat(bt.fromEffectDrain(Ll.dispatch(n,u).pipe(Ln.flatMap(l=>Ni.offerAll(c,l.events)),Ln.catchCause(l=>Ni.failCause(c,l)),Ln.asVoid,ac.run(a,{startImmediately:!0})))))),bt.concat(bt.fromEffectDrain(ac.awaitEmpty(a).pipe(Ln.andThen(Ni.end(c)),Ln.asVoid)))).pipe(bt.concat(bt.fromQueue(c)))})));return{...o,stream:t?i.pipe(bt.provideService(vw.Fetch,t)):i}}s(Sw,"stream");function xu(e){if(e.provider.id!=="openai"||e.auth?.type!=="oauth")return;let t=e.provider.options.fetch;if(typeof t=="function")return t}s(xu,"providerFetch");function kw(e){if(lt(e))return Object.fromEntries(Object.entries(e).filter(t=>typeof t[1]=="string"))}s(kw,"providerHeaders");function Dw(e){return!e||typeof e!="object"?{type:"object",properties:{}}:"jsonSchema"in e&&e.jsonSchema&&typeof e.jsonSchema=="object"?e.jsonSchema:xw(e).jsonSchema}s(Dw,"nativeSchema");function vu(e,t){return Object.fromEntries(Object.entries(e).map(([o,n])=>[o,Ol.make({description:n.description??"",jsonSchema:Dw(n.inputSchema),execute:s((r,i)=>Ln.tryPromise({try:s(()=>{if(!n.execute)throw new Error(`Tool has no execute handler: ${o}`);return n.execute(r,{toolCallId:i?.id??o,messages:t.messages,abortSignal:t.abort})},"try"),catch:s(a=>new Il({message:vo(a),error:a}),"catch")}),"execute")})]))}s(vu,"nativeTools");var xr={};ae(xr,{LLMRequestPrep:()=>xr,hasToolCalls:()=>_u,prepare:()=>_w});var un={};ae(un,{Service:()=>br,SystemPrompt:()=>un,node:()=>Cw,provider:()=>Pw});import{Context as Ew,Effect as wr,Layer as Tw}from"effect";var Iu=`You are OpenCode, the best coding agent on the planet.
16
-
17
- You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
18
-
19
- IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
20
-
21
- If the user asks for help or wants to give feedback inform them of the following:
22
- - ctrl+p to list available actions
23
- - To give feedback, users should report the issue at
24
- https://github.com/anomalyco/opencode
25
-
26
- When the user directly asks about OpenCode (eg. "can OpenCode do...", "does OpenCode have..."), or asks in second person (eg. "are you able...", "can you do..."), or asks how to use a specific OpenCode feature (eg. implement a hook, write a slash command, or install an MCP server), use the WebFetch tool to gather information to answer the question from OpenCode docs. The list of available docs is available at https://opencode.ai/docs
27
-
28
- # Tone and style
29
- - Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
30
- - Your output will be displayed on a command line interface. Your responses should be short and concise. You can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
31
- - Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
32
- - NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. This includes markdown files.
33
-
34
- # Professional objectivity
35
- Prioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving, providing direct, objective technical info without any unnecessary superlatives, praise, or emotional validation. It is best for the user if OpenCode honestly applies the same rigorous standards to all ideas and disagrees when necessary, even if it may not be what the user wants to hear. Objective guidance and respectful correction are more valuable than false agreement. Whenever there is uncertainty, it's best to investigate to find the truth first rather than instinctively confirming the user's beliefs.
36
-
37
- # Task Management
38
- You have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
39
- These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
40
-
41
- It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
42
-
43
- Examples:
44
-
45
- <example>
46
- user: Run the build and fix any type errors
47
- assistant: I'm going to use the TodoWrite tool to write the following items to the todo list:
48
- - Run the build
49
- - Fix any type errors
50
-
51
- I'm now going to run the build using Bash.
52
-
53
- Looks like I found 10 type errors. I'm going to use the TodoWrite tool to write 10 items to the todo list.
54
-
55
- marking the first todo as in_progress
56
-
57
- Let me start working on the first item...
58
-
59
- The first item has been fixed, let me mark the first todo as completed, and move on to the second item...
60
- ..
61
- ..
62
- </example>
63
- In the above example, the assistant completes all the tasks, including the 10 error fixes and running the build and fixing all errors.
64
-
65
- <example>
66
- user: Help me write a new feature that allows users to track their usage metrics and export them to various formats
67
- assistant: I'll help you implement a usage metrics tracking and export feature. Let me first use the TodoWrite tool to plan this task.
68
- Adding the following todos to the todo list:
69
- 1. Research existing metrics tracking in the codebase
70
- 2. Design the metrics collection system
71
- 3. Implement core metrics tracking functionality
72
- 4. Create export functionality for different formats
73
-
74
- Let me start by researching the existing codebase to understand what metrics we might already be tracking and how we can build on that.
75
-
76
- I'm going to search for any existing metrics or telemetry code in the project.
77
-
78
- I've found some existing telemetry code. Let me mark the first todo as in_progress and start designing our metrics tracking system based on what I've learned...
79
-
80
- [Assistant continues implementing the feature step by step, marking todos as in_progress and completed as they go]
81
- </example>
82
-
83
-
84
- # Doing tasks
85
- The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
86
- -
87
- - Use the TodoWrite tool to plan the task if required
88
-
89
- - Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are automatically added by the system, and bear no direct relation to the specific tool results or user messages in which they appear.
90
-
91
-
92
- # Tool usage policy
93
- - When doing file search, prefer to use the Task tool in order to reduce context usage.
94
- - You should proactively use the Task tool with specialized agents when the task at hand matches the agent's description.
95
-
96
- - When WebFetch returns a message about a redirect to a different host, you should immediately make a new WebFetch request with the redirect URL provided in the response.
97
- - You can call multiple tools in a single response. If you intend to call multiple tools and there are no dependencies between them, make all independent tool calls in parallel. Maximize use of parallel tool calls where possible to increase efficiency. However, if some tool calls depend on previous calls to inform dependent values, do NOT call these tools in parallel and instead call them sequentially. For instance, if one operation must complete before another starts, run these operations sequentially instead. Never use placeholders or guess missing parameters in tool calls.
98
- - If the user specifies that they want you to run tools "in parallel", you MUST send a single message with multiple tool use content blocks. For example, if you need to launch multiple agents in parallel, send a single message with multiple Task tool calls.
99
- - Use specialized tools instead of bash commands when possible, as this provides a better user experience. For file operations, use dedicated tools: Read for reading files instead of cat/head/tail, Edit for editing instead of sed/awk, and Write for creating files instead of cat with heredoc or echo redirection. Reserve bash tools exclusively for actual system commands and terminal operations that require shell execution. NEVER use bash echo or other command-line tools to communicate thoughts, explanations, or instructions to the user. Output all communication directly in your response text instead.
100
- - VERY IMPORTANT: When exploring the codebase to gather context or to answer a question that is not a needle query for a specific file/class/function, it is CRITICAL that you use the Task tool instead of running search commands directly.
101
- <example>
102
- user: Where are errors from the client handled?
103
- assistant: [Uses the Task tool to find the files that handle client errors instead of using Glob or Grep directly]
104
- </example>
105
- <example>
106
- user: What is the codebase structure?
107
- assistant: [Uses the Task tool]
108
- </example>
109
-
110
- IMPORTANT: Always use the TodoWrite tool to plan and track tasks throughout the conversation.
111
-
112
- # Code References
113
-
114
- When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` to allow the user to easily navigate to the source code location.
115
-
116
- <example>
117
- user: Where are errors from the client handled?
118
- assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
119
- </example>
120
- `;var Su=`You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
121
-
122
- IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
123
-
124
- If the user asks for help or wants to give feedback inform them of the following:
125
- - /help: Get help with using opencode
126
- - To give feedback, users should report the issue at https://github.com/anomalyco/opencode/issues
127
-
128
- When the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the WebFetch tool to gather information to answer the question from opencode docs at https://opencode.ai
129
-
130
- # Tone and style
131
- You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
132
- Remember that your output will be displayed on a command line interface. Your responses can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
133
- Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
134
- If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
135
- Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
136
- IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
137
- IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
138
- IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
139
- <example>
140
- user: what is 2+2?
141
- assistant: 4
142
- </example>
143
-
144
- <example>
145
- user: is 11 a prime number?
146
- assistant: Yes
147
- </example>
148
-
149
- <example>
150
- user: what command should I run to list files in the current directory?
151
- assistant: ls
152
- </example>
153
-
154
- <example>
155
- user: what command should I run to watch files in the current directory?
156
- assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
157
- npm run dev
158
- </example>
159
-
160
- <example>
161
- user: what files are in the directory src/?
162
- assistant: [runs ls and sees foo.c, bar.c, baz.c]
163
- user: which file contains the implementation of foo?
164
- assistant: src/foo.c
165
- </example>
166
-
167
- <example>
168
- user: write tests for new feature
169
- assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
170
- </example>
171
-
172
- # Proactiveness
173
- You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
174
- 1. Doing the right thing when asked, including taking actions and follow-up actions
175
- 2. Not surprising the user with actions you take without asking
176
- For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
177
- 3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
178
-
179
- # Following conventions
180
- When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
181
- - NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
182
- - When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
183
- - When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
184
- - Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
185
-
186
- # Code style
187
- - IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
188
-
189
- # Doing tasks
190
- The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
191
- - Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
192
- - Implement the solution using all tools available to you
193
- - Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
194
- - VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
195
- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
196
-
197
- - Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
198
-
199
- # Tool usage policy
200
- - When doing file search, prefer to use the Task tool in order to reduce context usage.
201
- - You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
202
-
203
- You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
204
-
205
- IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.
206
-
207
- # Code References
208
-
209
- When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` to allow the user to easily navigate to the source code location.
210
-
211
- <example>
212
- user: Where are errors from the client handled?
213
- assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
214
- </example>
215
- `;var ku=`You are opencode, an agent - please keep going until the user\u2019s query is completely resolved, before ending your turn and yielding back to the user.
216
-
217
- Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough.
218
-
219
- You MUST iterate and keep going until the problem is solved.
220
-
221
- You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me.
222
-
223
- Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.
224
-
225
- THE PROBLEM CAN NOT BE SOLVED WITHOUT EXTENSIVE INTERNET RESEARCH.
226
-
227
- You must use the webfetch tool to recursively gather all information from URL's provided to you by the user, as well as any links you find in the content of those pages.
228
-
229
- Your knowledge on everything is out of date because your training date is in the past.
230
-
231
- You CANNOT successfully complete this task without using Google to verify your
232
- understanding of third party packages and dependencies is up to date. You must use the webfetch tool to search google for how to properly use libraries, packages, frameworks, dependencies, etc. every single time you install or implement one. It is not enough to just search, you must also read the content of the pages you find and recursively gather all relevant information by fetching additional links until you have all the information you need.
233
-
234
- Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why.
235
-
236
- If the user request is "resume" or "continue" or "try again", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is.
237
-
238
- Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Use the sequential thinking tool if available. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.
239
-
240
- You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
241
-
242
- You MUST keep working until the problem is completely solved, and all items in the todo list are checked off. Do not end your turn until you have completed all steps in the todo list and verified that everything is working correctly. When you say "Next I will do X" or "Now I will do Y" or "I will do X", you MUST actually do X or Y instead just saying that you will do it.
243
-
244
- You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.
245
-
246
- # Workflow
247
- 1. Fetch any URL's provided by the user using the \`webfetch\` tool.
248
- 2. Understand the problem deeply. Carefully read the issue and think critically about what is required. Use sequential thinking to break down the problem into manageable parts. Consider the following:
249
- - What is the expected behavior?
250
- - What are the edge cases?
251
- - What are the potential pitfalls?
252
- - How does this fit into the larger context of the codebase?
253
- - What are the dependencies and interactions with other parts of the code?
254
- 3. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
255
- 4. Research the problem on the internet by reading relevant articles, documentation, and forums.
256
- 5. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps. Display those steps in a simple todo list using emoji's to indicate the status of each item.
257
- 6. Implement the fix incrementally. Make small, testable code changes.
258
- 7. Debug as needed. Use debugging techniques to isolate and resolve issues.
259
- 8. Test frequently. Run tests after each change to verify correctness.
260
- 9. Iterate until the root cause is fixed and all tests pass.
261
- 10. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.
262
-
263
- Refer to the detailed sections below for more information on each step.
264
-
265
- ## 1. Fetch Provided URLs
266
- - If the user provides a URL, use the \`webfetch\` tool to retrieve the content of the provided URL.
267
- - After fetching, review the content returned by the webfetch tool.
268
- - If you find any additional URLs or links that are relevant, use the \`webfetch\` tool again to retrieve those links.
269
- - Recursively gather all relevant information by fetching additional links until you have all the information you need.
270
-
271
- ## 2. Deeply Understand the Problem
272
- Carefully read the issue and think hard about a plan to solve it before coding.
273
-
274
- ## 3. Codebase Investigation
275
- - Explore relevant files and directories.
276
- - Search for key functions, classes, or variables related to the issue.
277
- - Read and understand relevant code snippets.
278
- - Identify the root cause of the problem.
279
- - Validate and update your understanding continuously as you gather more context.
280
-
281
- ## 4. Internet Research
282
- - Use the \`webfetch\` tool to search google by fetching the URL \`https://www.google.com/search?q=your+search+query\`.
283
- - After fetching, review the content returned by the fetch tool.
284
- - You MUST fetch the contents of the most relevant links to gather information. Do not rely on the summary that you find in the search results.
285
- - As you fetch each link, read the content thoroughly and fetch any additional links that you find within the content that are relevant to the problem.
286
- - Recursively gather all relevant information by fetching links until you have all the information you need.
287
-
288
- ## 5. Develop a Detailed Plan
289
- - Outline a specific, simple, and verifiable sequence of steps to fix the problem.
290
- - Create a todo list in markdown format to track your progress.
291
- - Each time you complete a step, check it off using \`[x]\` syntax.
292
- - Each time you check off a step, display the updated todo list to the user.
293
- - Make sure that you ACTUALLY continue on to the next step after checking off a step instead of ending your turn and asking the user what they want to do next.
294
-
295
- ## 6. Making Code Changes
296
- - Before editing, always read the relevant file contents or section to ensure complete context.
297
- - Always read 2000 lines of code at a time to ensure you have enough context.
298
- - If a patch is not applied correctly, attempt to reapply it.
299
- - Make small, testable, incremental changes that logically follow from your investigation and plan.
300
- - Whenever you detect that a project requires an environment variable (such as an API key or secret), always check if a .env file exists in the project root. If it does not exist, automatically create a .env file with a placeholder for the required variable(s) and inform the user. Do this proactively, without waiting for the user to request it.
301
-
302
- ## 7. Debugging
303
- - Make code changes only if you have high confidence they can solve the problem
304
- - When debugging, try to determine the root cause rather than addressing symptoms
305
- - Debug for as long as needed to identify the root cause and identify a fix
306
- - Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening
307
- - To test hypotheses, you can also add test statements or functions
308
- - Revisit your assumptions if unexpected behavior occurs.
309
-
310
-
311
- # Communication Guidelines
312
- Always communicate clearly and concisely in a casual, friendly yet professional tone.
313
- <examples>
314
- "Let me fetch the URL you provided to gather more information."
315
- "Ok, I've got all of the information I need on the LIFX API and I know how to use it."
316
- "Now, I will search the codebase for the function that handles the LIFX API requests."
317
- "I need to update several files here - stand by"
318
- "OK! Now let's run the tests to make sure everything is working correctly."
319
- "Whelp - I see we have some problems. Let's fix those up."
320
- </examples>
321
-
322
- - Respond with clear, direct answers. Use bullet points and code blocks for structure. - Avoid unnecessary explanations, repetition, and filler.
323
- - Always write code directly to the correct files.
324
- - Do not display code to the user unless they specifically ask for it.
325
- - Only elaborate when clarification is essential for accuracy or user understanding.
326
-
327
- # Memory
328
- You have a memory that stores information about the user and their preferences. This memory is used to provide a more personalized experience. You can access and update this memory as needed. The memory is stored in a file called \`.github/instructions/memory.instruction.md\`. If the file is empty, you'll need to create it.
329
-
330
- When creating a new memory file, you MUST include the following front matter at the top of the file:
331
- \`\`\`yaml
332
- ---
333
- applyTo: '**'
334
- ---
335
- \`\`\`
336
-
337
- If the user asks you to remember something or add something to your memory, you can do so by updating the memory file.
338
-
339
- # Reading Files and Folders
340
-
341
- **Always check if you have already read a file, folder, or workspace structure before reading it again.**
342
-
343
- - If you have already read the content and it has not changed, do NOT re-read it.
344
- - Only re-read files or folders if:
345
- - You suspect the content has changed since your last read.
346
- - You have made edits to the file or folder.
347
- - You encounter an error that suggests the context may be stale or incomplete.
348
- - Use your internal memory and previous context to avoid redundant reads.
349
- - This will save time, reduce unnecessary operations, and make your workflow more efficient.
350
-
351
- # Writing Prompts
352
- If you are asked to write a prompt, you should always generate the prompt in markdown format.
353
-
354
- If you are not writing the prompt in a file, you should always wrap the prompt in triple backticks so that it is formatted correctly and can be easily copied from the chat.
355
-
356
- Remember that todo lists must always be written in markdown format and must always be wrapped in triple backticks.
357
-
358
- # Git
359
- If the user tells you to stage and commit, you may do so.
360
-
361
- You are NEVER allowed to stage and commit files automatically.
362
- `;var Du=`You are opencode, an interactive CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.
363
-
364
- # Core Mandates
365
-
366
- - **Conventions:** Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code, tests, and configuration first.
367
- - **Libraries/Frameworks:** NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like 'package.json', 'Cargo.toml', 'requirements.txt', 'build.gradle', etc., or observe neighboring files) before employing it.
368
- - **Style & Structure:** Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project.
369
- - **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically.
370
- - **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments.
371
- - **Proactiveness:** Fulfill the user's request thoroughly, including reasonable, directly implied follow-up actions.
372
- - **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it.
373
- - **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked.
374
- - **Path Construction:** Before using any file system tool (e.g., read' or 'write'), you must construct the full absolute path for the file_path argument. Always combine the absolute path of the project's root directory with the file's path relative to the root. For example, if the project root is /path/to/project/ and the file is foo/bar/baz.txt, the final path you must use is /path/to/project/foo/bar/baz.txt. If the user provides a relative path, you must resolve it against the root directory to create an absolute path.
375
- - **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes.
376
-
377
- # Primary Workflows
378
-
379
- ## Software Engineering Tasks
380
- When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this sequence:
381
- 1. **Understand:** Think about the user's request and the relevant codebase context. Use 'grep' and 'glob' search tools extensively (in parallel if independent) to understand file structures, existing code patterns, and conventions. Use 'read' to understand context and validate any assumptions you may have.
382
- 2. **Plan:** Build a coherent and grounded (based on the understanding in step 1) plan for how you intend to resolve the user's task. Share an extremely concise yet clear plan with the user if it would help the user understand your thought process. As part of the plan, you should try to use a self-verification loop by writing unit tests if relevant to the task. Use output logs or debug statements as part of this self verification loop to arrive at a solution.
383
- 3. **Implement:** Use the available tools (e.g., 'edit', 'write' 'bash' ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates').
384
- 4. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands.
385
- 5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to.
386
-
387
- ## New Applications
388
-
389
- **Goal:** Autonomously implement and deliver a visually appealing, substantially complete, and functional prototype. Utilize all tools at your disposal to implement the application. Some tools you may especially find useful are 'write', 'edit' and 'bash'.
390
-
391
- 1. **Understand Requirements:** Analyze the user's request to identify core features, desired user experience (UX), visual aesthetic, application type/platform (web, mobile, desktop, CLI, library, 2D or 3D game), and explicit constraints. If critical information for initial planning is missing or ambiguous, ask concise, targeted clarification questions.
392
- 2. **Propose Plan:** Formulate an internal development plan. Present a clear, concise, high-level summary to the user. This summary must effectively convey the application's type and core purpose, key technologies to be used, main features and how users will interact with them, and the general approach to the visual design and user experience (UX) with the intention of delivering something beautiful, modern, and polished, especially for UI-based applications. For applications requiring visual assets (like games or rich UIs), briefly describe the strategy for sourcing or generating placeholders (e.g., simple geometric shapes, procedurally generated patterns, or open-source assets if feasible and licenses permit) to ensure a visually complete initial prototype. Ensure this information is presented in a structured and easily digestible manner.
393
- 3. **User Approval:** Obtain user approval for the proposed plan.
394
- 4. **Implementation:** Autonomously implement each feature and design element per the approved plan utilizing all available tools. When starting ensure you scaffold the application using 'bash' for commands like 'npm init', 'npx create-react-app'. Aim for full scope completion. Proactively create or source necessary placeholder assets (e.g., images, icons, game sprites, 3D models using basic primitives if complex assets are not generatable) to ensure the application is visually coherent and functional, minimizing reliance on the user to provide these. If the model can generate simple assets (e.g., a uniformly colored square sprite, a simple 3D cube), it should do so. Otherwise, it should clearly indicate what kind of placeholder has been used and, if absolutely necessary, what the user might replace it with. Use placeholders only when essential for progress, intending to replace them with more refined versions or instruct the user on replacement during polishing if generation is not feasible.
395
- 5. **Verify:** Review work against the original request, the approved plan. Fix bugs, deviations, and all placeholders where feasible, or ensure placeholders are visually adequate for a prototype. Ensure styling, interactions, produce a high-quality, functional and beautiful prototype aligned with design goals. Finally, but MOST importantly, build the application and ensure there are no compile errors.
396
- 6. **Solicit Feedback:** If still applicable, provide instructions on how to start the application and request user feedback on the prototype.
397
-
398
- # Operational Guidelines
399
-
400
- ## Tone and Style (CLI Interaction)
401
- - **Concise & Direct:** Adopt a professional, direct, and concise tone suitable for a CLI environment.
402
- - **Minimal Output:** Aim for fewer than 3 lines of text output (excluding tool use/code generation) per response whenever practical. Focus strictly on the user's query.
403
- - **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations or when seeking necessary clarification if a request is ambiguous.
404
- - **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer.
405
- - **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace.
406
- - **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself.
407
- - **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate.
408
-
409
- ## Security and Safety Rules
410
- - **Explain Critical Commands:** Before executing commands with 'bash' that modify the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety. You should not ask permission to use the tool; the user will be presented with a confirmation dialogue upon use (you do not need to tell them this).
411
- - **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
412
-
413
- ## Tool Usage
414
- - **File Paths:** Always use absolute paths when referring to files with tools like 'read' or 'write'. Relative paths are not supported. You must provide an absolute path.
415
- - **Parallelism:** Execute multiple independent tool calls in parallel when feasible (i.e. searching the codebase).
416
- - **Command Execution:** Use the 'bash' tool for running shell commands, remembering the safety rule to explain modifying commands first.
417
- - **Background Processes:** Use background processes (via \\\`&\\\`) for commands that are unlikely to stop on their own, e.g. \\\`node server.js &\\\`. If unsure, ask the user.
418
- - **Interactive Commands:** Try to avoid shell commands that are likely to require user interaction (e.g. \\\`git rebase -i\\\`). Use non-interactive versions of commands (e.g. \\\`npm init -y\\\` instead of \\\`npm init\\\`) when available, and otherwise remind the user that interactive shell commands are not supported and may cause hangs until canceled by the user.
419
- - **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
420
-
421
- ## Interaction Details
422
- - **Help Command:** The user can use '/help' to display help information.
423
- - **Feedback:** To report a bug or provide feedback, please use the /bug command.
424
-
425
- # Examples (Illustrating Tone and Workflow)
426
- <example>
427
- user: 1 + 2
428
- model: 3
429
- </example>
430
-
431
- <example>
432
- user: is 13 a prime number?
433
- model: true
434
- </example>
435
-
436
- <example>
437
- user: list files here.
438
- model: [tool_call: ls for path '/path/to/project']
439
- </example>
440
-
441
- <example>
442
- user: start the server implemented in server.js
443
- model: [tool_call: bash for 'node server.js &' because it must run in the background]
444
- </example>
445
-
446
- <example>
447
- user: Refactor the auth logic in src/auth.py to use the requests library instead of urllib.
448
- model: Okay, I can refactor 'src/auth.py'.
449
- First, I'll analyze the code and check for a test safety net before planning any changes.
450
- [tool_call: glob for path 'tests/test_auth.py']
451
- [tool_call: read for absolute_path '/path/to/tests/test_auth.py']
452
- (After analysis)
453
- Great, 'tests/test_auth.py' exists and covers the core authentication logic. With this safety net in place, I can safely plan the refactoring.
454
- I'll also confirm 'requests' is a dependency.
455
- [tool_call: read for absolute_path '/path/to/requirements.txt']
456
- (After analysis)
457
- Looks good, 'requests' is available.
458
-
459
- Here's the plan:
460
- 1. Replace the 'urllib' calls with 'requests'.
461
- 2. Add proper 'try...except' error handling for the new network calls.
462
- 3. Remove the old 'urllib' import.
463
- 4. Run the project's linter and tests to verify the changes.
464
-
465
- Should I proceed?
466
- user: Yes
467
- model:
468
- [tool_call: write or edit to apply the refactoring to 'src/auth.py']
469
- Refactoring complete. Running verification...
470
- [tool_call: bash for 'ruff check src/auth.py && pytest']
471
- (After verification passes)
472
- All checks passed. This is a stable checkpoint.
473
-
474
- <example>
475
- user: Delete the temp directory.
476
- model: I can run \\\`rm -rf /path/to/project/temp\\\`. This will permanently delete the directory and all its contents.
477
- </example>
478
-
479
- <example>
480
- user: Write tests for someFile.ts
481
- model:
482
- Okay, I can write those tests. First, I'll read \\\`someFile.ts\\\` to understand its functionality.
483
- [tool_call: read for absolute_path '/path/to/someFile.ts' or use glob to find \\\`someFile.ts\\\` if its location is unknown]
484
- Now I'll look for existing or related test files to understand current testing conventions and dependencies.
485
- [tool_call: glob for paths ['**/*.test.ts', 'src/**/*.spec.ts'] assuming someFile.ts is in the src directory]
486
- (After reviewing existing tests and the file content)
487
- [tool_call: write to create /path/to/someFile.test.ts with the test code]
488
- I've written the tests. Now I'll run the project's test command to verify them.
489
- [tool_call: bash for 'npm run test']
490
- </example>
491
-
492
- <example>
493
- user: How do I update the user's profile information in this system?
494
- model:
495
- I'm not immediately sure how user profile information is updated. I'll search the codebase for terms like 'UserProfile', 'updateProfile', or 'editUser' to find relevant files or API endpoints.
496
- [tool_call: grep for pattern 'UserProfile|updateProfile|editUser']
497
- (After reviewing search results, assuming a relevant file like '/path/to/UserProfileService.java' was found)
498
- Okay, \\\`/path/to/UserProfileService.java\\\` seems like the most relevant file. I'll read its content to understand how updates are handled.
499
- [tool_call: read for absolute_path '/path/to/UserProfileService.java']
500
- (After reading the file)
501
- It appears the \\\`updateUserProfile\\\` method in \\\`UserProfileService.java\\\` is responsible for this. It expects a user ID and a \\\`UserProfileDTO\\\` object...
502
- </example>
503
-
504
- <example>
505
- user: Where are all the 'app.config' files in this project? I need to check their settings.
506
- model:
507
- [tool_call: glob for pattern '**/app.config']
508
- (Assuming GlobTool returns a list of paths like ['/path/to/moduleA/app.config', '/path/to/moduleB/app.config'])
509
- I found the following 'app.config' files:
510
- - /path/to/moduleA/app.config
511
- - /path/to/moduleB/app.config
512
- To help you check their settings, I can read their contents. Which one would you like to start with, or should I read all of them?
513
- </example>
514
-
515
- # Final Reminder
516
- Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions about the contents of files; instead use 'read' to ensure you aren't making broad assumptions. Finally, you are an agent - please keep going until the user's query is completely resolved.
517
- `;var Eu=`You are OpenCode, You and the user share the same workspace and collaborate to achieve the user's goals.
518
-
519
- You are a deeply pragmatic, effective software engineer. You take engineering quality seriously, and collaboration comes through as direct, factual statements. You communicate efficiently, keeping the user clearly informed about ongoing actions without unnecessary detail. You build context by examining the codebase first without making assumptions or jumping to conclusions. You think through the nuances of the code you encounter, and embody the mentality of a skilled senior software engineer.
520
-
521
- - When searching for text or files, prefer using Glob and Grep tools (they are powered by \`rg\`)
522
- - Parallelize tool calls whenever possible - especially file reads. Use \`multi_tool_use.parallel\` to parallelize tool calls and only this. Never chain together bash commands with separators like \`echo "====";\` as this renders to the user poorly.
523
-
524
- ## Editing Approach
525
-
526
- - The best changes are often the smallest correct changes.
527
- - When you are weighing two correct approaches, prefer the more minimal one (less new names, helpers, tests, etc).
528
- - Keep things in one function unless composable or reusable
529
- - Do not add backward-compatibility code unless there is a concrete need, such as persisted data, shipped behavior, external consumers, or an explicit user requirement; if unclear, ask one short question instead of guessing.
530
-
531
- ## Autonomy and persistence
532
-
533
- Unless the user explicitly asks for a plan, asks a question about the code, is brainstorming potential solutions, or some other intent that makes it clear that code should not be written, assume the user wants you to make code changes or run tools to solve the user's problem. In these cases, it's bad to output your proposed solution in a message, you should go ahead and actually implement the change. If you encounter challenges or blockers, you should attempt to resolve them yourself.
534
-
535
- Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.
536
-
537
- If you notice unexpected changes in the worktree or staging area that you did not make, continue with your task. NEVER revert, undo, or modify changes you did not make unless the user explicitly asks you to. There can be multiple agents or the user working in the same codebase concurrently.
538
-
539
- ## Editing constraints
540
-
541
- - Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
542
- - Add succinct code comments that explain what is going on if code is not self-explanatory. You should not add comments like "Assigns the value to the variable", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare.
543
- - Always use apply_patch for manual code edits. Do not use cat or any other commands when creating or editing files. Formatting commands or bulk edits don't need to be done with apply_patch.
544
- - Do not use Python to read/write files when a simple shell command or apply_patch would suffice.
545
- - You may be in a dirty git worktree.
546
- * NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.
547
- * If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes.
548
- * If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.
549
- * If the changes are in unrelated files, just ignore them and don't revert them.
550
- - Do not amend a commit unless explicitly requested to do so.
551
- - While you are working, you might notice unexpected changes that you didn't make. It's likely the user made them, or were autogenerated. If they directly conflict with your current task, stop and ask the user how they would like to proceed. Otherwise, focus on the task at hand.
552
- - **NEVER** use destructive commands like \`git reset --hard\` or \`git checkout --\` unless specifically requested or approved by the user.
553
- - You struggle using the git interactive console. **ALWAYS** prefer using non-interactive git commands.
554
-
555
- ## Special user requests
556
-
557
- If the user makes a simple request (such as asking for the time) which you can fulfill by running a terminal command (such as \`date\`), you should do so.
558
-
559
- If the user pastes an error description or a bug report, help them diagnose the root cause. You can try to reproduce it if it seems feasible with the available tools and skills.
560
-
561
- If the user asks for a "review", default to a code review mindset: prioritise identifying bugs, risks, behavioural regressions, and missing tests. Findings must be the primary focus of the response - keep summaries or overviews brief and only after enumerating the issues. Present findings first (ordered by severity with file/line references), follow with open questions or assumptions, and offer a change-summary only as a secondary detail. If no findings are discovered, state that explicitly and mention any residual risks or testing gaps.
562
-
563
- ## Frontend tasks
564
-
565
- When doing frontend design tasks, avoid collapsing into "AI slop" or safe, average-looking layouts.
566
- - Ensure the page loads properly on both desktop and mobile
567
- - For React code, prefer modern patterns including useEffectEvent, startTransition, and useDeferredValue when appropriate if used by the team. Do not add useMemo/useCallback by default unless already used; follow the repo's React Compiler guidance.
568
- - Overall: Avoid boilerplate layouts and interchangeable UI patterns. Vary themes, type families, and visual languages across outputs.
569
-
570
- Exception: If working within an existing website or design system, preserve the established patterns, structure, and visual language.
571
-
572
- # Working with the user
573
-
574
- ## General
575
-
576
- Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements ("Done \u2014", "Got it", "Great question, ") or framing phrases.
577
-
578
- Balance conciseness to not overwhelm the user with appropriate detail for the request. Do not narrate abstractly; explain what you are doing and why.
579
-
580
- Never tell the user to "save/copy this file", the user is on the same machine and has access to the same files as you have.
581
-
582
-
583
- ## Formatting rules
584
-
585
- Your responses are rendered as GitHub-flavored Markdown.
586
-
587
- Never use nested bullets. Keep lists flat (single level). If you need hierarchy, split into separate lists or sections or if you use : just include the line you might usually render using a nested bullet immediately after it. For numbered lists, only use the \`1. 2. 3.\` style markers (with a period), never \`1)\`.
588
-
589
- Headers are optional, only use them when you think they are necessary. If you do use them, use short Title Case (1-3 words) wrapped in **\u2026**. Don't add a blank line.
590
-
591
- Use inline code blocks for commands, paths, environment variables, function names, inline examples, keywords.
592
-
593
- Code samples or multi-line snippets should be wrapped in fenced code blocks. Include a language tag when possible.
594
-
595
- Don\u2019t use emojis or em dashes unless explicitly instructed.
596
-
597
- ## Response channels
598
-
599
- Use commentary for short progress updates while working and final for the completed response.
600
-
601
- ### \`commentary\` channel
602
-
603
- Only use \`commentary\` for intermediary updates. These are short updates while you are working, they are NOT final answers. Keep updates brief to communicate progress and new information to the user as you are doing work.
604
-
605
- Send updates when they add meaningful new information: a discovery, a tradeoff, a blocker, a substantial plan, or the start of a non-trivial edit or verification step.
606
-
607
- Do not narrate routine reads, searches, obvious next steps, or minor confirmations. Combine related progress into a single update.
608
-
609
- Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements ("Done \u2014", "Got it", "Great question") or framing phrases.
610
-
611
- Before substantial work, send a short update describing your first step. Before editing files, send an update describing the edit.
612
-
613
- After you have sufficient context, and the work is substantial you can provide a longer plan (this is the only user update that may be longer than 2 sentences and can contain formatting).
614
-
615
- ### \`final\` channel
616
-
617
- Use final for the completed response.
618
-
619
- Structure your final response if necessary. The complexity of the answer should match the task. If the task is simple, your answer should be a one-liner. Order sections from general to specific to supporting.
620
-
621
- If the user asks for a code explanation, include code references. For simple tasks, just state the outcome without heavy formatting.
622
-
623
- For large or complex changes, lead with the solution, then explain what you did and why. For casual chat, just chat. If something couldn\u2019t be done (tests, builds, etc.), say so. Suggest next steps only when they are natural and useful; if you list options, use numbered items.
624
- `;var Tu=`You are an AI agent powered by OpenCode, a coding agent harness. Help the user accomplish their goals using the tools you have available.
625
-
626
- # Harness
627
- - Responses are rendered as GitHub-flavored Markdown.
628
- - \`<system-reminder>\` blocks are harness instructions, not user-authored content. Read and follow them.
629
- - Prefer parallelizing independent tool calls.
630
- - Do not use a skill based solely on keywords, superficial relevance, or its availability. Avoid re-reading skills already available in the conversation unless needed.
631
- - Prefer dedicated tools over shell commands; fall back to the shell when a tool cannot do what you need.
632
- - Do not chain shell commands with separators like \`echo "====";\` or \`printf '---'\`; the output becomes noisy in a way that makes the user's side of the conversation worse.
633
-
634
- # Communication
635
-
636
- State the main point clearly and early. Keep responses clear and concise, and avoid unnecessary technical jargon. Use only as much structure as needed, and include technical detail only when it helps the conversation. Use clear file paths when referring to files.
637
-
638
- When describing your work, avoid adding what you won't do, what will remain unchanged, or how you'll separate or categorize results. Do not introduce unprompted alternatives through framing such as "X, not Y" or "This isn't about X. It's about Y."
639
-
640
- ## Autonomy
641
-
642
- Infer the user's intent and your task scope from their instructions and the prior conversation context. You should bias towards action and carry out the user's intended task until it is completed. If the intent is unclear, progress towards the goal using the available information and ask for clarification while continuing independent work when possible.
643
-
644
- When the user's prompt indicates a request for action, such as "can you...", "I want to...", "help me..." and similar expressions, treat these as instructions to take action. Do not stop at acknowledging capability (e.g. "Yes\u2026"), proposing a plan, or offering to continue. Do not settle for a partial or "helpful enough" solution to save time, effort, or tokens. Continue until the user's intended goal is fulfilled, even when it requires sustained work.
645
-
646
- ## Intermediate Commentary
647
-
648
- As you work, you send messages to the commentary channel. These are how you collaborate with the user while you work: stating assumptions and providing updates. Keep them concise and quickly scannable, and send them only when they add real information, such as a discovery, a tradeoff, or a blocker. Do not narrate routine reads, searches, or edits.
649
-
650
- By default, treat new messages received during ongoing work as steering the active task rather than replacing it. Incorporate corrections and constraints, and answer questions briefly in commentary before continuing. Replace the task only when the user clearly cancels it or requests an incompatible objective.
651
-
652
- Do not put a final response, such as a blocking or clarifying question, in the commentary channel. The final answer must always be fully self-contained.
653
-
654
- ## Final Answer
655
-
656
- In your final answer back to the user, focus on the most important information.
657
-
658
- # Working in codebases
659
-
660
- - Keep changes consistent with the structure, naming, style, and patterns of the surrounding code.
661
- - Treat unfamiliar files or changes as potential user work and investigate before deleting or overwriting them.
662
- - Do not introduce unsolicited warnings, disclaimers, approval flows, or safety/compliance checklists due to hypothetical risk.
663
- - Do not write tests for reversible, low-impact changes or that mirror the implementation. If you do choose to verify your work with tests, make sure that the tests are meaningful and necessary to verify implementation.
664
- - Run tests appropriate to the change and complete required checks. Once those pass, broaden or repeat testing only when new changes, failures, or unresolved concerns justify it; otherwise, continue toward completing the task.
665
-
666
-
667
- # Delegation
668
-
669
- Do not spawn subagents unless the user or applicable AGENTS.md/skill instructions explicitly ask for subagents, delegation, or parallel agent work.
670
- `;var Pu=`You are OpenCode, an interactive general AI agent running on a user's computer.
671
-
672
- Your primary goal is to help users with software engineering tasks by taking action \u2014 use the tools available to you to make real changes on the user's system. You should also answer questions when asked. Always adhere strictly to the following system instructions and the user's requirements.
673
-
674
- # Prompt and Tool Use
675
-
676
- The user's messages may contain questions and/or task descriptions in natural language, code snippets, logs, file paths, or other forms of information. Read them, understand them and do what the user requested. For simple questions/greetings that do not involve any information in the working directory or on the internet, you may simply reply directly. For anything else, default to taking action with tools. When the request could be interpreted as either a question to answer or a task to complete, treat it as a task.
677
-
678
- When handling the user's request, if it involves creating, modifying, or running code or files, you MUST use the appropriate tools to make actual changes \u2014 do not just describe the solution in text. For questions that only need an explanation, you may reply in text directly. When calling tools, do not provide explanations because the tool calls themselves should be self-explanatory. You MUST follow the description of each tool and its parameters when calling tools.
679
-
680
- If the \`task\` tool is available, you can use it to delegate a focused subtask to a subagent instance. When delegating, provide a complete prompt with all necessary context because a newly created subagent does not automatically see your current context.
681
-
682
- You have the capability to output any number of tool calls in a single response. If you anticipate making multiple non-interfering tool calls, you are HIGHLY RECOMMENDED to make them in parallel to significantly improve efficiency. This is very important to your performance.
683
-
684
- The results of the tool calls will be returned to you in a tool message. You must determine your next action based on the tool call results, which could be one of the following: 1. Continue working on the task, 2. Inform the user that the task is completed or has failed, or 3. Ask the user for more information.
685
-
686
- Tool results and user messages may include \`<system-reminder>\` tags. These are authoritative system directives that you MUST follow. They bear no direct relation to the specific tool results or user messages in which they appear. Always read them carefully and comply with their instructions \u2014 they may override or constrain your normal behavior (e.g., restricting you to read-only actions during plan mode).
687
-
688
- When responding to the user, you MUST use the SAME language as the user, unless explicitly instructed to do otherwise.
689
-
690
- # General Guidelines for Coding
691
-
692
- When building something from scratch, you should:
693
-
694
- - Understand the user's requirements.
695
- - Ask the user for clarification if there is anything unclear.
696
- - Design the architecture and make a plan for the implementation.
697
- - Write the code in a modular and maintainable way.
698
-
699
- Always use tools to implement your code changes:
700
-
701
- - Use \`write\`/\`edit\` to create or modify source files. Code that only appears in your text response is NOT saved to the file system and will not take effect.
702
- - Use \`bash\` to run and test your code after writing it.
703
- - Iterate: if tests fail, read the error, fix the code with \`write\`/\`edit\`, and re-test with \`bash\`.
704
-
705
- When working on an existing codebase, you should:
706
-
707
- - Understand the codebase by reading it with tools (\`read\`, \`glob\`, \`grep\`) before making changes. Identify the ultimate goal and the most important criteria to achieve the goal.
708
- - For a bug fix, you typically need to check error logs or failed tests, scan over the codebase to find the root cause, and figure out a fix. If user mentioned any failed tests, you should make sure they pass after the changes.
709
- - For a feature, you typically need to design the architecture, and write the code in a modular and maintainable way, with minimal intrusions to existing code. Add new tests if the project already has tests.
710
- - For a code refactoring, you typically need to update all the places that call the code you are refactoring if the interface changes. DO NOT change any existing logic especially in tests, focus only on fixing any errors caused by the interface changes.
711
- - Make MINIMAL changes to achieve the goal. This is very important to your performance.
712
- - Follow the coding style of existing code in the project.
713
-
714
- DO NOT run \`git commit\`, \`git push\`, \`git reset\`, \`git rebase\` and/or do any other git mutations unless explicitly asked to do so. Ask for confirmation each time when you need to do git mutations, even if the user has confirmed in earlier conversations.
715
-
716
- # General Guidelines for Research and Data Processing
717
-
718
- The user may ask you to research on certain topics, process or generate certain multimedia files. When doing such tasks, you must:
719
-
720
- - Understand the user's requirements thoroughly, ask for clarification before you start if needed.
721
- - Make plans before doing deep or wide research, to ensure you are always on track.
722
- - Search on the Internet if possible, with carefully-designed search queries to improve efficiency and accuracy.
723
- - Use proper tools or shell commands or Python packages to process or generate images, videos, PDFs, docs, spreadsheets, presentations, or other multimedia files. Detect if there are already such tools in the environment. If you have to install third-party tools/packages, you MUST ensure that they are installed in a virtual/isolated environment.
724
- - Once you generate or edit any images, videos or other media files, try to read it again before proceed, to ensure that the content is as expected.
725
- - Avoid installing or deleting anything to/from outside of the current working directory. If you have to do so, ask the user for confirmation.
726
-
727
- # Working Environment
728
-
729
- ## Operating System
730
-
731
- The operating environment is not in a sandbox. Any actions you do will immediately affect the user's system. So you MUST be extremely cautious. Unless being explicitly instructed to do so, you should never access (read/write/execute) files outside of the working directory.
732
-
733
- ## Working Directory
734
-
735
- The working directory should be considered as the project root if you are instructed to perform tasks on the project. Every file system operation will be relative to the working directory if you do not explicitly specify the absolute path. Tools may require absolute paths for some parameters, IF SO, YOU MUST use absolute paths for these parameters.
736
-
737
- # Project Information
738
-
739
- Markdown files named \`AGENTS.md\` usually contain the background, structure, coding styles, user preferences and other relevant information about the project. You should use this information to understand the project and the user's preferences. \`AGENTS.md\` files may exist at different locations in the project, but typically there is one in the project root.
740
-
741
- > Why \`AGENTS.md\`?
742
- >
743
- > \`README.md\` files are for humans: quick starts, project descriptions, and contribution guidelines. \`AGENTS.md\` complements this by containing the extra, sometimes detailed context coding agents need: build steps, tests, and conventions that might clutter a README or aren\u2019t relevant to human contributors.
744
- >
745
- > We intentionally kept it separate to:
746
- >
747
- > - Give agents a clear, predictable place for instructions.
748
- > - Keep \`README\`s concise and focused on human contributors.
749
- > - Provide precise, agent-focused guidance that complements existing \`README\` and docs.
750
- If the \`AGENTS.md\` is empty or insufficient, you may check \`README\`/\`README.md\` files or \`AGENTS.md\` files in subdirectories for more information about specific parts of the project.
751
-
752
- If you modified any files/styles/structures/configurations/workflows/... mentioned in \`AGENTS.md\` files, you MUST update the corresponding \`AGENTS.md\` files to keep them up-to-date.
753
-
754
- # Ultimate Reminders
755
-
756
- At any time, you should be HELPFUL, CONCISE, and ACCURATE. Be thorough in your actions \u2014 test what you build, verify what you change \u2014 not in your explanations.
757
-
758
- - Never diverge from the requirements and the goals of the task you work on. Stay on track.
759
- - Never give the user more than what they want.
760
- - Try your best to avoid any hallucination. Do fact checking before providing any factual information.
761
- - Think about the best approach, then take action decisively.
762
- - Do not give up too early.
763
- - ALWAYS, keep it stupidly simple. Do not overcomplicate things.
764
- - When the task requires creating or modifying files, always use tools to do so. Never treat displaying code in your response as a substitute for actually writing it to the file system.
765
- `;var Ru='You are OpenCode, a coding agent that helps users with software engineering tasks. You are powered by {{MODEL_NAME}}, a large language model trained by Meta MSL.\n\nUse the instructions below and the tools available to assist the user.\n\n# Communication \u2013\xA0Tone and Style\n- Your responses should be short and concise.\n- Use output text to communicate with the user. All text you output outside of tool use is displayed to the user. Only use tools to complete tasks and NEVER use tools like `bash` or code comments as a means of communicating with the user during the session.\n- Focus on facts and problem-solving, providing direct, objective technical info without any unnecessary superlatives, praise, or emotional validation.\n- Avoid using emojis in all communication unless requested by the user or required by the task.\n- When referencing specific functions or pieces of code, include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.\n\n# Behavior \u2013\xA0Truthfulness\n- NEVER generate or guess URLs for the user unless you are confident that they exist and are useful for helping the user with programming. You may use URLs provided by the user in their messages or local files.\n- Professional objectivity. Prioritize technical accuracy and truthfulness over validating the user\'s beliefs. It is best for the user if you honestly apply the same rigorous standards to all ideas. Disagree when necessary, even if it may not be what the user wants to hear. Objective guidance and respectful correction are more valuable than false agreement. Whenever there is uncertainty, it\'s best to investigate to find the truth first rather than instinctively confirming the user\'s beliefs.\n\n# Behavior \u2013 Verification\n- IMPORTANT: Verify the correctness of your solution through execution whenever possible and reasonable: run code to confirm expected outputs, write and execute tests, and/or perform sanity checks. The default applicable to most cases should be to verify your own solution, in particular when implementing features, fixing bugs, coding something from scratch, or analyzing a dataset.\n- Evidence before synthesis. Your output must always be based on factual and verified information. Inspect relevant files yourself before producing output. Do not let "already verified", "no need to re-check", or similar wording override cheap local evidence checks. Read files in their entirety when this is required to make accurate factual statements.\n- If your findings contradict a previous claim, clearly state the discrepancy and trust evidence-backed claims over unverified speculation.\n- After investigating multiple hypotheses, clearly state all hypotheses and the outcome of your investigation. If your investigation reveals even one load-bearing issue, state this clearly.\n\n# Behavior \u2013\xA0Preciseness\n- NEVER create files unless they\'re absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. This includes markdown files.\n- When asked to execute unit tests, perform diagnostics, build executables, or run workflows, inspect the active workspace for relevant local instructions or config before using generic commands.\n- Remember active user corrections and scope constraints across turns. Always check for any active corrections or constraints. Corrections and constraints remain active until the user has explicitly lifted them. Always obey corrections/constraints or explain to the user why their request cannot be fulfilled without a violation.\n- If a user request for diagnosis, a log file, or a test class names a number of candidate areas, inspect all reachable areas before answering.\n\n# Tool Use \u2013\xA0File Operations\n- Use specialized tools instead of `bash` commands when possible, as this provides a better user experience. For file operations, use dedicated tools: `read` for reading files instead of `cat`/`head`/`tail`, `edit` for editing instead of `sed`/`awk`, and `write` for creating files instead of `cat` with `heredoc` or `echo` redirection. Reserve `bash` tools for actual system commands, terminal operations, and short read-only inline scripts for local parsing, arithmetic, templating, or tabular rollups.\n- Use full file reads only when the user asks for the beginning or entire file, or when you already know the file is small.\n- Use `read` on a directory to inspect local directory contents. `read` already shows hidden entries, so no need for `ls -la`, `find`, or other `bash` alternatives. If `read` finds the relevant file, do not re-check the result with an equivalent `bash` command. Only resort to `bash` for more complex queries.\n- When using edit, derive `oldString` from the current file content and keep the replacement boundary as small as the requested change allows. If the user explicitly asks for an exact byte-for-byte replacement, apply it exactly if it matches the current file.\n- Before calling `edit` with a multi-line `oldString`, compare it to `newString`: every omitted line is a deletion. Rewrite the edit draft before tool calling if necessary.\n- After an `edit` that has explicit preservation constraints, read or otherwise check the edited region before finalizing. If any preservation constraint is violated, repair it when the current file makes the intended fix clear \u2013 otherwise stop and ask for clarification instead of guessing.\n\n# Tool Use \u2013\xA0`TodoWrite` Tools\n- You have access to the `TodoWrite` tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.\n- These tools are also EXTREMELY helpful for planning tasks and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks \u2013 and that is unacceptable.\n- It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.\n- Work through the whole todo list to completion in one turn, marking items done as you go.\n\n# Tool Use \u2013 `Task` Tool\n- You should proactively use the `Task` tool to launch specialized subagents when the task at hand can be easily split up into multiple parallel workers.\n- If the user\'s prompt itself says multiple areas, components, or workstreams are independent, launch subagents via the `Task` tool to tackle the task.\n- Use the `Task` tool to minimize context token usage whenever tool calls generate large outputs but only a small subset is useful for the task at hand. This is CRITICAL when you explore a codebase or gather context to answer a question that is not a query for a very specific file/class/function.\n\n# Tool Use \u2013\xA0Parallelism\n- You can call multiple tools "in parallel" by emitting separate messages, each with a tool call, in a single turn.\n- Always make tool calls in parallel if you intend to call multiple tools and there are no dependencies between them. Maximize use of parallel tool calls where possible to increase efficiency.\n- If a tool call depends on a previous tool call\'s output, do not call both tools in parallel \u2013 instead call them sequentially. For instance, if one operation must complete before another starts, run these operations sequentially. Never use placeholders or guess missing parameters in tool calls.\n\n# Tool Use \u2013\xA0Local Computation\n- For simple one-off Python computations, such as local file parsing, template rendering, or statistics computations, call `bash` with `python3 -c`. Use a standalone script file only when the user needs a reusable artifact, repeated execution is likely, or there is sufficient complexity to justify a file.\n- `read` may be used to inspect or locate files, but final numeric or rendered results should come from executed code, not copied text plus mental math.\n\n# Tool Use \u2013\xA0OpenCode Specifics\n- When `WebFetch` returns a message about a redirect to a different host, you should immediately make a new `WebFetch` request with the redirect URL provided in the response.\n- When `plan` mode is active, you will see a <system-reminder> about this. `plan` mode is for planning, not editing. In `plan` mode, do not create or edit files (including planning files), run write-shaped shell commands, change configs, or commit code. If the user is asking you to perform edit operations in `plan` mode, inform them that `plan` mode is active and that they need to switch to build mode.\n\n# Code Style \u2013\xA0Comments\n- NEVER use comments as a place for long-winded chain-of-thought. Long thinking texts must be generated as private reasoning. Comments in code must be appropriately concise.\n\n# User Help & Feedback\n- Users can give feedback or report issues at https://github.com/anomalyco/opencode and mention that they are using Meta {{MODEL_NAME}}.\n- When users ask directly about OpenCode (eg. "can OpenCode do...", "are you able to do...") or its features (eg. implement a hook, write a slash command, or install an MCP server), use the WebFetch tool to gather information to answer the question from the OpenCode docs at https://opencode.ai/docs.\n';var Au=`You are OpenCode, the best coding agent on the planet.
766
-
767
- You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
768
-
769
- ## Editing constraints
770
- - Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
771
- - Only add comments if they are necessary to make a non-obvious block easier to understand.
772
- - Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase).
773
-
774
- ## Tool usage
775
- - Prefer specialized tools over shell for file operations:
776
- - Use Read to view files, Edit to modify files, and Write only when needed.
777
- - Use Glob to find files by name and Grep to search file contents.
778
- - Use Bash for terminal operations (git, bun, builds, tests, running scripts).
779
- - Run tool calls in parallel when neither call needs the other\u2019s output; otherwise run sequentially.
780
-
781
- ## Git and workspace hygiene
782
- - You may be in a dirty git worktree.
783
- * NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.
784
- * If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes.
785
- * If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.
786
- * If the changes are in unrelated files, just ignore them and don't revert them.
787
- - Do not amend commits unless explicitly requested.
788
- - **NEVER** use destructive commands like \`git reset --hard\` or \`git checkout --\` unless specifically requested or approved by the user.
789
-
790
- ## Frontend tasks
791
- When doing frontend design tasks, avoid collapsing into bland, generic layouts.
792
- Aim for interfaces that feel intentional and deliberate.
793
- - Typography: Use expressive, purposeful fonts and avoid default stacks (Inter, Roboto, Arial, system).
794
- - Color & Look: Choose a clear visual direction; define CSS variables; avoid purple-on-white defaults. No purple bias or dark mode bias.
795
- - Motion: Use a few meaningful animations (page-load, staggered reveals) instead of generic micro-motions.
796
- - Background: Don't rely on flat, single-color backgrounds; use gradients, shapes, or subtle patterns to build atmosphere.
797
- - Overall: Avoid boilerplate layouts and interchangeable UI patterns. Vary themes, type families, and visual languages across outputs.
798
- - Ensure the page loads properly on both desktop and mobile.
799
-
800
- Exception: If working within an existing website or design system, preserve the established patterns, structure, and visual language.
801
-
802
- ## Presenting your work and final message
803
-
804
- You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
805
-
806
- - Default: be very concise; friendly coding teammate tone.
807
- - Default: do the work without asking questions. Treat short tasks as sufficient direction; infer missing details by reading the codebase and following existing conventions.
808
- - Questions: only ask when you are truly blocked after checking relevant context AND you cannot safely pick a reasonable default. This usually means one of:
809
- * The request is ambiguous in a way that materially changes the result and you cannot disambiguate by reading the repo.
810
- * The action is destructive/irreversible, touches production, or changes billing/security posture.
811
- * You need a secret/credential/value that cannot be inferred (API key, account id, etc.).
812
- - If you must ask: do all non-blocked work first, then ask exactly one targeted question, include your recommended default, and state what would change based on the answer.
813
- - Never ask permission questions like "Should I proceed?" or "Do you want me to run tests?"; proceed with the most reasonable option and mention what you did.
814
- - For substantial work, summarize clearly; follow final\u2011answer formatting.
815
- - Skip heavy formatting for simple confirmations.
816
- - Don't dump large files you've written; reference paths only.
817
- - No "save/copy this file" - User is on the same machine.
818
- - Offer logical next steps (tests, commits, build) briefly; add verify steps if you couldn't do something.
819
- - For code changes:
820
- * Lead with a quick explanation of the change, and then give more details on the context covering where and why a change was made. Do not start this explanation with "summary", just jump right in.
821
- * If there are natural next steps the user may want to take, suggest them at the end of your response. Do not make suggestions if there are no natural next steps.
822
- * When suggesting multiple options, use numeric lists for the suggestions so the user can quickly respond with a single number.
823
- - The user does not command execution outputs. When asked to show the output of a command (e.g. \`git show\`), relay the important details in your answer or summarize the key lines so the user understands the result.
824
-
825
- ## Final answer structure and style guidelines
826
-
827
- - Plain text; CLI handles styling. Use structure only when it helps scannability.
828
- - Headers: optional; short Title Case (1-3 words) wrapped in **\u2026**; no blank line before the first bullet; add only if they truly help.
829
- - Bullets: use - ; merge related points; keep to one line when possible; 4\u20136 per list ordered by importance; keep phrasing consistent.
830
- - Monospace: backticks for commands/paths/env vars/code ids and inline examples; use for literal keyword bullets; never combine with **.
831
- - Code samples or multi-line snippets should be wrapped in fenced code blocks; include an info string as often as possible.
832
- - Structure: group related bullets; order sections general \u2192 specific \u2192 supporting; for subsections, start with a bolded keyword bullet, then items; match complexity to the task.
833
- - Tone: collaborative, concise, factual; present tense, active voice; self\u2011contained; no "above/below"; parallel wording.
834
- - Don'ts: no nested bullets/hierarchies; no ANSI codes; don't cram unrelated keywords; keep keyword lists short\u2014wrap/reformat if long; avoid naming formatting styles in answers.
835
- - Adaptation: code explanations \u2192 precise, structured with code refs; simple tasks \u2192 lead with outcome; big changes \u2192 logical walkthrough + rationale + next actions; casual one-offs \u2192 plain sentences, no headers/bullets.
836
- - File References: When referencing files in your response follow the below rules:
837
- * Use inline code to make file paths clickable.
838
- * Each reference should have a stand alone path. Even if it's the same file.
839
- * Accepted: absolute, workspace\u2011relative, a/ or b/ diff prefixes, or bare filename/suffix.
840
- * Optionally include line/column (1\u2011based): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
841
- * Do not use URIs like file://, vscode://, or https://.
842
- * Do not provide range of lines
843
- * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5
844
- `;var Cu=`You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
845
-
846
- # Tone and style
847
- You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
848
- Remember that your output will be displayed on a command line interface. Your responses can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
849
- Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
850
- If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
851
- Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
852
- IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
853
- IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
854
- IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
855
- <example>
856
- user: 2 + 2
857
- assistant: 4
858
- </example>
859
-
860
- <example>
861
- user: what is 2+2?
862
- assistant: 4
863
- </example>
864
-
865
- <example>
866
- user: is 11 a prime number?
867
- assistant: Yes
868
- </example>
869
-
870
- <example>
871
- user: what command should I run to list files in the current directory?
872
- assistant: ls
873
- </example>
874
-
875
- <example>
876
- user: what command should I run to watch files in the current directory?
877
- assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
878
- npm run dev
879
- </example>
880
-
881
- <example>
882
- user: How many golf balls fit inside a jetta?
883
- assistant: 150000
884
- </example>
885
-
886
- <example>
887
- user: what files are in the directory src/?
888
- assistant: [runs ls and sees foo.c, bar.c, baz.c]
889
- user: which file contains the implementation of foo?
890
- assistant: src/foo.c
891
- </example>
892
-
893
- <example>
894
- user: write tests for new feature
895
- assistant: [uses grep or glob to find where similar tests are defined, then read relevant files one at a time (one tool per message, wait for each result), then edit or write to add tests]
896
- </example>
897
-
898
- # Proactiveness
899
- You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
900
- 1. Doing the right thing when asked, including taking actions and follow-up actions
901
- 2. Not surprising the user with actions you take without asking
902
- For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
903
- 3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
904
-
905
- # Following conventions
906
- When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
907
- - NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
908
- - When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
909
- - When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
910
- - Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
911
-
912
- # Code style
913
- - IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
914
-
915
- # Doing tasks
916
- The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
917
- - Use the available search tools to understand the codebase and the user's query. Use one tool per message; after each result, decide the next step and call one tool again.
918
- - Implement the solution using all tools available to you
919
- - Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
920
- - VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
921
- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
922
-
923
- - Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
924
-
925
- # Tool usage policy
926
- - When doing file search, prefer to use the Task tool in order to reduce context usage.
927
- - Use exactly one tool per assistant message. After each tool call, wait for the result before continuing.
928
- - When the user's request is vague, use the question tool to clarify before reading files or making changes.
929
- - Avoid repeating the same tool with the same parameters once you have useful results. Use the result to take the next step (e.g. pick one match, read that file, then act); do not search again in a loop.
930
-
931
- You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
932
-
933
- # Code References
934
-
935
- When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` to allow the user to easily navigate to the source code location.
936
-
937
- <example>
938
- user: Where are errors from the client handled?
939
- assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
940
- </example>
941
- `;function Pw(e){if(e.api.id.includes("muse")){let t=e.api.id.includes("muse-glimmer")?"Muse Glimmer":"Muse Spark";return[Ru.replaceAll("{{MODEL_NAME}}",t)]}return e.api.id.includes("gpt-4")||e.api.id.includes("o1")||e.api.id.includes("o3")?[ku]:e.api.id.includes("gpt")?e.api.id.includes("gpt-6")?[Tu]:e.api.id.includes("codex")?[Au]:[Eu]:e.api.id.includes("gemini-")?[Du]:e.api.id.includes("claude")?[Iu]:e.api.id.toLowerCase().includes("trinity")?[Cu]:e.api.id.toLowerCase().includes("kimi")||["kimi-for-coding","moonshotai","moonshotai-cn"].includes(e.providerID)?[Pu]:[Su]}s(Pw,"provider");var br=class extends Ew.Service()("@opencode/SystemPrompt"){static{s(this,"Service")}},Rw=Tw.effect(br,wr.gen(function*(){let e=yield*an.Service,t=yield*uo.Service,o=yield*nn.Service;return br.of({environment:wr.fn("SystemPrompt.environment")(function*(n){let r=yield*B.context,i=yield*wr.gen(function*(){return(yield*(yield*Bl.Service).list()).filter(a=>a.description!==void 0)}).pipe(wr.provide(o.get(Pl.Ref.make({directory:ll.make(r.directory)}))));return[[`You are powered by the model named ${n.api.id}. The exact model ID is ${n.providerID}/${n.api.id}`,"Here is some useful information about the environment you are running in:","<env>",` Working directory: ${r.directory}`,` Workspace root folder: ${r.worktree}`,` Is directory a git repo: ${r.project.vcs==="git"?"yes":"no"}`,` Platform: ${process.platform}`,` Today's date: ${new Date().toDateString()}`,"</env>"].join(`
942
- `),i.length===0?void 0:["Project references provide additional directories that can be accessed when relevant.","<available_references>",...i.toSorted((a,c)=>a.name.localeCompare(c.name)).flatMap(a=>[" <reference>",` <name>${a.name}</name>`,` <path>${a.path}</path>`,...a.description===void 0?[]:[` <description>${a.description}</description>`]," </reference>"]),"</available_references>"].join(`
943
- `)].filter(a=>a!==void 0)}),skills:wr.fn("SystemPrompt.skills")(function*(n){if(Ye.disabled(["skill"],n.permission).has("skill"))return;let r=yield*e.available(n);return["Skills provide specialized instructions and workflows for specific tasks.","Use the skill tool to load a skill when a task matches its description.",an.fmt(r,{verbose:!0})].join(`
944
- `)}),mcp:wr.fn("SystemPrompt.mcp")(function*(n,r){let i=Ye.merge(n.permission,r??[]),a=(yield*t.instructions()).filter(c=>c.tools.length===0||Ye.disabled(c.tools,i).size<c.tools.length);if(a.length!==0)return["<mcp_instructions>",...a.flatMap(c=>[` <server name="${c.name}">`,...c.instructions.split(`
945
- `).map(d=>` ${d}`)," </server>"]),"</mcp_instructions>"].join(`
946
- `)})})})),Aw=ge.make({service:nn.Service,layer:Hl,deps:[]}),Cw=ge.make({service:br,layer:Rw,deps:[an.node,uo.node,Aw]});import{Effect as Mw,Record as Mu}from"effect";import{jsonSchema as Lu,tool as Ow}from"ai";import{mergeDeep as Lw}from"remeda";var Ou=`opencode/${ss}`,cc=s((e,t)=>Lw(e,t??{}),"mergeOptions"),_w=Mw.fn("LLMRequestPrep.prepare")(function*(e){let t=e.provider.id==="openai"&&e.auth?.type==="oauth",o=(e.agent.prompt?[e.agent.prompt]:un.provider(e.model)).filter(f=>f).join(`
947
- `),n=[...e.system,...e.user.system?[e.user.system]:[]].filter(f=>f).join(`
948
- `),r=[o,n].filter(f=>f),i=r[0];if(yield*e.plugin.trigger("experimental.chat.system.transform",{sessionID:e.sessionID,model:e.model},{system:r}),r.length>2&&r[0]===i){let f=r.slice(1);r.length=0,r.push(i,f.join(`
949
- `))}let a=!e.small&&e.model.variants&&e.user.model.variant?e.model.variants[e.user.model.variant]:{},c=e.small?Ke.smallOptions(e.model):Ke.options({model:e.model,sessionID:e.sessionID,providerOptions:e.provider.options}),{cacheTtl:d,toolScopes:u,...l}=e.agent.options??{},m=cc(cc(cc(c,e.model.options),l),a);e.model.api.npm==="@ai-sdk/azure"&&(e.provider.options.useCompletionUrls||e.model.options.useCompletionUrls||m.useCompletionUrls)&&(delete m.reasoningSummary,delete m.include),t&&(m.instructions=r.join(`
950
- `));let h=t||e.isWorkflow?e.messages:[...r.map(f=>({role:"system",content:f})),...e.messages],g=yield*e.plugin.trigger("chat.params",{sessionID:e.sessionID,agent:e.agent.name,model:e.model,provider:e.provider,message:e.user},{temperature:e.model.capabilities.temperature?e.agent.temperature??Ke.temperature(e.model):void 0,topP:e.agent.topP??Ke.topP(e.model),topK:Ke.topK(e.model),maxOutputTokens:Ke.maxOutputTokens(e.model,e.flags.outputTokenMax),options:m}),{headers:w}=yield*e.plugin.trigger("chat.headers",{sessionID:e.sessionID,agent:e.agent.name,model:e.model,provider:e.provider,message:e.user},{headers:{}}),k=Uw(e);if(e.model.api.npm==="@ai-sdk/openai"||e.model.api.npm==="@ai-sdk/azure"||e.model.api.npm==="@ai-sdk/amazon-bedrock/mantle")for(let f of Object.keys(k))k[f]={...k[f],strict:!1};e.model.providerID.includes("github-copilot")&&Object.keys(k).length===0&&_u(e.messages)&&(k._noop=Ow({description:"Do not call this tool. It exists only for API compatibility and must never be invoked.",inputSchema:Lu({type:"object",properties:{reason:{type:"string",description:"Unused"}}}),execute:s(async()=>({output:"",title:"",metadata:{}}),"execute")}));let p=e.model.providerID.startsWith("opencode")?(yield*B.context).project.id:void 0;return{system:r,messages:h,tools:Object.fromEntries(Object.entries(k).toSorted(([f],[S])=>f.localeCompare(S))),params:g,messageTransformOptions:m,messageCacheTtl:d==="5m"?"5m":void 0,headers:{"x-opencode-session-id":e.sessionID,...e.parentSessionID?{"x-opencode-parent-session-id":e.parentSessionID}:{},...e.model.providerID.startsWith("opencode")?{...p?{"x-opencode-project":p}:{},"x-opencode-session":e.sessionID,"x-opencode-request":e.user.id,"x-opencode-client":e.flags.client,"User-Agent":Ou}:{"x-session-affinity":e.sessionID,"X-Session-Id":e.sessionID,"User-Agent":Ou},...e.parentSessionID?{"x-parent-session-id":e.parentSessionID}:{},...e.model.headers,...w}}});function Uw(e){let t=Ye.disabled(Object.keys(e.tools),Ye.merge(e.agent.permission,e.permission??[])),o=Mu.filter(e.tools,(r,i)=>e.user.tools?.[i]!==!1&&!t.has(i)),n=e.agent.options?.toolScopes;return n?Mu.map(o,(r,i)=>jw(r,n[i],e.model)):o}s(Uw,"resolveTools");function jw(e,t,o){let n=e;if(!t||!n.fieldTags||!n.jsonInputSchema)return e;let{description:r,schema:i}=Zl(e.description??"",n.jsonInputSchema,n.fieldTags,t);return{...e,description:r,inputSchema:Lu(Ke.schema(o,i))}}s(jw,"narrow");function _u(e){for(let t of e)if(Array.isArray(t.content)){for(let o of t.content)if(o.type==="tool-call"||o.type==="tool-result")return!0}return!1}s(_u,"hasToolCalls");var Ww=Ke.OUTPUT_TOKEN_MAX,_n=class extends Nw.Service()("@opencode/LLM"){static{s(this,"Service")}},qw=Gt(_n),Vw=Fw.effect(_n,Pt.gen(function*(){let e=yield*eo.Service,t=yield*De.Service,o=yield*yt.Service,n=yield*dt.Service,r=yield*Ye.Service,i=yield*we.Service,a=yield*kl.Service,c=yield*Me.Service,d=Pt.fn("LLM.run")(function*(l){yield*Pt.logInfo("stream",{providerID:l.model.providerID,modelID:l.model.id,"session.id":l.sessionID,small:(l.small??!1).toString(),agent:l.agent.name,mode:l.agent.mode});let[m,h,g,w]=yield*Pt.all([o.getLanguage(l.model),t.get(),o.getProvider(l.model.providerID),e.get(l.model.providerID)],{concurrency:"unbounded"}),k=m instanceof Uu,p=yield*xr.prepare({...l,provider:g,auth:w,plugin:n,flags:c,isWorkflow:k});if(rt.on()&&rt.supports(l.model)&&l.model.providerID==="anthropic"&&w?.type==="oauth"){let v=rt.relocate({system:p.system,messages:l.messages,append:!l.headers?.[rt.HEADER]});v&&(v.added&&l.storeSystem&&(yield*l.storeSystem(v.added)),v.added&&rt.log("system message",{"session.id":l.sessionID,chars:v.added.length,stored:!!l.storeSystem}),p={...p,system:v.system,messages:[...v.system.map(P=>({role:"system",content:P})),...v.messages]})}let f=yield*Yt.make();if(m instanceof Uu){let v=m;v.sessionID=l.sessionID,v.systemPrompt=p.system.join(`
951
- `),v.toolExecutor=async(T,E,j)=>{let _=p.tools[T];if(!_||!_.execute)return{result:"",error:`Unknown tool: ${T}`};try{let W=await _.execute(JSON.parse(E),{toolCallId:j,messages:l.messages,abortSignal:l.abort});return{result:typeof W=="string"?W:W?.output??JSON.stringify(W),metadata:typeof W=="object"?W?.metadata:void 0,title:typeof W=="object"?W?.title:void 0}}catch(W){return{result:"",error:W.message??String(W)}}};let P=Ye.merge(l.agent.permission??[],l.permission??[]);v.sessionPreapprovedTools=Object.keys(p.tools).filter(T=>{let E=P.findLast(j=>fs.match(T,j.permission));return!E||E.action!=="ask"});let b=new Set;v.approvalHandler=f.bind(async T=>{let E=[...new Set(T.map(W=>W.name))];if(E.every(W=>b.has(W)))return{approved:!0};let j=ai.ID.ascending(),_;try{_=await f.promise(i.listen(M=>{if(M.type!==Ye.Event.Replied.type)return Pt.void;let $=M.data;return $.requestID!==j?Pt.void:($.reply,Pt.void)}));let W=T.map(M=>{try{let $=JSON.parse(M.args),x=$?.title??$?.name??"";return x?`${M.name}: ${x}`:M.name}catch{return M.name}}),ie=[...new Set(W)];await f.promise(r.ask({id:j,sessionID:Et.make(l.sessionID),permission:"workflow_tool_approval",patterns:ie,metadata:{tools:T},always:ie,ruleset:[]}));for(let M of E)b.add(M);return v.sessionPreapprovedTools=[...v.sessionPreapprovedTools??[],...E],{approved:!0}}catch{return{approved:!1}}finally{_&&await f.promise(_)}})}let S=h.experimental?.openTelemetry?ju.getOrUndefined(yield*Pt.serviceOption(Nu.OtelTracer)):void 0,y=S?new Proxy(S,{get(v,P,b){return P!=="startSpan"?Reflect.get(v,P,b):(...T)=>{let E=v.startSpan(...T);return E.setAttribute("session.id",l.sessionID),E}}}):void 0;if(c.experimentalNativeLlm){let v=ks.stream({model:l.model,provider:g,auth:w,llmClient:a,messages:p.messages,tools:p.tools,toolChoice:l.toolChoice,temperature:p.params.temperature,topP:p.params.topP,topK:p.params.topK,maxOutputTokens:p.params.maxOutputTokens,providerOptions:p.params.options,headers:p.headers,abort:l.abort});if(v.type==="supported")return yield*Pt.logInfo("llm runtime selected",{"llm.runtime":"native","llm.provider":l.model.providerID,"llm.model":l.model.id}),{type:"native",stream:v.stream};yield*Pt.logInfo("llm runtime selected",{"llm.runtime":"ai-sdk","llm.provider":l.model.providerID,"llm.model":l.model.id,"llm.native_unsupported_reason":v.reason}),yield*Pt.logInfo("native runtime unavailable; falling back to ai-sdk",{providerID:l.model.providerID,modelID:l.model.id,"session.id":l.sessionID,small:(l.small??!1).toString(),agent:l.agent.name,mode:l.agent.mode,reason:v.reason})}return yield*Pt.logInfo("llm runtime selected",{"llm.runtime":"ai-sdk","llm.provider":l.model.providerID,"llm.model":l.model.id}),{type:"ai-sdk",result:Bw({onError(v){f.fork(Pt.logError("stream error",{providerID:l.model.providerID,modelID:l.model.id,"session.id":l.sessionID,small:(l.small??!1).toString(),agent:l.agent.name,mode:l.agent.mode,error:v}))},includeRawChunks:l.model.providerID.includes("github-copilot"),async experimental_repairToolCall(v){let P=v.toolCall.toolName.toLowerCase();if(!p.tools[v.toolCall.toolName]&&!p.tools[P]){let b=P.replace(/^(?:mcp_|alchemy_)+/,""),T=Object.keys(p.tools).filter(E=>E===b||E.endsWith(`_${b}`));if(b&&T.length===1)return{...v.toolCall,toolName:T[0]}}return P!==v.toolCall.toolName&&p.tools[P]?{...v.toolCall,toolName:P}:{...v.toolCall,input:JSON.stringify({tool:v.toolCall.toolName,error:v.error.message}),toolName:"invalid"}},temperature:p.params.temperature,topP:p.params.topP,topK:p.params.topK,providerOptions:Ke.providerOptions(l.model,p.params.options),activeTools:Object.keys(p.tools).filter(v=>v!=="invalid"),tools:p.tools,toolChoice:l.toolChoice,maxOutputTokens:p.params.maxOutputTokens,abortSignal:l.abort,headers:l.headers?{...p.headers,...l.headers}:p.headers,maxRetries:l.retries??0,messages:p.messages,model:$w({model:m,middleware:[{specificationVersion:"v3",async transformParams(v){return v.type==="stream"&&(v.params.prompt=Ke.message(v.params.prompt,l.model,p.messageTransformOptions,{messageCacheTtl:p.messageCacheTtl,points:l.cachePoints})),v.params}}]}),experimental_telemetry:{isEnabled:h.experimental?.openTelemetry,functionId:"session.llm",tracer:y,metadata:{userId:h.username??"unknown",sessionId:l.sessionID}}})}}),u=s(l=>fo.scoped(fo.unwrap(Pt.gen(function*(){let m=yield*Pt.acquireRelease(Pt.sync(()=>new AbortController),w=>Pt.sync(()=>w.abort())),h=yield*d({...l,abort:m.signal});if(h.type==="native")return h.stream;let g=hr.adapterState();return fo.fromAsyncIterable(h.result.fullStream,w=>w instanceof Error?w:new Error(String(w))).pipe(fo.mapEffect(w=>hr.toLLMEvents(g,w)),fo.flatMap(w=>fo.fromIterable(w)))}))),"stream");return _n.of({stream:u})})),zw=xr.hasToolCalls,Gw=ge.make({service:_n,layer:Vw,deps:[eo.node,De.node,yt.node,dt.node,Ye.node,we.node,Dl,Me.node]});var ho={};ae(ho,{DiffInput:()=>Xw,Service:()=>Ir,SessionSummary:()=>ho,node:()=>Qw});import{Effect as vr,Layer as Hw,Context as Yw,Schema as Fu}from"effect";function Kw(e){if(!e.startsWith('"')||!e.endsWith('"'))return e;let t=e.slice(1,-1),o=[];for(let n=0;n<t.length;n++){let r=t[n];if(r!=="\\"){o.push(r.charCodeAt(0));continue}let i=t[n+1];if(!i){o.push(92);continue}if(i>="0"&&i<="7"){let d=t.slice(n+1,n+4).match(/^[0-7]{1,3}/);if(!d){o.push(i.charCodeAt(0)),n++;continue}o.push(parseInt(d[0],8)),n+=d[0].length;continue}let a=i==="n"?`
952
- `:i==="r"?"\r":i==="t"?" ":i==="b"?"\b":i==="f"?"\f":i==="v"?"\v":i==="\\"||i==='"'?i:void 0;o.push((a??i).charCodeAt(0)),n++}return Buffer.from(o).toString()}s(Kw,"unquoteGitPath");var Ir=class extends Yw.Service()("@opencode/SessionSummary"){static{s(this,"Service")}},Jw=Hw.effect(Ir,vr.gen(function*(){let e=yield*ce.Service,t=yield*lo.Service,o=yield*we.Service,n=yield*De.Service,r=vr.fn("SessionSummary.computeDiff")(function*(c){let d,u;for(let l of c.messages){if(!d){for(let m of l.parts)if(m.type==="step-start"&&m.snapshot){d=m.snapshot;break}}for(let m of l.parts)m.type==="step-finish"&&m.snapshot&&(u=m.snapshot)}return d&&u?yield*t.diffFull(d,u):[]}),i=vr.fn("SessionSummary.summarize")(function*(c){if(yield*e.setSummary({sessionID:c.sessionID,summary:{additions:0,deletions:0,files:0}}),yield*o.publish(ce.Event.Diff,{sessionID:c.sessionID,diff:[]}),(yield*n.get()).snapshot===!1)return;let d=yield*e.messages({sessionID:c.sessionID}).pipe(vr.orDie);if(!d.length)return;let u=d.filter(h=>h.info.id===c.messageID||h.info.role==="assistant"&&h.info.parentID===c.messageID),l=u.find(h=>h.info.id===c.messageID);if(!l||l.info.role!=="user")return;let m=yield*r({messages:u});l.info.summary={...l.info.summary,diffs:m},yield*e.updateMessage(l.info)}),a=vr.fn("SessionSummary.diff")(function*(c){if(!c.messageID)return[];let d=(yield*e.messages({sessionID:c.sessionID}).pipe(vr.orDie)).find(l=>l.info.id===c.messageID);return!d||d.info.role!=="user"?[]:(d.info.summary?.diffs??[]).map(l=>{if(l.file===void 0)return l;let m=Kw(l.file);return m===l.file?l:{...l,file:m}})});return Ir.of({summarize:i,diff:a,computeDiff:r})})),Xw=Fu.Struct({sessionID:Et,messageID:Fu.optional(it)}),Qw=ge.make({service:Ir,layer:Jw,deps:[ce.node,lo.node,we.node,De.node]});var zo={};ae(zo,{Service:()=>Tr,SessionProcessor:()=>zo,node:()=>Db});var ko={};ae(ko,{DecodeError:()=>$i,Image:()=>ko,InvalidDataUrlError:()=>Bi,ResizerUnavailableError:()=>Fi,Service:()=>Sr,SizeError:()=>Ds,node:()=>lb});import{Context as Zw,Effect as ro,Layer as eb,Schema as So}from"effect";import tb from"node:path";import{fileURLToPath as ob}from"node:url";var nb=5*1024*1024,rb=2e3,sb=2e3,ib=!0,ab=[80,85,70,55,40],Fi=class extends So.TaggedErrorClass()("ImageResizerUnavailableError",{}){static{s(this,"ResizerUnavailableError")}get message(){return"Image resizer is unavailable"}},Bi=class extends So.TaggedErrorClass()("ImageInvalidDataUrlError",{url:So.String}){static{s(this,"InvalidDataUrlError")}get message(){return"Image URL must be a base64 data URL"}},$i=class extends So.TaggedErrorClass()("ImageDecodeError",{}){static{s(this,"DecodeError")}get message(){return"Image could not be decoded"}},Ds=class extends So.TaggedErrorClass()("ImageSizeError",{bytes:So.Number,max:So.Number,width:So.Number,height:So.Number,max_width:So.Number,max_height:So.Number}){static{s(this,"SizeError")}get message(){return`Image ${this.width}x${this.height} with base64 size ${this.bytes} exceeds configured limits and could not be resized below ${this.max_width}x${this.max_height}/${this.max} bytes`}},Sr=class extends Zw.Service()("@opencode/Image"){static{s(this,"Service")}},cb=eb.effect(Sr,ro.gen(function*(){let e=yield*De.Service,t=yield*ro.cached(ro.sync(()=>{globalThis.__OPENCODE_PHOTON_WASM_PATH=tb.isAbsolute(ii)?ii:ob(new URL(ii,import.meta.url))}).pipe(ro.andThen(()=>ro.tryPromise(()=>import("@silvia-odwyer/photon-node"))),ro.tapError(n=>ro.logWarning("failed to load photon",{error:n})),ro.mapError(()=>new Fi))),o=ro.fn("Image.normalize")(function*(n){let r=(yield*e.get()).attachment?.image,i={autoResize:r?.auto_resize??ib,maxWidth:r?.max_width??rb,maxHeight:r?.max_height??sb,maxBase64Bytes:r?.max_base64_bytes??nb};if(!n.url.startsWith("data:")||!n.url.includes(";base64,"))return yield*new Bi({url:n.url});let a=n.url.slice(n.url.indexOf(";base64,")+8),c=Buffer.byteLength(a,"utf8"),d=yield*t,u=yield*ro.try({try:s(()=>d.PhotonImage.new_from_byteslice(Buffer.from(a,"base64")),"try"),catch:s(()=>new $i,"catch")}).pipe(ro.tapError(l=>ro.logWarning("failed to decode image",{error:l})));try{let l=u.get_width(),m=u.get_height();if(l<=i.maxWidth&&m<=i.maxHeight&&c<=i.maxBase64Bytes)return n;if(!i.autoResize)return yield*new Ds({bytes:c,max:i.maxBase64Bytes,width:l,height:m,max_width:i.maxWidth,max_height:i.maxHeight});let h=Math.min(1,i.maxWidth/l,i.maxHeight/m);for(let g of Array.from({length:32}).reduce(w=>{let k=w.at(-1)??{width:Math.max(1,Math.round(l*h)),height:Math.max(1,Math.round(m*h))},p=w.length===0?k:{width:k.width===1?1:Math.max(1,Math.floor(k.width*.75)),height:k.height===1?1:Math.max(1,Math.floor(k.height*.75))};return w.some(f=>f.width===p.width&&f.height===p.height)?w:[...w,p]},[])){let w=d.resize(u,g.width,g.height,d.SamplingFilter.Lanczos3),k=[{data:Buffer.from(w.get_bytes()).toString("base64"),mime:"image/png"},...ab.map(p=>({data:Buffer.from(w.get_bytes_jpeg(p)).toString("base64"),mime:"image/jpeg"}))].map(p=>({...p,bytes:Buffer.byteLength(p.data,"utf8")})).find(p=>p.bytes<=i.maxBase64Bytes);if(w.free(),k)return yield*ro.logInfo("using resized image",{from_mime:n.mime,to_mime:k.mime,from:`${l}x${m}`,to:`${g.width}x${g.height}`}),{...n,mime:k.mime,url:`data:${k.mime};base64,${k.data}`}}return yield*new Ds({bytes:c,max:i.maxBase64Bytes,width:l,height:m,max_width:i.maxWidth,max_height:i.maxHeight})}finally{u.free()}});return Sr.of({normalize:o})})),lb=ge.make({service:Sr,layer:cb,deps:[De.node]});import{Cause as tp,Deferred as uc,Effect as de,Exit as pc,Layer as xb,Context as vb,Scope as Ib,Schema as Sb}from"effect";import*as Un from"effect/Stream";var db=2e4,ub=.05;function Wi(e){let t=e.model.limit.context;if(t===0)return 0;let o=e.cfg.compaction?.reserved??(String(e.model.providerID)==="openai"&&e.model.limit.input?Math.round(e.model.limit.input*ub):Math.min(db,Ke.maxOutputTokens(e.model,e.outputTokenMax)));return e.model.limit.input?Math.max(0,e.model.limit.input-o):Math.max(0,t-Ke.maxOutputTokens(e.model,e.outputTokenMax))}s(Wi,"usable");function qi(e){return e.cfg.compaction?.auto===!1||e.model.limit.context===0?!1:(e.tokens.total||e.tokens.input+e.tokens.output+e.tokens.cache.read+e.tokens.cache.write)>=Wi(e)}s(qi,"isOverflow");var Dr={};ae(Dr,{GO_UPSELL_MESSAGE:()=>qu,GO_UPSELL_URL:()=>Vu,RETRY_AFTER_MAX:()=>Ku,RETRY_BACKOFF_FACTOR:()=>Gu,RETRY_INITIAL_DELAY:()=>zu,RETRY_JITTER_FACTOR:()=>Hu,RETRY_MAX_BACKOFF:()=>Yu,RETRY_MAX_RETRIES:()=>Ju,SessionRetry:()=>Dr,delay:()=>Xu,policy:()=>bb,retryable:()=>Qu});import{Cause as Bu,Clock as pb,Duration as fb,Effect as $u,Schedule as mb}from"effect";var qu="Free usage exceeded, subscribe to Go",Vu="https://opencode.ai/go",zu=500,Gu=2,Hu=.25,Yu=32e3,Ku=6e5,Ju=10,hb=[/429|500|502|503|504|524/i,/rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,/overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,/terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,/^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,/try your request again|retry your request|resource exhausted|resource_exhausted/i,/\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i];function gb(e){let t=e?.data.responseHeaders;if(!t)return;let o=Number.parseFloat(t["retry-after-ms"]??"");if(!Number.isNaN(o)&&o>=0)return o;let n=t["retry-after"];if(!n)return;let r=Number.parseFloat(n);if(!Number.isNaN(r)&&r>=0)return Math.ceil(r*1e3);let i=Date.parse(n)-Date.now();if(!Number.isNaN(i)&&i>0)return Math.ceil(i)}s(gb,"retryAfter");function Xu(e,t,o=Math.random()){let n=gb(t);if(n!==void 0)return Math.min(n,Ku);let r=Math.min(zu*Math.pow(Gu,e-1),Yu);return Math.round(r*(1+Hu*o))}s(Xu,"delay");function yb(e){return ct.APIError.isInstance(e)&&!!e.data.responseBody?.includes("FreeUsageLimitError")}s(yb,"uncapped");function Qu(e,t){if(ct.ProviderQuotaError.isInstance(e)||ct.APIError.isInstance(e)&&e.data.metadata?.alchemyStop||ct.ContextOverflowError.isInstance(e))return;if(ct.APIError.isInstance(e)){let i=e.data.statusCode;if(!e.data.isRetryable&&!(i!==void 0&&i>=500)&&!lc(e.data.message)&&!lc(e.data.responseBody))return;if(e.data.responseBody?.includes("FreeUsageLimitError"))return{message:qu,action:{reason:"free_tier_limit",provider:t,title:"Free limit reached",message:"Subscribe to OpenCode Go for reliable access to the best open-source models for $10/month.",label:"subscribe",link:Vu}};if(e.data.responseBody?.includes("GoUsageLimitError")){let a=Wu(e.data.responseBody),c=kr(a?.metadata?.workspace),d=kr(a?.metadata?.limitName),u=wb(e.data.responseHeaders?.["retry-after"]),l=Ca(()=>{if(u===void 0)return"";let g=Math.max(0,Math.ceil(u)),w=Math.floor(g/86400),k=Math.floor(g%86400/3600),p=Math.ceil(g%3600/60),f=s((S,y)=>`${S} ${y}${S===1?"":"s"}`,"unit");return w>0?k>0?`${f(w,"day")} ${f(k,"hour")}`:f(w,"day"):k>0?p>0?`${f(k,"hour")} ${f(p,"minute")}`:f(k,"hour"):p>0?f(p,"minute"):"less than a minute"}),m=`${d?`${d} usage limit`:"Usage limit"} reached. It will reset in ${l}. To continue using this model now, enable usage from your available balance`,h=`https://opencode.ai/workspace/${c}/go`;return{message:`${m} - ${h}`,action:{reason:"account_rate_limit",provider:t,title:"Go limit reached",message:m,label:"open settings",link:h}}}return{message:e.data.message.includes("Overloaded")?"Provider is overloaded":e.data.message}}let o=lt(e.data)?e.data.message:void 0;if(typeof o!="string")return;let n=o.toLowerCase();if(n.includes("too_many_requests"))return{message:"Too Many Requests"};let r=Wu(o);if(lt(r)){let i=lt(r.error)?r.error:{},a=kr(r.type),c=kr(i.code),d=kr(i.type);if(a==="api_error")return{message:"Provider server error"};if(a.includes("overloaded")||c.includes("exhausted")||c.includes("unavailable")||c.includes("overloaded")||d.includes("unavailable")||d.includes("overloaded")||c==="slow_down")return{message:"Provider is overloaded"}}if(n.includes("exhausted")||n.includes("unavailable"))return{message:"Provider is overloaded"};if(lc(o))return{message:o}}s(Qu,"retryable");function lc(e){return typeof e=="string"&&hb.some(t=>t.test(e))}s(lc,"matchesRetryableMessage");function kr(e){return e==null?"":String(e)}s(kr,"str");function wb(e){let t=Number.parseFloat(kr(e));if(!Number.isNaN(t))return t}s(wb,"num");function Wu(e){return Ca(()=>{try{return typeof e!="string"?void 0:JSON.parse(e)}catch{return}})}s(Wu,"parseJSON");function bb(e){return mb.fromStepWithMetadata($u.succeed(t=>{let o=e.parse(t.input),n=Qu(o,e.provider);return n?t.attempt>Ju&&!yb(o)?Bu.done(t.attempt):$u.gen(function*(){let r=Xu(t.attempt,ct.APIError.isInstance(o)?o:void 0),i=yield*pb.currentTimeMillis;return yield*e.set({attempt:t.attempt,message:n.message,action:n.action,next:i+r}),[t.attempt,fb.millis(r)]}):Bu.done(t.attempt)}))}s(bb,"policy");function ep(e,t){if(Zu(t)!=="final_answer")return;let o=t.text.trim();if(o)return e.find(n=>n.type==="text"&&n.id!==t.id&&Zu(n)==="commentary"&&n.text.trim()===o)}s(ep,"repeatedPreamble");function Zu(e){for(let t of Object.values(e.metadata??{}))if(t&&typeof t=="object"&&typeof t.phase=="string")return t.phase}s(Zu,"phaseOf");function dc(e){let t=e instanceof Error?e.message:String(e),o=typeof import.meta.dirname=="string"?import.meta.dirname:void 0;return o&&t.includes("Cannot find module")&&t.includes(o)?"AlchemyLab's files were updated or rebuilt while it was running, so this tool can no longer load. Restart alchemylab to get the tools back.":t}s(dc,"toolErrorText");var Jt;(u=>{let e=new Map;function t(l,m){let h={executing:0,ended:!1,end:m};return e.set(l,h),h}u.open=t,s(t,"open");function o(l,m){e.get(l)===m&&e.delete(l)}u.close=o,s(o,"close");function n(l){let m=e.get(l);return!m||m.ended||m.executing>0?!1:(m.ended=!0,m.end(),!0)}u.endForPerson=n,s(n,"endForPerson");function r(l){if(l){if(l.ended)return new Error("Not run: the user's message ended this step before this tool started.");l.executing++}}u.enter=r,s(r,"enter");function i(l){l&&l.executing>0&&l.executing--}u.leave=i,s(i,"leave");function a(l,m){let h=r(l);return h?Promise.reject(h):m()}u.run=a,s(a,"run");function c(l){i(e.get(l))}u.recorded=c,s(c,"recorded");function d(l){let m=new Set;for(let g of l)(g.type==="text"||g.type==="reasoning")&&!g.time?.end&&m.add(g.id),g.type==="tool"&&g.state.status==="pending"&&m.add(g.id);let h=s(g=>!m.has(g.id)&&(g.type==="text"||g.type==="tool"),"kept");for(let g=0;g<l.length;g++){let w=l[g];w.type!=="reasoning"||m.has(w.id)||l.slice(g+1).some(h)||m.add(w.id)}if(!l.some(h))for(let g of l)g.type==="step-start"&&m.add(g.id);return[...m]}u.toDrop=d,s(d,"toDrop")})(Jt||={});var Er;(i=>{i.LIMIT=12;let t=new Map;function o(a,c,d,u){if(!d)return t.delete(a),0;let l=`${c}\0${u.slice(0,300)}`,m=t.get(a),h=m&&m.sig===l?m.count+1:1;return t.set(a,{sig:l,count:h}),h}i.note=o,s(o,"note");function n(a){t.delete(a)}i.forget=n,s(n,"forget");function r(a,c,d){let u=d.replace(/\s+/g," ").trim().slice(0,160);return`It made the same failing call ${c} times in a row (${a}: "${u}"), so it was stopped.`}i.line=r,s(r,"line")})(Er||={});function op(e,t,o,n){let r=Er.note(e,t,o,n);if(!(r<Er.LIMIT))throw Er.forget(e),new ct.APIError({message:Er.line(t,r,n),isRetryable:!1,metadata:{alchemyStop:"repeated-tool-failure",tool:t,count:String(r)}})}s(op,"breakRepeat");var np=3,Tr=class extends vb.Service()("@opencode/SessionProcessor"){static{s(this,"Service")}},kb=xb.effect(Tr,de.gen(function*(){let e=yield*ce.Service,t=yield*De.Service,o=yield*lo.Service,n=yield*Nt.Service,r=yield*mo.Service,i=yield*Ye.Service,a=yield*dt.Service,c=yield*ho.Service,d=yield*Ib.Scope,u=yield*po.Service,l=yield*ko.Service,m=yield*we.Service,h=yield*Xe.Service,g=de.fn("SessionProcessor.create")(function*(w){let k=yield*o.track(),p={assistantMessage:w.assistantMessage,sessionID:w.sessionID,model:w.model,toolcalls:{},shouldBreak:!1,snapshot:k,blocked:!1,needsCompaction:!1,currentText:void 0,reasoningMap:{}},f=!1,S={},y={},v=s(D=>Qe.fromError(D,{providerID:w.model.providerID,aborted:f}),"parse"),P=de.fn("SessionProcessor.settleToolCall")(function*(D){let N=p.toolcalls[D]?.done;delete p.toolcalls[D],N&&(yield*uc.succeed(N,void 0).pipe(de.ignore))}),b=de.fn("SessionProcessor.readToolCall")(function*(D){let N=p.toolcalls[D];if(!N)return;let q=yield*e.getPart({partID:N.partID,messageID:N.messageID,sessionID:N.sessionID});if(!q||q.type!=="tool"){delete p.toolcalls[D];return}return{call:N,part:q}}),T=de.fn("SessionProcessor.updateToolCall")(function*(D,N){let q=yield*b(D);if(!q)return;let te=yield*e.updatePart(N(q.part));return p.toolcalls[D]={...q.call,partID:te.id,messageID:te.messageID,sessionID:te.sessionID},te}),E=de.fn("SessionProcessor.completeToolCall")(function*(D,N){let q=yield*b(D);if(!q||q.part.state.status!=="running")return Jt.recorded(p.sessionID);yield*e.updatePart({...q.part,state:{status:"completed",input:q.part.state.input,output:N.output,metadata:N.metadata,title:N.title,time:{start:q.part.state.time.start,end:Date.now()},attachments:N.attachments}}),yield*P(D),Jt.recorded(p.sessionID),op(p.sessionID,q.part.tool,N.metadata?.isError===!0,String(N.output??""))}),j=de.fn("SessionProcessor.failToolCall")(function*(D,N){let q=yield*b(D);return!q||q.part.state.status!=="running"?(Jt.recorded(p.sessionID),!1):(yield*e.updatePart({...q.part,state:{status:"error",input:q.part.state.input,error:dc(N),metadata:q.part.state.metadata,time:{start:q.part.state.time.start,end:Date.now()}}}),(N instanceof ai.RejectedError||N instanceof to.RejectedError)&&(p.blocked=p.shouldBreak),yield*P(D),Jt.recorded(p.sessionID),op(p.sessionID,q.part.tool,!0,dc(N)),!0)}),_=de.fn("SessionProcessor.finishReasoning")(function*(D){D in p.reasoningMap&&(p.reasoningMap[D].text=p.reasoningMap[D].text,p.reasoningMap[D].time={...p.reasoningMap[D].time,end:Date.now()},yield*e.updatePart(p.reasoningMap[D]),delete p.reasoningMap[D])}),W=de.fn("SessionProcessor.ensureToolCall")(function*(D){let N=yield*b(D.id);if(N){if(!D.providerExecuted||N.part.metadata?.providerExecuted)return N;let te=yield*e.updatePart({...N.part,metadata:{...N.part.metadata,providerExecuted:!0}});return p.toolcalls[D.id]={...N.call,partID:te.id,messageID:te.messageID,sessionID:te.sessionID},{call:p.toolcalls[D.id],part:te}}let q=yield*e.updatePart({id:Ce.ascending(),messageID:p.assistantMessage.id,sessionID:p.assistantMessage.sessionID,type:"tool",tool:D.name,callID:D.id,state:{status:"pending",input:{},raw:""},metadata:D.providerExecuted?{providerExecuted:!0}:void 0});return p.toolcalls[D.id]={done:yield*uc.make(),partID:q.id,messageID:q.messageID,sessionID:q.sessionID},{call:p.toolcalls[D.id],part:q}}),ie=s(D=>Sb.is(ct.FilePart)(D),"isFilePart"),M=s(D=>lt(D.result.value)&&typeof D.result.value.output=="string"?{title:typeof D.result.value.title=="string"?D.result.value.title:D.name,metadata:lt(D.result.value.metadata)?D.result.value.metadata:{},output:D.result.value.output,attachments:Array.isArray(D.result.value.attachments)?D.result.value.attachments.filter(ie):void 0}:{title:D.name,metadata:D.result.type==="json"&&lt(D.result.value)?D.result.value:{},output:typeof D.result.value=="string"?D.result.value:JSON.stringify(D.result.value)??""},"toolResultOutput"),$=de.fnUntraced(function*(D){switch(D.type){case"reasoning-start":if(D.id in p.reasoningMap)return;p.reasoningMap[D.id]={id:Ce.ascending(),messageID:p.assistantMessage.id,sessionID:p.assistantMessage.sessionID,type:"reasoning",text:"",time:{start:Date.now()},metadata:D.providerMetadata},yield*e.updatePart(p.reasoningMap[D.id]);return;case"reasoning-delta":if(!(D.id in p.reasoningMap))return;p.reasoningMap[D.id].text+=D.text,D.providerMetadata&&(p.reasoningMap[D.id].metadata=D.providerMetadata),yield*e.updatePartDelta({sessionID:p.reasoningMap[D.id].sessionID,messageID:p.reasoningMap[D.id].messageID,partID:p.reasoningMap[D.id].id,field:"text",delta:D.text});return;case"reasoning-end":D.providerMetadata&&D.id in p.reasoningMap&&(p.reasoningMap[D.id].metadata=D.providerMetadata),yield*_(D.id);return;case"tool-input-start":if(p.assistantMessage.summary)throw new Error(`Tool call not allowed while generating summary: ${D.name}`);yield*W(D);return;case"tool-input-delta":{let N=yield*W(D);if(N.part.state.status!=="pending")return;let q=(y[D.id]??N.part.state.raw??"")+D.text,te=Date.now();if(te-(S[D.id]??0)<2e3){y[D.id]=q;return}S[D.id]=te,delete y[D.id],yield*T(D.id,Fe=>Fe.state.status==="pending"?{...Fe,state:{...Fe.state,raw:q}}:Fe),yield*e.touch(p.sessionID);return}case"tool-input-end":{yield*W(D);return}case"tool-call":{if(p.assistantMessage.summary)throw new Error(`Tool call not allowed while generating summary: ${D.name}`);yield*W(D);let N=lt(D.input)?D.input:{value:D.input};yield*T(D.id,ft=>({...ft,tool:D.name,state:ft.state.status==="running"?{...ft.state,input:N}:{status:"running",input:N,time:{start:Date.now()}},metadata:ft.metadata?.providerExecuted?{...D.providerMetadata,providerExecuted:!0}:D.providerMetadata}));let te=(yield*Qe.parts(p.assistantMessage.id).pipe(de.provideService(Xe.Service,h))).slice(-np);if(te.length!==np||!te.every(ft=>ft.type==="tool"&&ft.tool===D.name&&ft.state.status!=="pending"&&JSON.stringify(ft.state.input)===JSON.stringify(N)))return;let Fe=yield*n.get(p.assistantMessage.agent);yield*i.ask({permission:"doom_loop",patterns:[D.name],sessionID:p.assistantMessage.sessionID,metadata:{tool:D.name,input:N},always:[D.name],ruleset:Fe.permission});return}case"tool-result":{if(!(yield*b(D.id))&&D.result.type==="error")return;if(D.result.type==="error"){yield*j(D.id,D.result.value);return}let q=M(D),te=yield*de.forEach(q.attachments??[],It=>It.mime.startsWith("image/")?l.normalize(It).pipe(de.catchIf(bn=>bn instanceof ko.ResizerUnavailableError,()=>de.succeed(It)),de.exit):de.succeed(pc.succeed(It))),Fe=te.filter(pc.isFailure).length,ft=te.filter(pc.isSuccess).map(It=>It.value),zt={...q,output:Fe===0?q.output:`${q.output}
953
-
954
- [${Fe} image${Fe===1?"":"s"} omitted: could not be resized below the image size limit.]`,attachments:ft.length?ft:void 0};yield*E(D.id,zt);return}case"tool-error":{yield*j(D.id,D.error??new Error(D.message));return}case"provider-error":throw new Error(D.message);case"step-start":p.snapshot||(p.snapshot=yield*o.track()),yield*e.updatePart({id:Ce.ascending(),messageID:p.assistantMessage.id,sessionID:p.sessionID,snapshot:p.snapshot,type:"step-start"});return;case"step-finish":{let N=yield*o.track();yield*de.forEach(Object.keys(p.reasoningMap),_);let q=lt(D.providerMetadata?.anthropic)?D.providerMetadata.anthropic.inputTransformations:void 0;p.model.api.npm==="@ai-sdk/anthropic"&&rt.log("thinking check",{"session.id":p.sessionID,step:p.assistantMessage.id,dropped:Array.isArray(q)?q.length:0,entries:Array.isArray(q)?q.map(Fe=>({path:Fe?.path,reason:Fe?.reason,type:Fe?.type})):[]}),Array.isArray(q)&&q.length>0&&(yield*de.logWarning("thinking blocks dropped by provider",{sessionID:p.sessionID,messageID:p.assistantMessage.id,model:p.model.id,transformations:JSON.stringify(q)}));let te=ce.getUsage({model:p.model,usage:D.usage??new Bo({}),metadata:D.providerMetadata});if(p.assistantMessage.finish=D.reason,p.assistantMessage.cost+=te.cost,p.assistantMessage.tokens=te.tokens,D.responseModelID&&(p.assistantMessage.servedModelID=D.responseModelID),yield*e.updatePart({id:Ce.ascending(),reason:D.reason,snapshot:N,messageID:p.assistantMessage.id,sessionID:p.assistantMessage.sessionID,type:"step-finish",tokens:te.tokens,cost:te.cost}),yield*e.updateMessage(p.assistantMessage),p.snapshot){let Fe=yield*o.patch(p.snapshot);Fe.files.length&&(yield*e.updatePart({id:Ce.ascending(),messageID:p.assistantMessage.id,sessionID:p.sessionID,type:"patch",hash:Fe.hash,files:Fe.files})),p.snapshot=void 0}yield*c.summarize({sessionID:p.sessionID,messageID:p.assistantMessage.parentID}).pipe(de.ignore,de.forkIn(d)),!p.assistantMessage.summary&&qi({cfg:yield*t.get(),tokens:te.tokens,model:p.model})&&(p.needsCompaction=!0);return}case"text-start":p.currentText={id:Ce.ascending(),messageID:p.assistantMessage.id,sessionID:p.assistantMessage.sessionID,type:"text",text:"",time:{start:Date.now()},metadata:D.providerMetadata},yield*e.updatePart(p.currentText);return;case"text-delta":if(!p.currentText)return;p.currentText.text+=D.text,D.providerMetadata&&(p.currentText.metadata=D.providerMetadata),yield*e.updatePartDelta({sessionID:p.currentText.sessionID,messageID:p.currentText.messageID,partID:p.currentText.id,field:"text",delta:D.text});return;case"text-end":if(!p.currentText)return;p.currentText.text=p.currentText.text,p.currentText.text=(yield*a.trigger("experimental.text.complete",{sessionID:p.sessionID,messageID:p.assistantMessage.id,partID:p.currentText.id},{text:p.currentText.text})).text;{let N=Date.now();p.currentText.time={start:p.currentText.time?.start??N,end:N}}D.providerMetadata&&(p.currentText.metadata=D.providerMetadata),yield*e.updatePart(p.currentText);{let N=yield*Qe.parts(p.assistantMessage.id).pipe(de.provideService(Xe.Service,h)),q=ep(N,p.currentText);q&&(yield*e.removePart({sessionID:q.sessionID,messageID:q.messageID,partID:q.id}))}p.currentText=void 0;return;case"finish":return}}),x=de.fn("SessionProcessor.cleanup")(function*(){if(p.snapshot){let D=yield*o.patch(p.snapshot);D.files.length&&(yield*e.updatePart({id:Ce.ascending(),messageID:p.assistantMessage.id,sessionID:p.sessionID,type:"patch",hash:D.hash,files:D.files})),p.snapshot=void 0}if(p.currentText){let D=Date.now();p.currentText.time={start:p.currentText.time?.start??D,end:D},yield*e.updatePart(p.currentText),p.currentText=void 0}for(let D of Object.values(p.reasoningMap)){let N=Date.now();yield*e.updatePart({...D,time:{start:D.time.start??N,end:N}})}p.reasoningMap={},yield*de.forEach(Object.values(p.toolcalls),D=>uc.await(D.done).pipe(de.timeout("250 millis"),de.ignore),{concurrency:"unbounded"});for(let D of Object.keys(p.toolcalls)){let N=yield*b(D);if(!N)continue;let q=N.part,te=Date.now(),Fe="metadata"in q.state&&lt(q.state.metadata)?q.state.metadata:{};yield*e.updatePart({...q,state:{...q.state,status:"error",error:"Tool execution aborted",metadata:{...Fe,interrupted:!0},time:{start:"time"in q.state?q.state.time.start:te,end:te}}})}p.toolcalls={},p.assistantMessage.time.completed=Date.now(),yield*e.updateMessage(p.assistantMessage)}),R=de.fn("SessionProcessor.halt")(function*(D){yield*de.logError("process",{"session.id":w.sessionID,messageID:w.assistantMessage.id,error:vo(D),stack:D instanceof Error?D.stack:void 0});let N=v(D);if(ct.ContextOverflowError.isInstance(N)){if((yield*t.get()).compaction?.auto===!1&&!p.assistantMessage.summary){p.assistantMessage.error=N,p.assistantMessage.finish="error",yield*m.publish(ce.Event.Error,{sessionID:p.sessionID,error:N}),yield*u.set(p.sessionID,{type:"idle"});return}p.needsCompaction=!0,yield*m.publish(ce.Event.Error,{sessionID:p.sessionID,error:N});return}p.assistantMessage.error=N,yield*m.publish(ce.Event.Error,{sessionID:p.assistantMessage.sessionID,error:p.assistantMessage.error}),yield*u.set(p.sessionID,{type:"idle"})}),A=new Set,O=s(()=>Qe.parts(p.assistantMessage.id).pipe(de.provideService(Xe.Service,h),de.map(D=>D.filter(N=>!A.has(N.id)))),"attemptParts"),F=s(D=>(D.type==="text"||D.type==="reasoning")&&!D.time?.end,"unfinished"),U=de.fn("SessionProcessor.dropAttempt")(function*(){p.currentText=void 0,p.reasoningMap={};for(let D of yield*O())D.type!=="text"&&D.type!=="reasoning"&&D.type!=="step-start"||(yield*e.removePart({sessionID:D.sessionID,messageID:D.messageID,partID:D.id}))}),pe=de.fn("SessionProcessor.keepFinished")(function*(D){if(!Dr.retryable(v(D),w.model.providerID))return yield*de.fail(D);let N=yield*O();if(!N.some(te=>te.type==="tool"&&(te.state.status==="completed"||te.state.status==="error")))return yield*de.fail(D);yield*de.logInfo("step failed after a tool finished; continuing from its finished items",{error:vo(D)}),p.currentText=void 0,p.reasoningMap={};for(let te of N)F(te)&&(yield*e.removePart({sessionID:te.sessionID,messageID:te.messageID,partID:te.id}));p.assistantMessage.finish="tool-calls"}),re=!1,Z=de.fn("SessionProcessor.endForPerson")(function*(){p.currentText=void 0,p.reasoningMap={};let D=yield*O(),N=new Set(Jt.toDrop(D));for(let q of D)N.has(q.id)&&(q.type==="tool"&&delete p.toolcalls[q.callID],yield*e.removePart({sessionID:q.sessionID,messageID:q.messageID,partID:q.id}));p.assistantMessage.finish="tool-calls",yield*de.logInfo("step ended for a person's message",{sessionID:p.sessionID,messageID:p.assistantMessage.id,dropped:N.size})}),Q=de.fn("SessionProcessor.process")(function*(D){yield*de.logInfo("process",{"session.id":w.sessionID,messageID:w.assistantMessage.id}),p.needsCompaction=!1,p.shouldBreak=(yield*t.get()).experimental?.continue_loop_on_deny!==!0;let N=0,q=w.preempt?.pipe(de.andThen(de.sync(()=>{re=!0})));return yield*de.gen(function*(){return yield*de.gen(function*(){if(re)return;N++>0&&(yield*U()),A=new Set((yield*Qe.parts(p.assistantMessage.id).pipe(de.provideService(Xe.Service,h))).map(Fe=>Fe.id)),p.currentText=void 0,p.reasoningMap={},yield*u.set(p.sessionID,{type:"busy"});let te=r.stream(D).pipe(Un.tap(Fe=>$(Fe)),Un.takeUntil(()=>p.needsCompaction));yield*q?de.raceFirst(te.pipe(Un.runDrain),q):te.pipe(Un.runDrain),re&&(yield*Z())}).pipe(de.onInterrupt(()=>de.gen(function*(){f=!0,p.assistantMessage.error||(yield*R(new DOMException("Aborted","AbortError")))})),de.catchCauseIf(te=>!tp.hasInterruptsOnly(te),te=>de.fail(tp.squash(te))),de.catch(pe),de.retry(Dr.policy({provider:w.model.providerID,parse:v,set:s(te=>u.set(p.sessionID,{type:"retry",attempt:te.attempt,message:te.message,action:te.action,next:te.next}),"set")})),de.catch(R),de.ensuring(x())),p.needsCompaction?"compact":p.blocked||p.assistantMessage.error?"stop":"continue"})});return{get message(){return p.assistantMessage},updateToolCall:T,completeToolCall:E,process:Q}});return Tr.of({create:g})})),Db=ge.make({service:Tr,layer:kb,deps:[ce.node,De.node,lo.node,Nt.node,mo.node,Ye.node,dt.node,ho.node,po.node,ko.node,we.node,Xe.node]});var Pr={};ae(Pr,{Event:()=>up,PRUNE_MINIMUM:()=>pp,PRUNE_PROTECT:()=>fp,Service:()=>jn,SessionCompaction:()=>Pr,lastStep:()=>fc,node:()=>Vb,summaryOnPrefix:()=>dp,use:()=>Wb});import{Effect as Ve,Layer as Tb,Context as Pb}from"effect";var Es={};ae(Es,{Compacted:()=>rp,Definitions:()=>Eb,SessionCompactionEvent:()=>Es});var rp=kt.define({type:"session.compacted",schema:{sessionID:No}}),Eb=kt.inventory(rp);import Rb from"path";import{readFile as Ab}from"fs/promises";var Vi="The messages before this compaction, word for word (newest last):";function sp(e){let t=[];for(let r of e)if(!(r.info.role!=="user"||r.parts.some(i=>i.type==="compaction"))){for(let i of r.parts)if(!(i.type!=="text"||!i.text?.trim())){if(!i.synthetic)t.push(i.text.trim());else if(i.text.includes(Vi)){let a=i.text.slice(i.text.indexOf(Vi)+Vi.length).split(`
955
-
956
- <<<END>>>`)[0];t.push(...a.split(`
957
-
958
- <<<NEXT>>>
959
-
960
- `).map(c=>c.trim()).filter(Boolean))}}}let o=[],n=0;for(let r=t.length-1;r>=0&&!(n+t[r].length>16e3);r--)o.unshift(t[r]),n+=t[r].length;return o.length===0?"":`${Vi}
961
-
962
- ${o.join(`
963
-
964
- <<<NEXT>>>
965
-
966
- `)}
967
-
968
- <<<END>>>`}s(sp,"wordsToCarry");import*as lp from"effect/Stream";import{Cause as ip}from"effect";async function Cb(e,t){if(!rs.ALCHEMYLAB)return"";try{let o=JSON.parse(await Ab(Rb.join(e,".alchemy_lab","action-server.json"),"utf8"));if(!o?.port)return"";let n=await fetch(`http://127.0.0.1:${o.port}/api/sessions/${encodeURIComponent(t)}/after-compaction`,{signal:AbortSignal.timeout(8e3),headers:typeof o.secret=="string"?{"x-alchemy-local":o.secret}:{}});if(!n.ok)return"";let r=await n.json();return String(r?.data?.text??"").trim()}catch{return""}}s(Cb,"recordsAfterCompaction");function fc(e){let t;for(let o of e){let n=o.info;n.role!=="assistant"||n.summary||n.aside||!n.finish||n.error||(!t||n.time.created>t.time.created||n.time.created===t.time.created&&n.id>t.id)&&(t=n)}return t}s(fc,"lastStep");function dp(e){let t=e.step;if(!t||t.providerID!==e.model.providerID||t.modelID!==e.model.id||t.tokens.cache.read+t.tokens.cache.write<=0)return!1;let o=Ke.cacheWarmForMs(e.model,e.cacheTtl==="5m"?"5m":void 0);return o===void 0?!1:e.now-t.time.created<o}s(dp,"summaryOnPrefix");var up=Es,pp=2e4,fp=4e4,ap=2e3,Mb=["skill"],Ob=2e3,Lb=15e3,_b=4e3,Ub=s(e=>e.length<=ap?e:`${e.slice(0,ap)}
969
- [truncated]`,"truncate"),jb=s(e=>{if(e.info.role==="user"){let t=e.parts.filter(n=>n.type==="text"&&!n.ignored).map(n=>n.text).filter(Boolean).join(`
970
- `),o=e.parts.flatMap(n=>n.type==="file"?[`[Attached ${n.mime}: ${n.filename??"file"}]`]:[]);return[...t?[`[User]: ${t}`]:[],...o].join(`
971
- `)}return e.parts.flatMap(t=>{if(t.type==="text")return t.text?[`[Assistant]: ${t.text}`]:[];if(t.type==="reasoning")return t.text?[`[Assistant reasoning]: ${t.text}`]:[];if(t.type!=="tool")return[];let o=`[Assistant tool call]: ${t.tool}(${JSON.stringify(t.state.input)})`;if(t.state.status==="completed"){let n=(t.state.attachments??[]).map(i=>`[Attached ${i.mime}: ${i.filename??"file"}]`),r=t.state.time.compacted?"[Old tool result content cleared]":Ub([t.state.output,...n].join(`
972
- `));return[o,`[Tool result]: ${r}`]}return t.state.status==="error"?[o,`[Tool error]: ${t.state.error}`]:[o]}).join(`
973
- `)},"serialize");function Nb(e){return e.parts.filter(o=>o.type==="text").map(o=>o.text.trim()).filter(Boolean).join(`
974
-
975
- `).trim()||void 0}s(Nb,"summaryText");function Fb(e){let t=new Map;for(let o=0;o<e.length;o++){let n=e[o];n.info.role==="user"&&n.parts.some(r=>r.type==="compaction")&&t.set(n.info.id,o)}return e.flatMap((o,n)=>{if(o.info.role!=="assistant")return[];if(!o.info.summary||!o.info.finish||o.info.error)return[];let r=t.get(o.info.parentID);return r===void 0?[]:[{userIndex:r,assistantIndex:n,summary:Nb(o)}]})}s(Fb,"completedCompactions");function cp(e){return e.cfg.compaction?.preserve_recent_tokens??Math.min(Lb,Math.max(Ob,Math.floor(Wi(e)*.25)))}s(cp,"preserveRecentBudget");function Bb(e){let t=[];for(let o=0;o<e.length;o++){let n=e[o];n.info.role==="user"&&(n.parts.some(r=>r.type==="compaction")||t.push({start:o,end:e.length,id:n.info.id}))}for(let o=0;o<t.length-1;o++)t[o].end=t[o+1].start;return t}s(Bb,"turns");function $b(e){return Ve.gen(function*(){if(!(e.budget<=0)&&!(e.turn.end-e.turn.start<=1)){for(let t=e.turn.start+1;t<e.turn.end;t++)if(!((yield*e.estimate({messages:e.messages.slice(t,e.turn.end),model:e.model}))>e.budget))return{start:t,id:e.messages[t].info.id}}})}s($b,"splitTurn");var jn=class extends Pb.Service()("@opencode/SessionCompaction"){static{s(this,"Service")}},Wb=Gt(jn),qb=Tb.effect(jn,Ve.gen(function*(){let e=yield*De.Service,t=yield*ce.Service,o=yield*Nt.Service,n=yield*dt.Service,r=yield*zo.Service,i=yield*yt.Service,a=yield*we.Service,c=yield*Me.Service,d=yield*mo.Service,u=Ve.fn("SessionCompaction.isOverflow")(function*(f){return qi({cfg:yield*e.get(),tokens:f.tokens,model:f.model,outputTokenMax:c.outputTokenMax})}),l=Ve.fn("SessionCompaction.estimate")(function*(f){let S=yield*Qe.toModelMessagesEffect(f.messages,f.model);return di.estimate(JSON.stringify(S))}),m=Ve.fn("SessionCompaction.select")(function*(f){let S=f.cfg.compaction?.tail_turns;if(S!==void 0&&S<=0)return{head:f.messages,tail_start_id:void 0};let y=cp({cfg:f.cfg,model:f.model}),v=Bb(f.messages);if(!v.length)return{head:f.messages,tail_start_id:void 0};let P=S===void 0?v:v.slice(-S),b=0,T;for(let E=P.length-1;E>=0;E--){let j=P[E],_=yield*l({messages:f.messages.slice(j.start,j.end),model:f.model});if(b+_<=y){b+=_,T={start:j.start,id:j.id};continue}let W=y-b,ie=yield*$b({messages:f.messages,turn:j,model:f.model,budget:W,estimate:l});ie?T=ie:T||(yield*Ve.logInfo("tail fallback",{budget:y,size:_,total:b}));break}return!T||T.start===0?{head:f.messages,tail_start_id:void 0}:{head:f.messages.slice(0,T.start),tail_start_id:T.id}}),h=Ve.fn("SessionCompaction.prune")(function*(f){if(!(yield*e.get()).compaction?.prune)return;yield*Ve.logInfo("pruning");let y=yield*t.messages({sessionID:f.sessionID}).pipe(Ve.catchIf(mi.isInstance,()=>Ve.succeed(void 0)));if(!y)return;let v=0,P=0,b=[],T=0;e:for(let E=y.length-1;E>=0;E--){let j=y[E];if(j.info.role==="user"&&T++,!(T<2)){if(j.info.role==="assistant"&&j.info.summary)break e;for(let _=j.parts.length-1;_>=0;_--){let W=j.parts[_];if(W.type!=="tool"||W.state.status!=="completed"||Mb.includes(W.tool))continue;if(W.state.time.compacted)break e;let ie=di.estimate(W.state.output);v+=ie,!(v<=fp)&&(P+=ie,b.push(W))}}}if(yield*Ve.logInfo("found",{pruned:P,total:v}),P>pp){for(let E of b)E.state.status==="completed"&&(E.state.time.compacted=Date.now(),yield*t.updatePart(E));yield*Ve.logInfo("pruned",{count:b.length})}}),g=Ve.fn("SessionCompaction.serverSummary")(function*(f){let S=s((Z,Q)=>Ve.sync(()=>(rt.log("fallback to today's compaction",{"session.id":f.sessionID,reason:Z,...Q}),{fallback:Z})),"fallback"),y=f.step,v=yield*f.prefix(y);if(!v)return yield*S("the session's prefix could not be rebuilt");let P=yield*Ve.forEach(f.history,Z=>l({messages:[Z],model:f.model})),b=y.tokens.input+y.tokens.cache.read+y.tokens.cache.write+y.tokens.output,T=P.reduce((Z,Q)=>Z+Q,0),E=Math.floor(Wi({cfg:f.cfg,model:f.model,outputTokenMax:c.outputTokenMax})*.75)-Math.max(0,b-T)-_b,j=Math.min(cp({cfg:f.cfg,model:f.model}),Math.max(0,E)),_=rt.cut(f.history,P,j),W=structuredClone(_?f.history.slice(0,_.index):f.history);yield*n.trigger("experimental.chat.messages.transform",{},{messages:W});let ie=yield*Qe.toModelMessagesEffect(W,f.model),M=crypto.randomUUID();rt.log("compacting",{"session.id":f.sessionID,head:W.length,kept:_?f.history.length-_.index:0,keptFrom:_?.id,keptTokens:_?.tokens??0,budget:j,room:E,context:b});let $,x=yield*d.stream({user:v.user,agent:v.agent,permission:v.permission,sessionID:f.sessionID,parentSessionID:v.parentSessionID,system:v.system,tools:v.tools,messages:ie,model:f.model,cachePoints:"all",headers:{[rt.HEADER]:M}}).pipe(lp.runForEach(Z=>Ve.sync(()=>{Z.type==="step-finish"&&($={usage:Z.usage,providerMetadata:Z.providerMetadata})})),Ve.as("ok"),Ve.catchCause(Z=>ip.hasInterruptsOnly(Z)?Ve.interrupt:Ve.succeed(String(ip.squash(Z)).slice(0,500)))),R=rt.take(M);if(x!=="ok")return yield*S("the compaction request failed",{error:x,status:R?.status,body:R?.error});if(!R?.block)return yield*S("the reply carried no compaction block",{status:R?.status,stop:R?.stopReason,body:R?.error});let A=(R.usage?.iterations??[]).find(Z=>Z?.type==="compaction"),O=A?new Bo({inputTokens:(A.input_tokens??0)+(A.cache_read_input_tokens??0)+(A.cache_creation_input_tokens??0),outputTokens:A.output_tokens??0,totalTokens:(A.input_tokens??0)+(A.cache_read_input_tokens??0)+(A.cache_creation_input_tokens??0)+(A.output_tokens??0),cacheReadInputTokens:A.cache_read_input_tokens??0,cacheWriteInputTokens:A.cache_creation_input_tokens??0}):$?.usage??new Bo({}),F=ce.getUsage({model:f.model,usage:O,metadata:$?.providerMetadata}),U=yield*B.context,pe=Date.now(),re={id:it.ascending(),role:"assistant",parentID:f.parentID,sessionID:f.sessionID,mode:"compaction",agent:"compaction",variant:f.userMessage.model.variant,summary:!0,path:{cwd:U.directory,root:U.worktree},cost:F.cost,tokens:F.tokens,modelID:f.model.id,providerID:f.model.providerID,finish:"stop",time:{created:pe,completed:pe}};return yield*t.updateMessage(re),rt.remember(R.block),yield*t.updatePart({id:Ce.ascending(),messageID:re.id,sessionID:f.sessionID,type:"text",text:R.block.content,time:{start:pe,end:pe},metadata:{[rt.METADATA_KEY]:{block:R.block,system:[]}}}),rt.log("block stored",{"session.id":f.sessionID,message:re.id,chars:R.block.content.length,signature:typeof R.block.signature=="string"?R.block.signature.length:0,keptFrom:_?.id,usage:R.usage,inputTransformations:R.inputTransformations??[]}),{message:re,tailStartID:_?.id}}),w=s(f=>Ve.sync(()=>{let S=fc(f.history),y=f.tailStartID?f.history.findIndex(T=>T.info.id===f.tailStartID):-1,v=y<0?[]:f.history.slice(y).filter(T=>T.info.role==="assistant"&&!T.info.summary&&!T.info.aside),P=v.filter(T=>T.parts.some(E=>E.type==="reasoning"&&typeof E.metadata?.anthropic?.signature=="string")),b=f.message.tokens;rt.log("compaction done",{"session.id":f.sessionID,agent:f.agent,model:`${f.model.providerID}/${f.model.id}`,path:f.path,...f.then?{then:f.then}:{},result:f.result,contextBefore:S?S.tokens.input+S.tokens.cache.read+S.tokens.cache.write+S.tokens.output:0,usage:{input:b.input,cacheRead:b.cache.read,cacheWrite:b.cache.write,output:b.output+b.reasoning},cost:f.message.cost,keptSteps:v.length,keptWithThinking:P.length})}),"logDone"),k=Ve.fn("SessionCompaction.process")(function*(f){let S=f.messages.findLast(Q=>Q.info.id===f.parentID);if(!S||S.info.role!=="user")throw new Error(`Compaction parent must be a user message: ${f.parentID}`);let y=S.info,v=S.parts.find(Q=>Q.type==="compaction"),P=f.messages,b;if(f.overflow){let Q=f.messages.findIndex(N=>N.info.id===f.parentID);for(let N=Q-1;N>=0;N--){let q=f.messages[N];if(q.info.role==="user"&&!q.parts.some(te=>te.type==="compaction")){b={info:q.info,parts:q.parts},P=f.messages.slice(0,N);break}}b&&P.some(N=>N.info.role==="user"&&!N.parts.some(q=>q.type==="compaction"))||(b=void 0,P=f.messages)}let T=yield*o.get("compaction"),E=T.model?yield*i.getModel(T.model.providerID,T.model.modelID).pipe(Ve.orDie):yield*i.getModel(y.model.providerID,y.model.modelID).pipe(Ve.orDie),j=yield*e.get(),_=v&&P.at(-1)?.info.id===f.parentID?P.slice(0,-1):P,W=Fb(_),ie=new Set(W.flatMap(Q=>[Q.userIndex,Q.assistantIndex])),M=W.at(-1)?.summary,$=yield*B.context,x=f.prefix&&!f.overflow&&!T.model?fc(_):void 0,R=x?yield*o.get(x.agent):void 0,A=!!x&&!!R&&dp({step:x,model:E,cacheTtl:R.options?.cacheTtl,now:Date.now()}),O=A&&x&&f.prefix&&rt.on()&&rt.supports(E)?yield*g({sessionID:f.sessionID,parentID:f.parentID,history:_,model:E,userMessage:y,step:x,prefix:f.prefix,cfg:j}):void 0,F=O&&"message"in O?O:void 0;F&&v&&v.tail_start_id!==F.tailStartID&&(yield*t.updatePart({...v,tail_start_id:F.tailStartID}));let U=!F&&A&&x&&f.prefix?yield*f.prefix(x):void 0,pe=Ve.gen(function*(){let Q=yield*n.trigger("experimental.session.compacting",{sessionID:f.sessionID},{context:[],prompt:void 0}),D=U?void 0:yield*m({messages:_.filter((It,bn)=>!ie.has(bn)),cfg:j,model:E}),N=structuredClone(D?D.head:_);yield*n.trigger("experimental.chat.messages.transform",{},{messages:N});let q=U?"":N.map(jb).filter(Boolean).join(`
976
-
977
- `),te=Q.prompt??[U?Vl({previousSummary:W.length>0}):ql({previousSummary:M,context:[q]}),...Q.context].filter(Boolean).join(`
978
-
979
- `),Fe={id:it.ascending(),role:"assistant",parentID:f.parentID,sessionID:f.sessionID,mode:"compaction",agent:"compaction",variant:y.model.variant,summary:!0,path:{cwd:$.directory,root:$.worktree},cost:0,tokens:{output:0,input:0,reasoning:0,cache:{read:0,write:0}},modelID:E.id,providerID:E.providerID,time:{created:Date.now()}};yield*t.updateMessage(Fe);let ft=yield*r.create({assistantMessage:Fe,sessionID:f.sessionID,model:E});yield*Ve.logInfo(U?"compacting on the session's own prefix":"compacting a serialized history",{"session.id":f.sessionID,step:x?.id,overflow:!!f.overflow,ownModel:!!T.model});let zt=yield*ft.process(U?{user:U.user,agent:U.agent,permission:U.permission,sessionID:f.sessionID,parentSessionID:U.parentSessionID,tools:U.tools,system:U.system,messages:[...yield*Qe.toModelMessagesEffect(N,E),{role:"user",content:[{type:"text",text:te}]}],model:E,cachePoints:"history"}:{user:y,agent:T,sessionID:f.sessionID,tools:{},system:[],messages:[{role:"user",content:[{type:"text",text:[te,...Q.prompt?["The following is the conversation history:",q]:[]].filter(Boolean).join(`
980
-
981
- `)}]}],model:E,cachePoints:"none"});return zt==="compact"?(ft.message.error=new ct.ContextOverflowError({message:b?"Conversation history too large to compact - exceeds model context limit":"Session too large to compact - context exceeds model limit even after stripping media"}).toObject(),ft.message.finish="error",yield*t.updateMessage(ft.message),{result:"stop",message:ft.message,tailStartID:void 0,onPrefix:!!U}):(v&&D?.tail_start_id&&v.tail_start_id!==D.tail_start_id&&(yield*t.updatePart({...v,tail_start_id:D.tail_start_id})),{result:zt,message:ft.message,tailStartID:D?.tail_start_id,onPrefix:!!U})}),re=F?{result:"continue",message:F.message,tailStartID:F.tailStartID,onPrefix:!1}:yield*pe;if(yield*w({sessionID:f.sessionID,agent:x?.agent??y.agent,model:E,path:F?"anthropic":O&&"fallback"in O?`fallback:${O.fallback}`:re.onPrefix?"prefix":"condensed",then:O&&"fallback"in O?re.onPrefix?"prefix":"condensed":void 0,history:_,message:re.message,tailStartID:re.tailStartID,result:re.result}),re.result==="stop"&&re.message.error)return"stop";let Z=re.result;if(Z==="continue"&&f.auto){if(b){let Q=b.info,D=yield*t.updateMessage({id:it.ascending(),role:"user",sessionID:f.sessionID,time:{created:Date.now()},agent:Q.agent,model:Q.model,format:Q.format,tools:Q.tools,system:Q.system});for(let N of b.parts){if(N.type==="compaction")continue;let q=N.type==="file"&&Qe.isMedia(N.mime)?{type:"text",text:`[Attached ${N.mime}: ${N.filename??"file"}]`}:N;yield*t.updatePart({...q,id:Ce.ascending(),messageID:D.id,sessionID:f.sessionID})}}if(!b){let Q=yield*i.getProvider(y.model.providerID);if((yield*n.trigger("experimental.compaction.autocontinue",{sessionID:f.sessionID,agent:y.agent,model:yield*i.getModel(y.model.providerID,y.model.modelID).pipe(Ve.orDie),provider:{source:Q.source,info:Q,options:Q.options},message:y,overflow:f.overflow===!0},{enabled:!0})).enabled){let D=yield*t.updateMessage({id:it.ascending(),role:"user",sessionID:f.sessionID,time:{created:Date.now()},agent:y.agent,model:y.model}),N=yield*Ve.promise(()=>Cb($.directory,f.sessionID)),q=sp(f.messages),te=(f.overflow?`The previous request exceeded the provider's size limit due to large media attachments. The conversation was compacted and media files were removed from context. If the user was asking about attached images or files, explain that the attachments were too large to process and suggest they try again with smaller or fewer files.
982
-
983
- `:"")+"This session was compacted automatically to free context: the summary above covers the earlier part of it, and nothing else has happened since. "+(q||N?`Below are the messages it received and the records as they stand now.
984
-
985
- `:`
986
-
987
- `)+(q?`${q}
988
-
989
- `:"")+(N?`${N}
990
-
991
- `:"")+"Resume directly with the next step: do not acknowledge the summary, do not recap, and do not stop to report. Pick up the last task as if the break never happened.";yield*t.updatePart({id:Ce.ascending(),messageID:D.id,sessionID:f.sessionID,type:"text",metadata:{compaction_continue:!0},synthetic:!0,text:te,time:{start:Date.now(),end:Date.now()}})}}}return re.message.error?"stop":(Z==="continue"&&(yield*a.publish(up.Compacted,{sessionID:f.sessionID})),Z)}),p=Ve.fn("SessionCompaction.create")(function*(f){let S=yield*t.updateMessage({id:it.ascending(),role:"user",model:f.model,sessionID:f.sessionID,agent:f.agent,time:{created:Date.now()}});yield*t.updatePart({id:Ce.ascending(),messageID:S.id,sessionID:S.sessionID,type:"compaction",auto:f.auto,overflow:f.overflow})});return jn.of({isOverflow:u,prune:h,process:k,create:p})})),Vb=ge.make({service:jn,layer:qb,deps:[De.node,ce.node,Nt.node,dt.node,zo.node,yt.node,we.node,Me.node,mo.node]});var Ar={};ae(Ar,{RevertInput:()=>Hb,Service:()=>Rr,SessionRevert:()=>Ar,node:()=>Kb});import{Effect as go,Layer as zb,Context as Gb,Schema as mp}from"effect";var Hb=mp.Struct({sessionID:Et,messageID:it,partID:mp.optional(Ce)}),Rr=class extends Gb.Service()("@opencode/SessionRevert"){static{s(this,"Service")}},Yb=zb.effect(Rr,go.gen(function*(){let e=yield*ce.Service,t=yield*lo.Service,o=yield*La.Service,n=yield*we.Service,r=yield*ho.Service,i=yield*qo.Service,a=go.fn("SessionRevert.revert")(function*(u){yield*i.assertNotBusy(u.sessionID);let l=yield*e.messages({sessionID:u.sessionID}).pipe(go.orDie),m,h=yield*e.get(u.sessionID).pipe(go.orDie),g,w=[];for(let S of l){S.info.role==="user"&&(m=S.info);let y=[];for(let v of S.parts){if(g){v.type==="patch"&&w.push(v);continue}if(!g){if(S.info.id===u.messageID&&!u.partID||v.id===u.partID){let P=y.some(b=>["text","tool"].includes(b.type))?u.partID:void 0;g={messageID:!P&&m?m.id:S.info.id,partID:P}}y.push(v)}}}if(!g)return h;g.snapshot=h.revert?.snapshot??(yield*t.track()),h.revert?.snapshot&&(yield*t.restore(h.revert.snapshot)),yield*t.revert(w),g.snapshot&&(g.diff=yield*t.diff(g.snapshot));let k=l.findIndex(S=>S.info.id===g.messageID),p=k<0?[]:l.slice(k),f=yield*r.computeDiff({messages:p});return yield*o.write(["session_diff",u.sessionID],f).pipe(go.ignore),yield*n.publish(ce.Event.Diff,{sessionID:u.sessionID,diff:f}),yield*e.setRevert({sessionID:u.sessionID,revert:g,summary:{additions:f.reduce((S,y)=>S+y.additions,0),deletions:f.reduce((S,y)=>S+y.deletions,0),files:f.length}}),yield*e.get(u.sessionID).pipe(go.orDie)}),c=go.fn("SessionRevert.unrevert")(function*(u){yield*go.logInfo("unreverting",{sessionID:u.sessionID}),yield*i.assertNotBusy(u.sessionID);let l=yield*e.get(u.sessionID).pipe(go.orDie);return l.revert?(l.revert.snapshot&&(yield*t.restore(l.revert.snapshot)),yield*e.clearRevert(u.sessionID),yield*e.get(u.sessionID).pipe(go.orDie)):l}),d=go.fn("SessionRevert.cleanup")(function*(u){if(!u.revert)return;let l=u.id,m=yield*e.messages({sessionID:l}).pipe(go.orDie),h=u.revert.messageID,g=m.findIndex(p=>p.info.id===h),w=g<0?void 0:m[g],k=g<0?[]:m.slice(g+(u.revert.partID?1:0));for(let p of k)yield*e.removeMessage({sessionID:l,messageID:p.info.id});if(u.revert.partID&&w){let p=u.revert.partID,f=w.parts.findIndex(S=>S.id===p);if(f>=0){let S=w.parts.slice(f);w.parts=w.parts.slice(0,f);for(let y of S)yield*e.removePart({sessionID:l,messageID:w.info.id,partID:y.id})}}yield*e.clearRevert(l)});return Rr.of({revert:a,unrevert:c,cleanup:d})})),Kb=ge.make({service:Rr,layer:Yb,deps:[ce.node,lo.node,La.node,we.node,ho.node,qo.node]});var Lo={};ae(Lo,{Instruction:()=>Lo,Service:()=>Cr,loaded:()=>ex,node:()=>tx});import Rt from"path";import{Effect as Je,Layer as Jb,Context as Xb}from"effect";import{HttpClient as hp,HttpClientRequest as Qb}from"effect/unstable/http";function gp(e){let t=new Set;for(let o of e)for(let n of o.parts)if(n.type==="tool"&&n.tool==="read"&&n.state.status==="completed"){if(n.state.time.compacted)continue;let r=n.state.metadata?.loaded;if(!r||!Array.isArray(r))continue;for(let i of r)typeof i=="string"&&t.add(i)}return t}s(gp,"extract");var Cr=class extends Xb.Service()("@opencode/Instruction"){static{s(this,"Service")}},Zb=Jb.effect(Cr,Je.gen(function*(){let e=yield*De.Service,t=yield*Se.Service,o=yield*me.Service,n=yield*Me.Service,r=hp.filterStatusOk(ui(yield*hp.HttpClient)),i=[Rt.join(o.config,"AGENTS.md"),...n.disableClaudeCodePrompt?[]:[Rt.join(o.home,".claude","CLAUDE.md")]],a=["AGENTS.md",...n.disableClaudeCodePrompt?[]:["CLAUDE.md"],"CONTEXT.md"],c=yield*B.make(Je.fn("Instruction.state")(()=>Je.succeed({claims:new Map}))),d=Je.fnUntraced(function*(p){let f=yield*B.context;return rs.OPENCODE_DISABLE_PROJECT_CONFIG?yield*t.globUp(p,o.config,o.config).pipe(Je.catch(()=>Je.succeed([]))):yield*t.globUp(p,f.directory,f.worktree).pipe(Je.catch(()=>Je.succeed([])))}),u=Je.fnUntraced(function*(p){return yield*t.readFileString(p).pipe(Je.catch(()=>Je.succeed("")))}),l=Je.fnUntraced(function*(p){let f=yield*r.execute(Qb.get(p)).pipe(Je.timeout(5e3),Je.catch(()=>Je.succeed(null)));if(!f)return"";let S=yield*f.arrayBuffer.pipe(Je.catch(()=>Je.succeed(new ArrayBuffer(0))));return new TextDecoder().decode(S)}),m=Je.fn("Instruction.clear")(function*(p){(yield*B.get(c)).claims.delete(p)}),h=Je.fn("Instruction.systemPaths")(function*(){let p=yield*e.get(),f=yield*B.context,S=new Set;for(let y of i)if(yield*t.existsSafe(y)){S.add(Rt.resolve(y));break}if(!rs.OPENCODE_DISABLE_PROJECT_CONFIG)for(let y of a){let v=yield*t.findUp(y,f.directory,f.worktree).pipe(Je.catch(()=>Je.succeed([])));if(v.length>0){v.forEach(P=>S.add(Rt.resolve(P)));break}}if(p.instructions)for(let y of p.instructions){if(y.startsWith("https://")||y.startsWith("http://"))continue;let v=y.startsWith("~/")?Rt.join(o.home,y.slice(2)):y;(yield*(Rt.isAbsolute(v)?t.glob(Rt.basename(v),{cwd:Rt.dirname(v),absolute:!0,include:"file"}):d(v)).pipe(Je.catch(()=>Je.succeed([])))).forEach(b=>S.add(Rt.resolve(b)))}return S}),g=Je.fn("Instruction.system")(function*(){let p=yield*e.get(),f=yield*h(),S=(p.instructions??[]).filter(P=>P.startsWith("https://")||P.startsWith("http://")),y=yield*Je.forEach(Array.from(f),u,{concurrency:8}),v=yield*Je.forEach(S,l,{concurrency:4});return[...Array.from(f).flatMap((P,b)=>y[b]?[`Instructions from: ${P}
992
- ${y[b]}`]:[]),...S.flatMap((P,b)=>v[b]?[`Instructions from: ${P}
993
- ${v[b]}`]:[])]}),w=Je.fn("Instruction.find")(function*(p){for(let f of a){let S=Rt.resolve(Rt.join(p,f));if(yield*t.existsSafe(S))return S}}),k=Je.fn("Instruction.resolve")(function*(p,f,S){let y=yield*h(),v=gp(p),P=[],b=yield*B.get(c),T=Rt.resolve(yield*B.directory),E=Rt.resolve(f),j=Rt.dirname(E);for(;j.startsWith(T)&&j!==T;){let _=yield*w(j);if(!_||_===E||y.has(_)||v.has(_)){j=Rt.dirname(j);continue}let W=b.claims.get(S);if(W||(W=new Set,b.claims.set(S,W)),W.has(_)){j=Rt.dirname(j);continue}W.add(_);let ie=yield*u(_);ie&&P.push({filepath:_,content:`Instructions from: ${_}
994
- ${ie}`}),j=Rt.dirname(j)}return P});return Cr.of({clear:m,systemPaths:h,system:g,find:w,resolve:k})}));function ex(e){return gp(e)}s(ex,"loaded");var tx=ge.make({service:Cr,layer:Zb,deps:[De.node,Se.node,me.node,Me.node,Co]});var ut={};ae(ut,{Diagnostic:()=>Rs,DocumentSymbol:()=>fv,Event:()=>Rp,LSP:()=>ut,Range:()=>Hi,Service:()=>Ur,Status:()=>mv,Symbol:()=>pv,node:()=>wv});import Ts from"path";import{pathToFileURL as pn,fileURLToPath as ox}from"url";import{createMessageConnection as nx,StreamMessageReader as rx,StreamMessageWriter as sx}from"vscode-jsonrpc/node.js";var yp={".abap":"abap",".bat":"bat",".bib":"bibtex",".bibtex":"bibtex",".clj":"clojure",".cljs":"clojure",".cljc":"clojure",".edn":"clojure",".coffee":"coffeescript",".c":"c",".cpp":"cpp",".cxx":"cpp",".cc":"cpp",".c++":"cpp",".cs":"csharp",".csx":"csharp",".css":"css",".d":"d",".pas":"pascal",".pascal":"pascal",".diff":"diff",".patch":"diff",".dart":"dart",".dockerfile":"dockerfile",".ex":"elixir",".exs":"elixir",".erl":"erlang",".ets":"typescript",".hrl":"erlang",".fs":"fsharp",".fsi":"fsharp",".fsx":"fsharp",".fsscript":"fsharp",".gitcommit":"git-commit",".gitrebase":"git-rebase",".go":"go",".groovy":"groovy",".gleam":"gleam",".hbs":"handlebars",".handlebars":"handlebars",".hs":"haskell",".lhs":"haskell",".html":"html",".htm":"html",".ini":"ini",".java":"java",".jl":"julia",".js":"javascript",".kt":"kotlin",".kts":"kotlin",".jsx":"javascriptreact",".json":"json",".tex":"latex",".latex":"latex",".less":"less",".lua":"lua",".makefile":"makefile",makefile:"makefile",".md":"markdown",".markdown":"markdown",".m":"objective-c",".mm":"objective-cpp",".pl":"perl",".pm":"perl",".pm6":"perl6",".php":"php",".ps1":"powershell",".psm1":"powershell",".pug":"jade",".jade":"jade",".py":"python",".r":"r",".cshtml":"razor",".razor":"razor",".rb":"ruby",".rake":"ruby",".gemspec":"ruby",".ru":"ruby",".erb":"erb",".html.erb":"erb",".js.erb":"erb",".css.erb":"erb",".json.erb":"erb",".rs":"rust",".scss":"scss",".sass":"sass",".scala":"scala",".shader":"shaderlab",".sh":"shellscript",".bash":"shellscript",".zsh":"shellscript",".ksh":"shellscript",".sql":"sql",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescriptreact",".mts":"typescript",".cts":"typescript",".mtsx":"typescriptreact",".ctsx":"typescriptreact",".xml":"xml",".xsl":"xsl",".yaml":"yaml",".yml":"yaml",".mjs":"javascript",".cjs":"javascript",".vue":"vue",".zig":"zig",".zon":"zig",".astro":"astro",".ml":"ocaml",".mli":"ocaml",".tf":"terraform",".tfvars":"terraform-vars",".hcl":"hcl",".nix":"nix",".typ":"typst",".typc":"typst"};import{Schema as zi}from"effect";var ix=150,mc=5e3,hc=1e4,wp=3e3,ax=45e3,cx=1,lx=2,dx=2,yc=class extends zi.TaggedErrorClass()("LSPInitializeError",{serverID:zi.String,cause:zi.optional(zi.Defect())}){static{s(this,"InitializeError")}};function gc(e){if(e.startsWith("file://"))return le.normalizePath(ox(e))}s(gc,"getFilePath");function ux(e){if(!e)return;let t=e.textDocumentSync;return typeof t=="number"?t:t?.change}s(ux,"getSyncKind");function px(e){let t=e.split(/\r\n|\r|\n/);return{line:t.length-1,character:t.at(-1)?.length??0}}s(px,"endPosition");function bp(e){let t=new Set;return e.filter(o=>{let n=JSON.stringify({code:o.code,severity:o.severity,message:o.message,source:o.source,range:o.range});return t.has(n)?!1:(t.add(n),!0)})}s(bp,"dedupeDiagnostics");function fx(e,t){return t?t.split(".").reduce((n,r)=>{if(!(!n||typeof n!="object"||!(r in n)))return n[r]},e)??null:e??null}s(fx,"configurationValue");function mx(e){return e==="typescript"}s(mx,"shouldSeedDiagnosticsOnFirstPush");async function xp(e){let t=e.instance,o=nx(new rx(e.server.process.stdout),new sx(e.server.process.stdin));e.server.process.stderr?.resume();let n=new Map,r=new Map,i=new Map,a=new Map,c=new Set,d=new Set,u=s(x=>bp([...n.get(x)??[],...r.get(x)??[]]),"mergedDiagnostics"),l=s((x,R)=>{n.set(x,R);for(let A of d)A({path:x,serverID:e.serverID})},"updatePushDiagnostics"),m=s((x,R)=>{r.set(x,R)},"updatePullDiagnostics"),h=s(()=>{for(let x of[...c])x()},"emitRegistrationChange");o.onNotification("textDocument/publishDiagnostics",x=>{let R=gc(x.uri);if(R){if(i.set(R,{at:Date.now(),version:typeof x.version=="number"?x.version:void 0}),mx(e.serverID)&&!n.has(R)){n.set(R,x.diagnostics);return}l(R,x.diagnostics)}}),o.onRequest("window/workDoneProgress/create",x=>null),o.onRequest("workspace/configuration",async x=>(x.items??[]).map(A=>fx(e.server.initialization,A.section))),o.onRequest("client/registerCapability",async x=>{let R=x.registrations??[],A=!1;for(let O of R)O.method==="textDocument/diagnostic"&&(a.set(O.id,O),A=!0);A&&h()}),o.onRequest("client/unregisterCapability",async x=>{let R=x.unregisterations??[],A=!1;for(let O of R)O.method==="textDocument/diagnostic"&&(a.delete(O.id),A=!0);A&&h()}),o.onRequest("workspace/workspaceFolders",async()=>[{name:"workspace",uri:pn(e.root).href}]),o.onRequest("workspace/diagnostic/refresh",async()=>null),o.listen();let g=await hi(o.sendRequest("initialize",{rootUri:pn(e.root).href,processId:e.server.process.pid,workspaceFolders:[{name:"workspace",uri:pn(e.root).href}],initializationOptions:{...e.server.initialization},capabilities:{window:{workDoneProgress:!0},workspace:{configuration:!0,didChangeWatchedFiles:{dynamicRegistration:!0},diagnostics:{refreshSupport:!1}},textDocument:{synchronization:{didOpen:!0,didChange:!0},diagnostic:{dynamicRegistration:!0,relatedDocumentSupport:!0},publishDiagnostics:{versionSupport:!1}}}}),ax).catch(x=>{throw new yc({serverID:e.serverID,cause:x})}),w=ux(g.capabilities),k=!!g.capabilities?.diagnosticProvider;await o.sendNotification("initialized",{}),e.server.initialization&&await o.sendNotification("workspace/didChangeConfiguration",{settings:e.server.initialization});let p={},f=s((x,R)=>{let A=R.some(U=>U.handled),O=R.some(U=>U.matched);if(!A)return{handled:!1,matched:!1};let F=new Map;for(let U of R)for(let[pe,re]of U.byFile.entries()){let Z=F.get(pe)??[];F.set(pe,Z.concat(re))}O&&!F.has(x)&&F.set(x,[]);for(let[U,pe]of F.entries())m(U,bp(pe));return{handled:A,matched:O}},"mergeResults");async function S(x,R){let A=await hi(o.sendRequest("textDocument/diagnostic",{...R?{identifier:R}:{},textDocument:{uri:pn(x).href}}),wp).catch(()=>null);if(!A)return{handled:!1,matched:!1,byFile:new Map};let O=new Map,F=s((re,Z)=>{let Q=O.get(re)??[];O.set(re,Q.concat(Z))},"push"),U=!1,pe=!1;Array.isArray(A.items)&&(F(x,A.items),U=!0,pe=!0);for(let[re,Z]of Object.entries(A.relatedDocuments??{})){let Q=gc(re);!Q||!Array.isArray(Z.items)||(F(Q,Z.items),U=!0,pe=pe||Q===x)}return{handled:U,matched:pe,byFile:O}}s(S,"requestDiagnosticReport");async function y(x,R){let A=await hi(o.sendRequest("workspace/diagnostic",{...R?{identifier:R}:{},previousResultIds:[]}),wp).catch(()=>null);if(!A)return{handled:!1,matched:!1,byFile:new Map};let O=new Map,F=!1;for(let U of A.items??[]){let pe=U.uri?gc(U.uri):void 0;if(!pe||!Array.isArray(U.items))continue;let re=O.get(pe)??[];O.set(pe,re.concat(U.items)),F=F||pe===x}return{handled:!0,matched:F,byFile:O}}s(y,"requestWorkspaceDiagnosticReport");function v(){let x=[...a.values()].filter(R=>R.registerOptions?.workspaceDiagnostics!==!0);return{documentIdentifiers:[...new Set(x.flatMap(R=>R.registerOptions?.identifier??[]))],supported:k||x.length>0}}s(v,"documentPullState");function P(){let x=[...a.values()].filter(R=>R.registerOptions?.workspaceDiagnostics===!0);return{workspaceIdentifiers:[...new Set(x.flatMap(R=>R.registerOptions?.identifier??[]))],supported:x.length>0}}s(P,"workspacePullState");let b=s((x,R)=>R.some(A=>(A.byFile.get(x)?.length??0)>0),"hasCurrentFileDiagnostics");async function T(x,R,A){if(!R.length)return{handled:!1,matched:!1};let O=[];return new Promise(F=>{let U=R.length,pe=!1,re=s((Z,Q=!1)=>{pe||!Q&&!A(O)||(pe=!0,F(Z))},"finish");for(let Z of R)Z.then(Q=>{O.push(Q),U-=1;let D=f(x,O);re(D),U===0&&re(D,!0)})})}s(T,"requestDiagnostics");async function E(x){let R=v();return R.supported?T(x,[S(x),...R.documentIdentifiers.map(A=>S(x,A))],A=>b(x,A)):{handled:!1,matched:!1}}s(E,"requestDocumentDiagnostics");async function j(x){let R=v(),A=P();return!R.supported&&!A.supported?{handled:!1,matched:!1}:f(x,await Promise.all([...R.supported?[S(x)]:[],...R.documentIdentifiers.map(O=>S(x,O)),...A.supported?[y(x)]:[],...A.workspaceIdentifiers.map(O=>y(x,O))]))}s(j,"requestFullDiagnostics");function _(x){return x<=0?Promise.resolve(!1):new Promise(R=>{let A=!1,O,F=s(pe=>{A||(A=!0,O&&clearTimeout(O),c.delete(U),R(pe))},"finish"),U=s(()=>F(!0),"listener");c.add(U),O=setTimeout(()=>F(!1),x)})}s(_,"waitForRegistrationChange");function W(x){return x.timeout<=0?Promise.resolve(!1):new Promise(R=>{let A=!1,O,F,U,pe=s(Q=>{A||(A=!0,O&&clearTimeout(O),F&&clearTimeout(F),U?.(),R(Q))},"finish"),re=s(()=>{let Q=i.get(x.path);Q&&(typeof Q.version=="number"&&Q.version!==x.version||Q.at<x.after&&Q.version!==x.version||(O&&clearTimeout(O),O=setTimeout(()=>pe(!0),Math.max(0,ix-(Date.now()-Q.at)))))},"schedule");F=setTimeout(()=>pe(!1),x.timeout);let Z=s(Q=>{Q.path!==x.path||Q.serverID!==e.serverID||re()},"listener");d.add(Z),U=s(()=>d.delete(Z),"unsub"),re()})}s(W,"waitForFreshPush");async function ie(x){let R=x.after??Date.now(),A=W({path:x.path,version:x.version,after:R,timeout:mc});for(;Date.now()-R<mc;){if((await E(x.path)).matched)return;let F=mc-(Date.now()-R);if(F<=0||await Promise.race([A.then(pe=>pe?"push":"timeout"),_(F).then(pe=>pe?"registration":"timeout")])!=="registration")return}}s(ie,"waitForDocumentDiagnostics");async function M(x){let R=x.after??Date.now(),A=W({path:x.path,version:x.version,after:R,timeout:hc});for(;Date.now()-R<hc;){let O=await j(x.path);if(O.handled||O.matched)return;let F=hc-(Date.now()-R);if(F<=0||await Promise.race([A.then(pe=>pe?"push":"timeout"),_(F).then(pe=>pe?"registration":"timeout")])!=="registration")return}}return s(M,"waitForFullDiagnostics"),{root:e.root,get serverID(){return e.serverID},get connection(){return o},notify:{async open(x){x.path=le.normalizePath(Ts.isAbsolute(x.path)?x.path:Ts.resolve(e.directory,x.path));let R=await le.readText(x.path),A=Ts.extname(x.path),O=yp[A]??"plaintext",F=p[x.path];if(F!==void 0){await o.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:pn(x.path).href,type:lx}]});let U=F.version+1;return p[x.path]={version:U,text:R},await o.sendNotification("textDocument/didChange",{textDocument:{uri:pn(x.path).href,version:U},contentChanges:w===dx?[{range:{start:{line:0,character:0},end:px(F.text)},text:R}]:[{text:R}]}),U}return await o.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:pn(x.path).href,type:cx}]}),n.delete(x.path),r.delete(x.path),await o.sendNotification("textDocument/didOpen",{textDocument:{uri:pn(x.path).href,languageId:O,version:0,text:R}}),p[x.path]={version:0,text:R},0}},get diagnostics(){let x=new Map;for(let R of new Set([...n.keys(),...r.keys()]))x.set(R,u(R));return x},async waitForDiagnostics(x){let R=le.normalizePath(Ts.isAbsolute(x.path)?x.path:Ts.resolve(e.directory,x.path));if(x.mode==="document"){await ie({path:R,version:x.version,after:x.after});return}await M({path:R,version:x.version,after:x.after})},async shutdown(){o.end(),o.dispose(),await st.stop(e.server.process)}}}s(xp,"create");import xc from"path";import{pathToFileURL as _r,fileURLToPath as lv}from"url";var bc={};ae(bc,{Astro:()=>$x,BashLS:()=>Xx,Biome:()=>Dx,CSharp:()=>Mx,Clangd:()=>Fx,Clojure:()=>ov,Dart:()=>Kx,Deno:()=>xx,DockerfileLS:()=>ev,ESLint:()=>Sx,ElixirLS:()=>Ax,FSharp:()=>Ux,Gleam:()=>tv,Gopls:()=>Ex,HLS:()=>sv,JDTLS:()=>qx,JuliaLS:()=>iv,KotlinLS:()=>Vx,LuaLS:()=>Gx,Nixd:()=>nv,Ocaml:()=>Jx,Oxlint:()=>kx,PHPIntelephense:()=>Hx,Prisma:()=>Yx,Pyright:()=>Rx,Razor:()=>Ox,Rubocop:()=>Tx,RustAnalyzer:()=>Nx,SourceKit:()=>jx,Svelte:()=>Bx,TerraformLS:()=>Qx,TexLab:()=>Zx,Tinymist:()=>rv,Ty:()=>Px,Typescript:()=>vx,Vue:()=>Ix,YamlLS:()=>zx,Zls:()=>Cx});import Y from"path";import Or from"os";import{text as wx}from"node:stream/consumers";import je from"fs/promises";var so={};ae(so,{Archive:()=>so,extractZip:()=>hx});import Ip from"path";async function hx(e,t){if(process.platform==="win32"){let o=Ip.resolve(e),n=Ip.resolve(t),r=`$global:ProgressPreference = 'SilentlyContinue'; Expand-Archive -Path '${o}' -DestinationPath '${n}' -Force`;await Aa(["powershell","-NoProfile","-NonInteractive","-Command",r]);return}await Aa(["unzip","-o","-q",e,"-d",t])}s(hx,"extractZip");import{createRequire as gx}from"node:module";import yx from"node:path";var Mr;(t=>{function e(o,n){try{return gx(yx.join(n,"package.json")).resolve(o)}catch{}}t.resolve=e,s(e,"resolve")})(Mr||={});function xe(e,t,o){let n=Array.isArray(t)?[...t]:[],r=Array.isArray(t)?o:t,i=st.spawn([e,...n],{...r,stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(!i.stdin||!i.stdout||!i.stderr)throw new Error("Process output not available");return i}s(xe,"spawn");var Lr=s(async e=>je.stat(e).then(()=>!0).catch(()=>!1),"pathExists"),Nn=s((e,t={})=>st.run(e,{...t,nothrow:!0}),"run"),bx=s((e,t={})=>st.text(e,{...t,nothrow:!0}),"output"),Re=s((e,t)=>async(o,n)=>{if(t){let a=le.up({targets:t,start:Y.dirname(o),stop:n.directory}),c=await a.next();if(await a.return(),c.value)return}let r=le.up({targets:e,start:Y.dirname(o),stop:n.directory}),i=await r.next();return await r.return(),i.value?Y.dirname(i.value):n.directory},"NearestRoot"),Gi=s((e,t)=>async(o,n)=>{if(t){let a=le.up({targets:t,start:Y.dirname(o),stop:n.directory}),c=await a.next();if(await a.return(),c.value)return}let r=le.up({targets:e,start:Y.dirname(o),stop:n.directory}),i=await r.next();if(await r.return(),!!i.value)return Y.dirname(i.value)},"StrictNearestRoot"),xx={id:"deno",root:s(async(e,t)=>{let o=le.up({targets:["deno.json","deno.jsonc"],start:Y.dirname(e),stop:t.directory}),n=await o.next();if(await o.return(),!!n.value)return Y.dirname(n.value)},"root"),extensions:[".ts",".tsx",".js",".jsx",".mjs"],async spawn(e){let t=X("deno");if(t)return{process:xe(t,["lsp"],{cwd:e})}}},vx={id:"typescript",root:Re(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"],["deno.json","deno.jsonc"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],async spawn(e,t){let o=Mr.resolve("typescript/lib/tsserver.js",t.directory);if(!o)return;let n=await jt.which("typescript-language-server");return n?{process:xe(n,["--stdio"],{cwd:e,env:{...process.env}}),initialization:{tsserver:{path:o}}}:void 0}},Ix={id:"vue",extensions:[".vue"],root:Re(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,o){let n=X("vue-language-server"),r=[];if(!n){if(o.disableLspDownload)return;let a=await jt.which("@vue/language-server");if(!a)return;n=a}return r.push("--stdio"),{process:xe(n,r,{cwd:e,env:{...process.env}}),initialization:{}}}},Sx={id:"eslint",root:Re(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue"],async spawn(e,t,o){if(!Mr.resolve("eslint",t.directory))return;let r=Y.join(me.Path.bin,"vscode-eslint","server","out","eslintServer.js");if(!await le.exists(r)){if(o.disableLspDownload)return;let a=await fetch("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip");if(!a.ok)return;let c=Y.join(me.Path.bin,"vscode-eslint.zip");if(a.body&&await le.writeStream(c,a.body),!await so.extractZip(c,me.Path.bin).then(()=>!0).catch(g=>!1))return;await je.rm(c,{force:!0});let u=Y.join(me.Path.bin,"vscode-eslint-main"),l=Y.join(me.Path.bin,"vscode-eslint");await je.stat(l).catch(()=>{})&&await je.rm(l,{force:!0,recursive:!0}),await je.rename(u,l);let h=process.platform==="win32"?"npm.cmd":"npm";await st.run([h,"install"],{cwd:l}),await st.run([h,"run","compile"],{cwd:l})}return{process:xe("node",[r,"--stdio"],{cwd:e,env:{...process.env}})}}},kx={id:"oxlint",root:Re([".oxlintrc.json","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock","package.json"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".astro",".svelte"],async spawn(e,t){let o=process.platform==="win32"?".cmd":"",n=Y.join("node_modules",".bin","oxc_language_server"+o),r=Y.join("node_modules",".bin","oxlint"+o),i=s(async d=>{let u=Y.join(e,d);if(await le.exists(u))return u;let l=le.up({targets:[d],start:e,stop:t.worktree}),m=await l.next();if(await l.return(),m.value)return m.value},"resolveBin"),a=await i(r);if(!a){let d=X("oxlint");d&&(a=d)}if(a){let d=xe(a,["--help"]);if(await d.exited,d.stdout&&(await wx(d.stdout)).includes("--lsp"))return{process:xe(a,["--lsp"],{cwd:e})}}let c=await i(n);if(!c){let d=X("oxc_language_server");d&&(c=d)}if(c)return{process:xe(c,[],{cwd:e})}}},Dx={id:"biome",root:Re(["biome.json","biome.jsonc","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".json",".jsonc",".vue",".astro",".svelte",".css",".graphql",".gql",".html"],async spawn(e){let t=Y.join(e,"node_modules",".bin","biome"),o;if(await le.exists(t)&&(o=t),!o){let i=X("biome");i&&(o=i)}let n=["lsp-proxy","--stdio"];if(!o){if(!Mr.resolve("biome",e)||(o=await jt.which("biome"),!o))return;n=["lsp-proxy","--stdio"]}return{process:xe(o,n,{cwd:e,env:{...process.env}})}}},Ex={id:"gopls",root:s(async(e,t)=>{let o=await Re(["go.work"])(e,t);return o||Re(["go.mod","go.sum"])(e,t)},"root"),extensions:[".go"],async spawn(e,t,o){let n=X("gopls");if(!n){if(!X("go")||o.disableLspDownload||await st.spawn(["go","install","golang.org/x/tools/gopls@latest"],{env:{...process.env,GOBIN:me.Path.bin},stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;n=Y.join(me.Path.bin,"gopls"+(process.platform==="win32"?".exe":""))}return{process:xe(n,{cwd:e})}}},Tx={id:"ruby-lsp",root:Re(["Gemfile"]),extensions:[".rb",".rake",".gemspec",".ru"],async spawn(e,t,o){let n=X("rubocop");if(!n){let r=X("ruby"),i=X("gem");if(!r||!i||o.disableLspDownload||await st.spawn(["gem","install","rubocop","--bindir",me.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;n=Y.join(me.Path.bin,"rubocop"+(process.platform==="win32"?".exe":""))}return{process:xe(n,["--lsp"],{cwd:e})}}},Px={id:"ty",extensions:[".py",".pyi"],root:Re(["pyproject.toml","ty.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(e,t,o){if(!o.experimentalLspTy)return;let n=X("ty"),r={},i=[process.env.VIRTUAL_ENV,Y.join(e,".venv"),Y.join(e,"venv")].filter(c=>c!==void 0);for(let c of i){let u=process.platform==="win32"?Y.join(c,"Scripts","python.exe"):Y.join(c,"bin","python");if(await le.exists(u)){r.pythonPath=u;break}}if(!n)for(let c of i){let u=process.platform==="win32"?Y.join(c,"Scripts","ty.exe"):Y.join(c,"bin","ty");if(await le.exists(u)){n=u;break}}return n?{process:xe(n,["server"],{cwd:e}),initialization:r}:void 0}},Rx={id:"pyright",extensions:[".py",".pyi"],root:Re(["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(e,t,o){let n=X("pyright-langserver"),r=[];if(!n){if(o.disableLspDownload)return;let d=await jt.which("pyright","pyright-langserver");if(!d)return;n=d}r.push("--stdio");let i={},a=[process.env.VIRTUAL_ENV,Y.join(e,".venv"),Y.join(e,"venv")].filter(d=>d!==void 0);for(let d of a){let l=process.platform==="win32"?Y.join(d,"Scripts","python.exe"):Y.join(d,"bin","python");if(await le.exists(l)){i.pythonPath=l;break}}return{process:xe(n,r,{cwd:e,env:{...process.env}}),initialization:i}}},Ax={id:"elixir-ls",extensions:[".ex",".exs"],root:Re(["mix.exs","mix.lock"]),async spawn(e,t,o){let n=X("elixir-ls");if(!n){let r=Y.join(me.Path.bin,"elixir-ls");if(n=Y.join(me.Path.bin,"elixir-ls-master","release",process.platform==="win32"?"language_server.bat":"language_server.sh"),!await le.exists(n)){if(!X("elixir")||o.disableLspDownload)return;let a=await fetch("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip");if(!a.ok)return;let c=Y.join(me.Path.bin,"elixir-ls.zip");if(a.body&&await le.writeStream(c,a.body),!await so.extractZip(c,me.Path.bin).then(()=>!0).catch(m=>!1))return;await je.rm(c,{force:!0,recursive:!0});let u=Y.join(me.Path.bin,"elixir-ls-master"),l={MIX_ENV:"prod",...process.env};await st.run(["mix","deps.get"],{cwd:u,env:l}),await st.run(["mix","compile"],{cwd:u,env:l}),await st.run(["mix","elixir_ls.release2","-o","release"],{cwd:u,env:l})}}return{process:xe(n,{cwd:e})}}},Cx={id:"zls",extensions:[".zig",".zon"],root:Re(["build.zig"]),async spawn(e,t,o){let n=X("zls");if(!n){if(!X("zig")||o.disableLspDownload)return;let i=await fetch("https://api.github.com/repos/zigtools/zls/releases/latest");if(!i.ok)return;let a=await i.json(),c=process.platform,d=process.arch,u="",l=d;d==="arm64"?l="aarch64":d==="x64"?l="x86_64":d==="ia32"&&(l="x86");let m=c;c==="darwin"?m="macos":c==="win32"&&(m="windows");let h=c==="win32"?"zip":"tar.xz";if(u=`zls-${l}-${m}.${h}`,!["zls-x86_64-linux.tar.xz","zls-x86_64-macos.tar.xz","zls-x86_64-windows.zip","zls-aarch64-linux.tar.xz","zls-aarch64-macos.tar.xz","zls-aarch64-windows.zip","zls-x86-linux.tar.xz","zls-x86-windows.zip"].includes(u))return;let w=a.assets?.find(S=>S.name===u);if(!w?.browser_download_url)return;let k=w.browser_download_url,p=await fetch(k);if(!p.ok)return;let f=Y.join(me.Path.bin,u);if(p.body&&await le.writeStream(f,p.body),h==="zip"){if(!await so.extractZip(f,me.Path.bin).then(()=>!0).catch(y=>!1))return}else await Nn(["tar","-xf",f],{cwd:me.Path.bin});if(await je.rm(f,{force:!0}),n=Y.join(me.Path.bin,"zls"+(c==="win32"?".exe":"")),!await le.exists(n))return;c!=="win32"&&await je.chmod(n,493).catch(()=>{})}return{process:xe(n,{cwd:e})}}},Mx={id:"csharp",root:Re([".slnx",".sln",".csproj","global.json"]),extensions:[".cs",".csx"],async spawn(e,t,o){let n=await Sp(o.disableLspDownload);if(n)return{process:xe(n,["--stdio","--autoLoadProjects"],{cwd:e})}}},Ox={id:"razor",root:Re([".slnx",".sln",".csproj","global.json"]),extensions:[".razor",".cshtml"],async spawn(e,t,o){let n=await Sp(o.disableLspDownload);if(!n)return;let r=await _x();if(r)return{process:xe(n,["--stdio","--autoLoadProjects",`--razorSourceGenerator=${r.compiler}`,`--razorDesignTimePath=${r.targets}`,"--extension",r.extension],{cwd:e})}}},wc;async function Sp(e){let t=X("roslyn-language-server");if(t)return t;let o=await kp();return o||(wc||=Lx(e).finally(()=>{wc=void 0}),wc)}s(Sp,"getRoslynLanguageServer");async function Lx(e){if(!X("dotnet")||e||await st.spawn(["dotnet","tool","install","--global","roslyn-language-server","--prerelease"],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;let n=X("roslyn-language-server");if(n)return n;let r=await kp();if(r)return r}s(Lx,"installRoslynLanguageServer");async function kp(){let e=Y.join(process.env.DOTNET_CLI_HOME??Or.homedir(),".dotnet","tools","roslyn-language-server"+(process.platform==="win32"?".cmd":""));return await Lr(e)?e:void 0}s(kp,"roslynLanguageServerGlobalPath");async function _x(){let e=[process.env.VSCODE_EXTENSIONS,Y.join(Or.homedir(),".vscode","extensions"),Y.join(Or.homedir(),".vscode-insiders","extensions"),Y.join(Or.homedir(),".vscode-server","extensions"),Y.join(Or.homedir(),".vscode-server-insiders","extensions")].filter(t=>t!==void 0);for(let t of[...new Set(e)]){let o=await je.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=await Promise.all(o.filter(r=>r.isDirectory()&&r.name.startsWith("ms-dotnettools.csharp-")).map(async r=>({path:Y.join(t,r.name,".razorExtension"),modified:(await je.stat(Y.join(t,r.name)).catch(()=>{}))?.mtimeMs??0})));for(let r of n.sort((i,a)=>a.modified-i.modified).map(i=>i.path)){let i={compiler:Y.join(r,"Microsoft.CodeAnalysis.Razor.Compiler.dll"),targets:Y.join(r,"Targets","Microsoft.NET.Sdk.Razor.DesignTime.targets"),extension:Y.join(r,"Microsoft.VisualStudioCode.RazorExtension.dll")};if(await Lr(i.compiler)&&await Lr(i.targets)&&await Lr(i.extension))return i}}}s(_x,"findVscodeRazorExtension");var Ux={id:"fsharp",root:Re([".slnx",".sln",".fsproj","global.json"]),extensions:[".fs",".fsi",".fsx",".fsscript"],async spawn(e,t,o){let n=X("fsautocomplete");if(!n){if(!X("dotnet")||o.disableLspDownload||await st.spawn(["dotnet","tool","install","fsautocomplete","--tool-path",me.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;n=Y.join(me.Path.bin,"fsautocomplete"+(process.platform==="win32"?".exe":""))}return{process:xe(n,{cwd:e})}}},jx={id:"sourcekit-lsp",extensions:[".swift",".objc","objcpp"],root:Re(["Package.swift","*.xcodeproj","*.xcworkspace"]),async spawn(e){let t=X("sourcekit-lsp");if(t)return{process:xe(t,{cwd:e})};if(!X("xcrun"))return;let o=await bx(["xcrun","--find","sourcekit-lsp"]);if(o.code!==0)return;let n=o.text.trim();return{process:xe(n,{cwd:e})}}},Nx={id:"rust",root:s(async(e,t)=>{let o=await Re(["Cargo.toml","Cargo.lock"])(e,t);if(o===void 0)return;let n=o;for(;n!==Y.dirname(n);){let r=Y.join(n,"Cargo.toml");try{if((await le.readText(r)).includes("[workspace]"))return n}catch{}let i=Y.dirname(n);if(i===n||(n=i,!n.startsWith(t.worktree)))break}return o},"root"),extensions:[".rs"],async spawn(e){let t=X("rust-analyzer");if(t)return{process:xe(t,{cwd:e})}}},Fx={id:"clangd",root:Re(["compile_commands.json","compile_flags.txt",".clangd"]),extensions:[".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++"],async spawn(e,t,o){let n=["--background-index","--clang-tidy"],r=X("clangd");if(r)return{process:xe(r,n,{cwd:e})};let i=process.platform==="win32"?".exe":"",a=Y.join(me.Path.bin,"clangd"+i);if(await le.exists(a))return{process:xe(a,n,{cwd:e})};let c=await je.readdir(me.Path.bin,{withFileTypes:!0}).catch(()=>[]);for(let E of c){if(!E.isDirectory()||!E.name.startsWith("clangd_"))continue;let j=Y.join(me.Path.bin,E.name,"bin","clangd"+i);if(await le.exists(j))return{process:xe(j,n,{cwd:e})}}if(o.disableLspDownload)return;let d=await fetch("https://api.github.com/repos/clangd/clangd/releases/latest");if(!d.ok)return;let u=await d.json(),l=u.tag_name;if(!l)return;let m=process.platform,g={darwin:"mac",linux:"linux",win32:"windows"}[m];if(!g)return;let w=u.assets??[],k=s(E=>!E.name||!E.browser_download_url||!E.name.includes(g)?!1:E.name.includes(l),"valid"),p=w.find(E=>k(E)&&E.name?.endsWith(".zip"))??w.find(E=>k(E)&&E.name?.endsWith(".tar.xz"))??w.find(E=>k(E));if(!p?.name||!p.browser_download_url)return;let f=p.name,S=await fetch(p.browser_download_url);if(!S.ok)return;let y=Y.join(me.Path.bin,f),v=await S.arrayBuffer();if(v.byteLength===0)return;await le.write(y,Buffer.from(v));let P=f.endsWith(".zip"),b=f.endsWith(".tar.xz");if(!P&&!b||P&&!await so.extractZip(y,me.Path.bin).then(()=>!0).catch(j=>!1))return;b&&await Nn(["tar","-xf",y],{cwd:me.Path.bin}),await je.rm(y,{force:!0});let T=Y.join(me.Path.bin,"clangd_"+l,"bin","clangd"+i);if(await le.exists(T))return m!=="win32"&&await je.chmod(T,493).catch(()=>{}),await je.unlink(Y.join(me.Path.bin,"clangd")).catch(()=>{}),await je.symlink(T,Y.join(me.Path.bin,"clangd")).catch(()=>{}),{process:xe(T,n,{cwd:e})}}},Bx={id:"svelte",extensions:[".svelte"],root:Re(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,o){let n=X("svelteserver"),r=[];if(!n){if(o.disableLspDownload)return;let a=await jt.which("svelte-language-server");if(!a)return;n=a}return r.push("--stdio"),{process:xe(n,r,{cwd:e,env:{...process.env}}),initialization:{}}}},$x={id:"astro",extensions:[".astro"],root:Re(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,o){let n=Mr.resolve("typescript/lib/tsserver.js",t.directory);if(!n)return;let r=Y.dirname(n),i=X("astro-ls"),a=[];if(!i){if(o.disableLspDownload)return;let d=await jt.which("@astrojs/language-server");if(!d)return;i=d}return a.push("--stdio"),{process:xe(i,a,{cwd:e,env:{...process.env}}),initialization:{typescript:{tsdk:r}}}}};function Wx(e,t){let o=t.replace(/\\/g,"/").replace(/\/$/,"");if(!o)return!1;let n=e.match(/<modules>([\s\S]*?)<\/modules>/g)??[];for(let r of n){let i=r.replace(/<!--[\s\S]*?-->/g,"");for(let a of i.matchAll(/<module>\s*([^<]+?)\s*<\/module>/g))if(a[1].replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"")===o)return!0}return!1}s(Wx,"isModuleOf");var qx={id:"jdtls",root:s(async(e,t)=>{let o=["settings.gradle","settings.gradle.kts"],n=["gradlew","gradlew.bat"],[r,i]=await Promise.all([Gi(n,o)(e,t),Gi(o)(e,t)]);if(r)return r;if(i)return i;let a=await Gi(["build.gradle","build.gradle.kts"])(e,t);if(a)return a;let c=await le.findUp("pom.xml",Y.dirname(e),t.directory);if(c.length>0){let u=Y.dirname(c[0]);for(let l=1;l<c.length;l++){let m=Y.dirname(c[l]),h=Y.relative(m,u),g=await je.readFile(c[l],"utf-8").catch(()=>null);if(g&&Wx(g,h))u=m;else break}return u}let d=await Gi([".project",".classpath"])(e,t);if(d)return d},"root"),extensions:[".java"],async spawn(e,t,o){let n=X("java");if(!n)return;let r=await Nn(["java","-version"]).then(h=>{let g=/"(\d+)\.\d+\.\d+"/.exec(h.stderr.toString());return g?parseInt(g[1]):void 0});if(r==null||r<21)return;let i=Y.join(me.Path.bin,"jdtls"),a=Y.join(i,"plugins");if(!await Lr(a)){if(o.disableLspDownload)return;await je.mkdir(i,{recursive:!0});let h="https://www.eclipse.org/downloads/download.php?file=/jdtls/snapshots/jdt-language-server-latest.tar.gz",g="release.tar.gz",w=await fetch(h);if(!w.ok||!w.body||(await le.writeStream(Y.join(i,g),w.body),(await Nn(["tar","-xzf",g],{cwd:i})).code!==0))return;await je.rm(Y.join(i,g),{force:!0})}let d=(await je.readdir(a).catch(()=>[])).find(h=>/^org\.eclipse\.equinox\.launcher_.*\.jar$/.test(h))?.trim()??"",u=Y.join(a,d);if(!await Lr(u))return;let l=Y.join(i,(()=>{switch(process.platform){case"darwin":return"config_mac";case"linux":return"config_linux";case"win32":return"config_win";default:return"config_linux"}})()),m=await je.mkdtemp(Y.join(Or.tmpdir(),"opencode-jdtls-data"));return{process:xe(n,["-jar",u,"-configuration",l,"-data",m,"-Declipse.application=org.eclipse.jdt.ls.core.id1","-Dosgi.bundles.defaultStartLevel=4","-Declipse.product=org.eclipse.jdt.ls.core.product","-Dlog.level=ALL","--add-modules=ALL-SYSTEM","--add-opens java.base/java.util=ALL-UNNAMED","--add-opens java.base/java.lang=ALL-UNNAMED"],{cwd:e})}}},Vx={id:"kotlin-ls",extensions:[".kt",".kts"],root:s(async(e,t)=>{let o=await Re(["settings.gradle.kts","settings.gradle"])(e,t);if(o)return o;let n=await Re(["gradlew","gradlew.bat"])(e,t);if(n)return n;let r=await Re(["build.gradle.kts","build.gradle"])(e,t);return r||Re(["pom.xml"])(e,t)},"root"),async spawn(e,t,o){let n=Y.join(me.Path.bin,"kotlin-ls"),r=process.platform==="win32"?Y.join(n,"kotlin-lsp.cmd"):Y.join(n,"kotlin-lsp.sh");if(!await le.exists(r)){if(o.disableLspDownload)return;let a=await fetch("https://api.github.com/repos/Kotlin/kotlin-lsp/releases/latest");if(!a.ok)return;let d=(await a.json()).name?.replace(/^v/,"");if(!d)return;let u=process.platform,l=process.arch,m=l;l==="arm64"?m="aarch64":l==="x64"&&(m="x64");let h=u;u==="darwin"?h="mac":u==="linux"?h="linux":u==="win32"&&(h="win");let g=["mac-x64","mac-aarch64","linux-x64","linux-aarch64","win-x64","win-aarch64"],w=`${h}-${m}`;if(!g.includes(w))return;let k=`kotlin-lsp-${d}-${h}-${m}.zip`,p=`https://download-cdn.jetbrains.com/kotlin-lsp/${d}/${k}`;await je.mkdir(n,{recursive:!0});let f=Y.join(n,"kotlin-ls.zip"),S=await fetch(p);if(!S.ok||!S.body||(await le.writeStream(f,S.body),!await so.extractZip(f,n).then(()=>!0).catch(v=>!1)))return;await je.rm(f,{force:!0}),process.platform!=="win32"&&await je.chmod(r,493).catch(()=>{})}if(await le.exists(r))return{process:xe(r,["--stdio"],{cwd:e})}}},zx={id:"yaml-ls",extensions:[".yaml",".yml"],root:Re(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,o){let n=X("yaml-language-server"),r=[];if(!n){if(o.disableLspDownload)return;let a=await jt.which("yaml-language-server");if(!a)return;n=a}return r.push("--stdio"),{process:xe(n,r,{cwd:e,env:{...process.env}})}}},Gx={id:"lua-ls",root:Re([".luarc.json",".luarc.jsonc",".luacheckrc",".stylua.toml","stylua.toml","selene.toml","selene.yml"]),extensions:[".lua"],async spawn(e,t,o){let n=X("lua-language-server");if(!n){if(o.disableLspDownload)return;let r=await fetch("https://api.github.com/repos/LuaLS/lua-language-server/releases/latest");if(!r.ok)return;let i=await r.json(),a=process.platform,c=process.arch,d="",u=c;c==="arm64"?u="arm64":c==="x64"?u="x64":c==="ia32"&&(u="ia32");let l=a;a==="darwin"?l="darwin":a==="linux"?l="linux":a==="win32"&&(l="win32");let m=a==="win32"?"zip":"tar.gz";d=`lua-language-server-${i.tag_name}-${l}-${u}.${m}`;let h=["darwin-arm64.tar.gz","darwin-x64.tar.gz","linux-x64.tar.gz","linux-arm64.tar.gz","win32-x64.zip","win32-ia32.zip"],g=`${l}-${u}.${m}`;if(!h.includes(g))return;let w=i.assets.find(v=>v.name===d);if(!w)return;let k=w.browser_download_url,p=await fetch(k);if(!p.ok)return;let f=Y.join(me.Path.bin,d);p.body&&await le.writeStream(f,p.body);let S=Y.join(me.Path.bin,`lua-language-server-${u}-${l}`);if(await je.stat(S).catch(()=>{})&&await je.rm(S,{force:!0,recursive:!0}),await je.mkdir(S,{recursive:!0}),m==="zip"){if(!await so.extractZip(f,S).then(()=>!0).catch(P=>!1))return}else if(!await Nn(["tar","-xzf",f,"-C",S]).then(P=>P.code===0).catch(P=>!1))return;if(await je.rm(f,{force:!0}),n=Y.join(S,"bin","lua-language-server"+(a==="win32"?".exe":"")),!await le.exists(n)||a!=="win32"&&!await je.chmod(n,493).then(()=>!0).catch(P=>!1))return}return{process:xe(n,{cwd:e})}}},Hx={id:"php intelephense",extensions:[".php"],root:Re(["composer.json","composer.lock",".php-version"]),async spawn(e,t,o){let n=X("intelephense"),r=[];if(!n){if(o.disableLspDownload)return;let a=await jt.which("intelephense");if(!a)return;n=a}return r.push("--stdio"),{process:xe(n,r,{cwd:e,env:{...process.env}}),initialization:{telemetry:{enabled:!1}}}}},Yx={id:"prisma",extensions:[".prisma"],root:Re(["schema.prisma","prisma/schema.prisma","prisma"],["package.json"]),async spawn(e){let t=X("prisma");if(t)return{process:xe(t,["language-server"],{cwd:e})}}},Kx={id:"dart",extensions:[".dart"],root:Re(["pubspec.yaml","analysis_options.yaml"]),async spawn(e){let t=X("dart");if(t)return{process:xe(t,["language-server","--lsp"],{cwd:e})}}},Jx={id:"ocaml-lsp",extensions:[".ml",".mli"],root:Re(["dune-project","dune-workspace",".merlin","opam"]),async spawn(e){let t=X("ocamllsp");if(t)return{process:xe(t,{cwd:e})}}},Xx={id:"bash",extensions:[".sh",".bash",".zsh",".ksh"],root:s(async(e,t)=>t.directory,"root"),async spawn(e,t,o){let n=X("bash-language-server"),r=[];if(!n){if(o.disableLspDownload)return;let a=await jt.which("bash-language-server");if(!a)return;n=a}return r.push("start"),{process:xe(n,r,{cwd:e,env:{...process.env}})}}},Qx={id:"terraform",extensions:[".tf",".tfvars"],root:Re([".terraform.lock.hcl","terraform.tfstate","*.tf"]),async spawn(e,t,o){let n=X("terraform-ls");if(!n){if(o.disableLspDownload)return;let r=await fetch("https://api.releases.hashicorp.com/v1/releases/terraform-ls/latest");if(!r.ok)return;let i=await r.json(),a=process.platform,d=process.arch==="arm64"?"arm64":"amd64",u=a==="win32"?"windows":a,m=(i.builds??[]).find(k=>k.arch===d&&k.os===u);if(!m?.url)return;let h=await fetch(m.url);if(!h.ok)return;let g=Y.join(me.Path.bin,"terraform-ls.zip");if(h.body&&await le.writeStream(g,h.body),!await so.extractZip(g,me.Path.bin).then(()=>!0).catch(k=>!1)||(await je.rm(g,{force:!0}),n=Y.join(me.Path.bin,"terraform-ls"+(a==="win32"?".exe":"")),!await le.exists(n)))return;a!=="win32"&&await je.chmod(n,493).catch(()=>{})}return{process:xe(n,["serve"],{cwd:e}),initialization:{experimentalFeatures:{prefillRequiredFields:!0,validateOnSave:!0}}}}},Zx={id:"texlab",extensions:[".tex",".bib"],root:Re([".latexmkrc","latexmkrc",".texlabroot","texlabroot"]),async spawn(e,t,o){let n=X("texlab");if(!n){if(o.disableLspDownload)return;let r=await fetch("https://api.github.com/repos/latex-lsp/texlab/releases/latest");if(!r.ok)return;let i=await r.json();if(!i.tag_name?.replace("v",""))return;let c=process.platform,u=process.arch==="arm64"?"aarch64":"x86_64",l=c==="darwin"?"macos":c==="win32"?"windows":"linux",m=c==="win32"?"zip":"tar.gz",h=`texlab-${u}-${l}.${m}`,w=(i.assets??[]).find(f=>f.name===h);if(!w?.browser_download_url)return;let k=await fetch(w.browser_download_url);if(!k.ok)return;let p=Y.join(me.Path.bin,h);if(k.body&&await le.writeStream(p,k.body),m==="zip"&&!await so.extractZip(p,me.Path.bin).then(()=>!0).catch(S=>!1)||(m==="tar.gz"&&await Nn(["tar","-xzf",p],{cwd:me.Path.bin}),await je.rm(p,{force:!0}),n=Y.join(me.Path.bin,"texlab"+(c==="win32"?".exe":"")),!await le.exists(n)))return;c!=="win32"&&await je.chmod(n,493).catch(()=>{})}return{process:xe(n,{cwd:e})}}},ev={id:"dockerfile",extensions:[".dockerfile","Dockerfile"],root:s(async(e,t)=>t.directory,"root"),async spawn(e,t,o){let n=X("docker-langserver"),r=[];if(!n){if(o.disableLspDownload)return;let a=await jt.which("dockerfile-language-server-nodejs");if(!a)return;n=a}return r.push("--stdio"),{process:xe(n,r,{cwd:e,env:{...process.env}})}}},tv={id:"gleam",extensions:[".gleam"],root:Re(["gleam.toml"]),async spawn(e){let t=X("gleam");if(t)return{process:xe(t,["lsp"],{cwd:e})}}},ov={id:"clojure-lsp",extensions:[".clj",".cljs",".cljc",".edn"],root:Re(["deps.edn","project.clj","shadow-cljs.edn","bb.edn","build.boot"]),async spawn(e){let t=X("clojure-lsp");if(!t&&process.platform==="win32"&&(t=X("clojure-lsp.exe")),!!t)return{process:xe(t,["listen"],{cwd:e})}}},nv={id:"nixd",extensions:[".nix"],root:s(async(e,t)=>{let o=await Re(["flake.nix"])(e,t);return o&&o!==t.directory?o:t.worktree&&t.worktree!==t.directory?t.worktree:t.directory},"root"),async spawn(e){let t=X("nixd");if(t)return{process:xe(t,[],{cwd:e,env:{...process.env}})}}},rv={id:"tinymist",extensions:[".typ",".typc"],root:Re(["typst.toml"]),async spawn(e,t,o){let n=X("tinymist");if(!n){if(o.disableLspDownload)return;let r=await fetch("https://api.github.com/repos/Myriad-Dreamin/tinymist/releases/latest");if(!r.ok)return;let i=await r.json(),a=process.platform,d=process.arch==="arm64"?"aarch64":"x86_64",u,l;a==="darwin"?(u="apple-darwin",l="tar.gz"):a==="win32"?(u="pc-windows-msvc",l="zip"):(u="unknown-linux-gnu",l="tar.gz");let m=`tinymist-${d}-${u}.${l}`,g=(i.assets??[]).find(p=>p.name===m);if(!g?.browser_download_url)return;let w=await fetch(g.browser_download_url);if(!w.ok)return;let k=Y.join(me.Path.bin,m);if(w.body&&await le.writeStream(k,w.body),l==="zip"){if(!await so.extractZip(k,me.Path.bin).then(()=>!0).catch(f=>!1))return}else await Nn(["tar","-xzf",k,"--strip-components=1"],{cwd:me.Path.bin});if(await je.rm(k,{force:!0}),n=Y.join(me.Path.bin,"tinymist"+(a==="win32"?".exe":"")),!await le.exists(n))return;a!=="win32"&&await je.chmod(n,493).catch(()=>{})}return{process:xe(n,{cwd:e})}}},sv={id:"haskell-language-server",extensions:[".hs",".lhs"],root:Re(["stack.yaml","cabal.project","hie.yaml","*.cabal"]),async spawn(e){let t=X("haskell-language-server-wrapper");if(t)return{process:xe(t,["--lsp"],{cwd:e})}}},iv={id:"julials",extensions:[".jl"],root:Re(["Project.toml","Manifest.toml","*.jl"]),async spawn(e){let t=X("julia");if(t)return{process:xe(t,["--startup-file=no","--history-file=no","-e","using LanguageServer; runserver()"],{cwd:e})}}};import{Effect as Ne,Layer as dv,Context as uv,Schema as $t}from"effect";var Ps={};ae(Ps,{Definitions:()=>av,LspEvent:()=>Ps,Updated:()=>Dp});var Dp=kt.define({type:"lsp.updated",schema:{}}),av=kt.inventory(Dp);var Rs={};ae(Rs,{Diagnostic:()=>Rs,pretty:()=>Tp,report:()=>cv});var Ep=20;function Tp(e){let o={1:"ERROR",2:"WARN",3:"INFO",4:"HINT"}[e.severity||1],n=e.range.start.line+1,r=e.range.start.character+1;return`${o} [${n}:${r}] ${e.message}`}s(Tp,"pretty");function cv(e,t){let o=t.filter(a=>a.severity===1);if(o.length===0)return"";let n=o.slice(0,Ep),r=o.length-Ep,i=r>0?`
995
- ... and ${r} more`:"";return`<diagnostics file="${e}">
996
- ${n.map(Tp).join(`
997
- `)}${i}
998
- </diagnostics>`}s(cv,"report");var Rp=Ps,Pp=$t.Struct({line:bo,character:bo}),Hi=$t.Struct({start:Pp,end:Pp}).annotate({identifier:"Range"}),pv=$t.Struct({name:$t.String,kind:bo,location:$t.Struct({uri:$t.String,range:Hi})}).annotate({identifier:"Symbol"}),fv=$t.Struct({name:$t.String,detail:$t.optional($t.String),kind:bo,range:Hi,selectionRange:Hi}).annotate({identifier:"DocumentSymbol"}),mv=$t.Struct({id:$t.String,name:$t.String,root:$t.String,status:$t.Literals(["connected","error"])}).annotate({identifier:"LSPStatus"});var hv=[5,12,6,11,13,14,23,10],gv=s((e,t)=>{t.experimentalLspTy?e.pyright&&delete e.pyright:e.ty&&delete e.ty},"filterExperimentalServers"),Ur=class extends uv.Service()("@opencode/LSP"){static{s(this,"Service")}},yv=dv.effect(Ur,Ne.gen(function*(){let e=yield*De.Service,t=yield*Me.Service,o=yield*we.Service,n=yield*B.make(Ne.fn("LSP.state")(function*(b){let T=yield*e.get(),E={};if(!T.lsp)yield*Ne.logInfo("all LSPs are disabled");else{for(let _ of Object.values(bc))E[_.id]=_;if(gv(E,t),T.lsp!==!0)for(let[_,W]of Object.entries(T.lsp)){let ie=E[_];if(W.disabled){yield*Ne.logInfo(`LSP server ${_} is disabled`),delete E[_];continue}E[_]={...ie,id:_,root:ie?.root??(async(M,$)=>$.directory),extensions:W.extensions??ie?.extensions??[],spawn:s(async M=>({process:xe(W.command[0],W.command.slice(1),{cwd:M,env:{...process.env,...W.env}}),initialization:W.initialization}),"spawn")}}yield*Ne.logInfo("enabled LSP servers",{serverIds:Object.values(E).map(_=>_.id).join(", ")})}let j={clients:[],servers:E,broken:new Set,spawning:new Map};return yield*Ne.addFinalizer(()=>Ne.promise(async()=>{await Promise.all(j.clients.map(_=>_.shutdown()))})),j})),r=Ne.fnUntraced(function*(b){let T=yield*B.context;if(!fi(b,T))return[];let E=yield*B.get(n),j=yield*Ne.promise(async()=>{let _=xc.parse(b).ext||b,W=[],ie=0;async function M($,x,R){let A=await $.spawn(x,T,t).then(U=>(U||E.broken.add(R),U)).catch(()=>{E.broken.add(R)});if(!A)return;let O=await xp({serverID:$.id,server:A,root:x,directory:T.directory,instance:T}).catch(async()=>{E.broken.add(R),await st.stop(A.process)});if(!O)return;let F=E.clients.find(U=>U.root===x&&U.serverID===$.id);return F?(await st.stop(A.process),F):(E.clients.push(O),O)}s(M,"schedule");for(let $ of Object.values(E.servers)){if($.extensions.length&&!$.extensions.includes(_))continue;let x=await $.root(b,T);if(!x||E.broken.has(x+$.id))continue;let R=E.clients.find(U=>U.root===x&&U.serverID===$.id);if(R){W.push(R);continue}let A=E.spawning.get(x+$.id);if(A){let U=await A;if(!U)continue;W.push(U);continue}let O=M($,x,x+$.id);E.spawning.set(x+$.id,O),O.finally(()=>{E.spawning.get(x+$.id)===O&&E.spawning.delete(x+$.id)});let F=await O;F&&(W.push(F),ie++)}return{result:W,updated:ie}});return yield*Ne.forEach(Array.from({length:j.updated}),()=>o.publish(Rp.Updated,{}),{discard:!0}),j.result}),i=Ne.fnUntraced(function*(b,T){let E=yield*r(b);return yield*Ne.promise(()=>Promise.all(E.map(j=>T(j))))}),a=Ne.fnUntraced(function*(b){let T=yield*B.get(n);return yield*Ne.promise(()=>Promise.all(T.clients.map(E=>b(E))))}),c=Ne.fn("LSP.init")(function*(){yield*B.get(n)}),d=Ne.fn("LSP.status")(function*(){let b=yield*B.context,T=yield*B.get(n),E=[];for(let j of T.clients)E.push({id:j.serverID,name:T.servers[j.serverID].id,root:xc.relative(b.directory,j.root),status:"connected"});return E}),u=Ne.fn("LSP.hasClients")(function*(b){let T=yield*B.context,E=yield*B.get(n);return yield*Ne.promise(async()=>{let j=xc.parse(b).ext||b;for(let _ of Object.values(E.servers)){if(_.extensions.length&&!_.extensions.includes(j))continue;let W=await _.root(b,T);if(W&&!E.broken.has(W+_.id))return!0}return!1})}),l=Ne.fn("LSP.touchFile")(function*(b,T){yield*Ne.logInfo("touching file",{file:b});let E=yield*r(b);yield*Ne.promise(()=>Promise.all(E.map(async j=>{let _=Date.now(),W=await j.notify.open({path:b});if(T)return j.waitForDiagnostics({path:b,version:W,mode:T,after:_})})).catch(()=>{}))}),m=Ne.fn("LSP.diagnostics")(function*(){let b={},T=yield*a(async E=>E.diagnostics);for(let E of T)for(let[j,_]of E.entries()){let W=b[j]||[];W.push(..._),b[j]=W}return b}),h=Ne.fn("LSP.hover")(function*(b){return yield*i(b.file,T=>T.connection.sendRequest("textDocument/hover",{textDocument:{uri:_r(b.file).href},position:{line:b.line,character:b.character}}).catch(()=>null))}),g=Ne.fn("LSP.definition")(function*(b){return(yield*i(b.file,E=>E.connection.sendRequest("textDocument/definition",{textDocument:{uri:_r(b.file).href},position:{line:b.line,character:b.character}}).catch(()=>null))).flat().filter(Boolean)}),w=Ne.fn("LSP.references")(function*(b){return(yield*i(b.file,E=>E.connection.sendRequest("textDocument/references",{textDocument:{uri:_r(b.file).href},position:{line:b.line,character:b.character},context:{includeDeclaration:!0}}).catch(()=>[]))).flat().filter(Boolean)}),k=Ne.fn("LSP.implementation")(function*(b){return(yield*i(b.file,E=>E.connection.sendRequest("textDocument/implementation",{textDocument:{uri:_r(b.file).href},position:{line:b.line,character:b.character}}).catch(()=>null))).flat().filter(Boolean)}),p=Ne.fn("LSP.documentSymbol")(function*(b){let T=lv(b);return(yield*i(T,j=>j.connection.sendRequest("textDocument/documentSymbol",{textDocument:{uri:b}}).catch(()=>[]))).flat().filter(Boolean)}),f=Ne.fn("LSP.workspaceSymbol")(function*(b){return(yield*a(E=>E.connection.sendRequest("workspace/symbol",{query:b}).then(j=>j.filter(_=>hv.includes(_.kind)).slice(0,10)).catch(()=>[]))).flat()}),S=Ne.fn("LSP.prepareCallHierarchy")(function*(b){return(yield*i(b.file,E=>E.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:_r(b.file).href},position:{line:b.line,character:b.character}}).catch(()=>[]))).flat().filter(Boolean)}),y=Ne.fnUntraced(function*(b,T){return(yield*i(b.file,async j=>{let _=await j.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:_r(b.file).href},position:{line:b.line,character:b.character}}).catch(()=>[]);return _?.length?j.connection.sendRequest(T,{item:_[0]}).catch(()=>[]):[]})).flat().filter(Boolean)}),v=Ne.fn("LSP.incomingCalls")(function*(b){return yield*y(b,"callHierarchy/incomingCalls")}),P=Ne.fn("LSP.outgoingCalls")(function*(b){return yield*y(b,"callHierarchy/outgoingCalls")});return Ur.of({init:c,status:d,hasClients:u,touchFile:l,diagnostics:m,hover:h,definition:g,references:w,implementation:k,documentSymbol:p,workspaceSymbol:f,prepareCallHierarchy:S,incomingCalls:v,outgoingCalls:P})})),wv=ge.make({service:Ur,layer:yv,deps:[De.node,Me.node,Se.node,we.node]});var Xt={};ae(Xt,{Format:()=>Xt,Service:()=>Fn,Status:()=>Kv,node:()=>Qv,use:()=>Jv});import{Effect as At,Layer as Vv,Context as zv,Schema as As}from"effect";import{ChildProcess as Gv}from"effect/unstable/process";import Hv from"path";import{mergeDeep as Yv}from"remeda";var Yi={};ae(Yi,{biome:()=>Sv,clang:()=>Dv,cljfmt:()=>Wv,dart:()=>Mv,dfmt:()=>qv,gleam:()=>Uv,gofmt:()=>bv,htmlbeautifier:()=>Cv,ktlint:()=>Ev,latexindent:()=>_v,mix:()=>xv,nixfmt:()=>Nv,ocamlformat:()=>Ov,ormolu:()=>$v,oxfmt:()=>Iv,pint:()=>Bv,prettier:()=>vv,rlang:()=>Tv,rubocop:()=>Rv,ruff:()=>Ap,rustfmt:()=>Fv,shfmt:()=>jv,standardrb:()=>Av,terraform:()=>Lv,uvformat:()=>Pv,zig:()=>kv});var bv={name:"gofmt",extensions:[".go"],async enabled(){let e=X("gofmt");return e?[e,"-w","$FILE"]:!1}},xv={name:"mix",extensions:[".ex",".exs",".eex",".heex",".leex",".neex",".sface"],async enabled(){let e=X("mix");return e?[e,"format","$FILE"]:!1}},vv={name:"prettier",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".yaml",".yml",".toml",".xml",".md",".mdx",".graphql",".gql"],async enabled(e){let t=await le.findUp("package.json",e.directory,e.worktree);for(let o of t){let n=await le.readJson(o);if(n.dependencies?.prettier||n.devDependencies?.prettier){let r=await jt.which("prettier");if(r)return[r,"--write","$FILE"]}}return!1}},Iv={name:"oxfmt",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts"],async enabled(e){if(!e.experimentalOxfmt)return!1;let t=await le.findUp("package.json",e.directory,e.worktree);for(let o of t){let n=await le.readJson(o);if(n.dependencies?.oxfmt||n.devDependencies?.oxfmt){let r=await jt.which("oxfmt");if(r)return[r,"$FILE"]}}return!1}},Sv={name:"biome",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".yaml",".yml",".toml",".xml",".md",".mdx",".graphql",".gql"],async enabled(e){let t=["biome.json","biome.jsonc"];for(let o of t)if((await le.findUp(o,e.directory,e.worktree)).length>0){let r=await jt.which("@biomejs/biome");if(r)return[r,"format","--write","$FILE"]}return!1}},kv={name:"zig",extensions:[".zig",".zon"],async enabled(){let e=X("zig");return e?[e,"fmt","$FILE"]:!1}},Dv={name:"clang-format",extensions:[".c",".cc",".cpp",".cxx",".c++",".h",".hh",".hpp",".hxx",".h++",".ino",".C",".H"],async enabled(e){if((await le.findUp(".clang-format",e.directory,e.worktree)).length>0){let o=X("clang-format");if(o)return[o,"-i","$FILE"]}return!1}},Ev={name:"ktlint",extensions:[".kt",".kts"],async enabled(){let e=X("ktlint");return e?[e,"-F","$FILE"]:!1}},Ap={name:"ruff",extensions:[".py",".pyi"],async enabled(e){if(!X("ruff"))return!1;let t=["pyproject.toml","ruff.toml",".ruff.toml"];for(let n of t){let r=await le.findUp(n,e.directory,e.worktree);if(r.length>0)if(n==="pyproject.toml"){if((await le.readText(r[0])).includes("[tool.ruff]"))return["ruff","format","$FILE"]}else return["ruff","format","$FILE"]}let o=["requirements.txt","pyproject.toml","Pipfile"];for(let n of o){let r=await le.findUp(n,e.directory,e.worktree);if(r.length>0&&(await le.readText(r[0])).includes("ruff"))return["ruff","format","$FILE"]}return!1}},Tv={name:"air",extensions:[".R"],async enabled(){let e=X("air");if(e==null)return!1;let t=await st.text([e,"--help"],{nothrow:!0}),o=t.text.split(`
999
- `)[0],n=o.includes("R language"),r=o.includes("formatter");return t.code===0&&n&&r?[e,"format","$FILE"]:!1}},Pv={name:"uv",extensions:[".py",".pyi"],async enabled(e){if(await Ap.enabled(e))return!1;let t=X("uv");return t==null?!1:(await st.run([t,"format","--help"],{nothrow:!0})).code===0?[t,"format","--","$FILE"]:!1}},Rv={name:"rubocop",extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){let e=X("rubocop");return e?[e,"--autocorrect","$FILE"]:!1}},Av={name:"standardrb",extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){let e=X("standardrb");return e?[e,"--fix","$FILE"]:!1}},Cv={name:"htmlbeautifier",extensions:[".erb",".html.erb"],async enabled(){let e=X("htmlbeautifier");return e?[e,"$FILE"]:!1}},Mv={name:"dart",extensions:[".dart"],async enabled(){let e=X("dart");return e?[e,"format","$FILE"]:!1}},Ov={name:"ocamlformat",extensions:[".ml",".mli"],async enabled(e){return X("ocamlformat")&&(await le.findUp(".ocamlformat",e.directory,e.worktree)).length>0?["ocamlformat","-i","$FILE"]:!1}},Lv={name:"terraform",extensions:[".tf",".tfvars"],async enabled(){let e=X("terraform");return e?[e,"fmt","$FILE"]:!1}},_v={name:"latexindent",extensions:[".tex"],async enabled(){let e=X("latexindent");return e?[e,"-w","-s","$FILE"]:!1}},Uv={name:"gleam",extensions:[".gleam"],async enabled(){let e=X("gleam");return e?[e,"format","$FILE"]:!1}},jv={name:"shfmt",extensions:[".sh",".bash"],async enabled(){let e=X("shfmt");return e?[e,"-w","$FILE"]:!1}},Nv={name:"nixfmt",extensions:[".nix"],async enabled(){let e=X("nixfmt");return e?[e,"$FILE"]:!1}},Fv={name:"rustfmt",extensions:[".rs"],async enabled(){let e=X("rustfmt");return e?[e,"$FILE"]:!1}},Bv={name:"pint",extensions:[".php"],async enabled(e){let t=await le.findUp("composer.json",e.directory,e.worktree);for(let o of t){let n=await le.readJson(o);if(n.require?.["laravel/pint"]||n["require-dev"]?.["laravel/pint"])return["./vendor/bin/pint","$FILE"]}return!1}},$v={name:"ormolu",extensions:[".hs"],async enabled(){let e=X("ormolu");return e?[e,"-i","$FILE"]:!1}},Wv={name:"cljfmt",extensions:[".clj",".cljs",".cljc",".edn"],async enabled(){let e=X("cljfmt");return e?[e,"fix","--quiet","$FILE"]:!1}},qv={name:"dfmt",extensions:[".d"],async enabled(){let e=X("dfmt");return e?[e,"-i","$FILE"]:!1}};var Kv=As.Struct({name:As.String,extensions:As.Array(As.String),enabled:As.Boolean}).annotate({identifier:"FormatterStatus"}),Fn=class extends zv.Service()("@opencode/Format"){static{s(this,"Service")}},Jv=Gt(Fn),Xv=Vv.effect(Fn,At.gen(function*(){let e=yield*De.Service,t=yield*nr.Service,o=yield*Me.Service,n=yield*B.make(At.fn("Format.state")(function*(c){let d={},u={};async function l(k){let p=d[k.name];return(p===!1||p===void 0)&&(p=await k.enabled({...c,experimentalOxfmt:o.experimentalOxfmt}),d[k.name]=p),p}s(l,"getCommand");async function m(k){return await l(k)!==!1}s(m,"isEnabled");async function h(k){let p=Object.values(u).filter(S=>S.extensions.includes(k));return(await Promise.all(p.map(async S=>{let y=await l(S);return{item:S,cmd:y}}))).filter(S=>S.cmd!==!1).map(S=>({item:S.item,cmd:S.cmd}))}s(h,"getFormatter");function g(k){return At.gen(function*(){yield*At.logInfo("formatting",{file:k});let p=yield*At.promise(()=>h(Hv.extname(k)));if(!p.length)return!1;for(let{item:f,cmd:S}of p){yield*At.logInfo("running",{command:S});let y=S.map(b=>b.replace("$FILE",k)),v=yield*B.directory,P=yield*t.run(Gv.make(y[0],y.slice(1),{cwd:v,env:f.environment,extendEnv:!0,stdin:"ignore",stdout:"ignore",stderr:"ignore"})).pipe(At.catch(b=>At.logError("failed to format file",{error:"spawn failed",command:S,...f.environment,file:k,cause:vo(b.cause??b)}).pipe(At.as(void 0))));P&&P.exitCode!==0&&(yield*At.logError("failed",{command:S,...f.environment}))}return!0})}s(g,"formatFile");let w=yield*e.get();if(!w.formatter)return yield*At.logInfo("all formatters are disabled"),yield*At.logInfo("init"),{formatters:u,isEnabled:m,formatFile:g};for(let k of Object.values(Yi))u[k.name]=k;if(w.formatter!==!0)for(let[k,p]of Object.entries(w.formatter)){let f=Yi[k];if(["ruff","uv"].includes(k)&&(w.formatter.ruff?.disabled||w.formatter.uv?.disabled)){delete u.ruff,delete u.uv;continue}if(p.disabled){delete u[k];continue}let S=Yv(f??{extensions:[]},p);u[k]={...S,name:k,extensions:S.extensions??[],enabled:f&&!S.command?f.enabled:async y=>S.command??!1}}return yield*At.logInfo("init"),{formatters:u,isEnabled:m,formatFile:g}})),r=At.fn("Format.init")(function*(){yield*B.get(n)}),i=At.fn("Format.status")(function*(){let{formatters:c,isEnabled:d}=yield*B.get(n),u=[];for(let l of Object.values(c)){let m=yield*At.promise(()=>d(l));u.push({name:l.name,extensions:l.extensions,enabled:m})}return u}),a=At.fn("Format.file")(function*(c){let{formatFile:d}=yield*B.get(n);return yield*d(c)});return Fn.of({init:r,status:i,file:a})})),Qv=ge.make({service:Fn,layer:Xv,deps:[De.node,nr.node,Me.node]});var Ko={};ae(Ko,{Service:()=>zr,ToolRegistry:()=>Ko,node:()=>VS,webSearchEnabled:()=>$f});import Zv from"path";import{Effect as Ki,Schema as eI}from"effect";var Cp=`Use this tool when you have completed the planning phase and are ready to exit plan agent.
1000
-
1001
- This tool will ask the user if they want to switch to build agent to start implementing the plan.
1002
-
1003
- Call this tool:
1004
- - After you have written a complete plan to the plan file
1005
- - After you have clarified any questions with the user
1006
- - When you are confident the plan is ready for implementation
1007
-
1008
- Do NOT call this tool:
1009
- - Before you have created or finalized the plan
1010
- - If you still have unanswered questions about the implementation
1011
- - If the user has indicated they want to continue planning
1012
- `;var tI=eI.Struct({}),Mp=We("plan_exit",Ki.gen(function*(){let e=yield*ce.Service,t=yield*to.Service,o=yield*yt.Service;return{description:Cp,parameters:tI,execute:s((n,r)=>Ki.gen(function*(){let i=yield*B.context,a=yield*e.get(r.sessionID),c=Zv.relative(i.worktree,ce.plan(a,i));(yield*t.ask({sessionID:r.sessionID,questions:[{question:`Plan at ${c} is complete. Would you like to switch to the build agent and start implementing?`,header:"Build Agent",custom:!1,options:[{label:"Yes",description:"Switch to build agent and start implementing the plan"},{label:"No",description:"Stay with plan agent to continue refining the plan"}]}],tool:r.callID?{messageID:r.messageID,callID:r.callID}:void 0}))[0]?.[0]==="No"&&(yield*new to.RejectedError);let l=(yield*e.messages({sessionID:r.sessionID}).pipe(Ki.orDie)).findLast(g=>g.info.role==="user"&&g.info.model),m=l?.info.role==="user"&&l.info.model?l.info.model:yield*o.defaultModel(),h={id:it.ascending(),sessionID:r.sessionID,role:"user",time:{created:Date.now()},agent:"build",model:m};return yield*e.updateMessage(h),yield*e.updatePart({id:Ce.ascending(),messageID:h.id,sessionID:r.sessionID,type:"text",text:`The plan at ${c} has been approved, you can now edit files. Execute the plan`,synthetic:!0}),{title:"Switching to build agent",output:"User approved switching to build agent. Wait for further instructions.",metadata:{}}}).pipe(Ki.orDie),"execute")}}));import{Effect as vc,Schema as Ic}from"effect";var Op=`Use this tool when you need to ask the user questions during execution. This allows you to:
1013
- 1. Gather user preferences or requirements
1014
- 2. Clarify ambiguous instructions
1015
- 3. Get decisions on implementation choices as you work
1016
- 4. Offer choices to the user about what direction to take.
1017
-
1018
- Usage notes:
1019
- - When \`custom\` is enabled (default), a "Type your own answer" option is added automatically; don't include "Other" or catch-all options
1020
- - Answers are returned as arrays of labels; set \`multiple: true\` to allow selecting more than one
1021
- - If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label
1022
- `;var oI=Ic.Struct({questions:Ic.mutable(Ic.Array(to.Prompt)).annotate({description:"Questions to ask"})}),Lp=We("question",vc.gen(function*(){let e=yield*to.Service;return{description:Op,parameters:oI,execute:s((t,o)=>vc.gen(function*(){let n=yield*e.ask({sessionID:o.sessionID,questions:t.questions,tool:o.callID?{messageID:o.messageID,callID:o.callID}:void 0}),r=t.questions.map((i,a)=>`"${i.question}"="${n[a]?.length?n[a].join(", "):"Unanswered"}"`).join(", ");return{title:`Asked ${t.questions.length} question${t.questions.length>1?"s":""}`,output:`User has answered your questions: ${r}. You can now continue with the user's answers in mind.`,metadata:{answers:n}}}).pipe(vc.orDie),"execute")}}));import*as mn from"path";import{Effect as jr,Schema as Nr,Semaphore as sI}from"effect";import{createTwoFilesPatch as kc,diffLines as iI}from"diff";var _p='Performs exact string replacements in files. \n\nUsage:\n- You must use your `Read` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file. \n- When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: line number + colon + space (e.g., `1: `). Everything after that space is the actual file content to match. Never include any part of the line number prefix in the oldString or newString.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\n- The edit will FAIL if `oldString` is not found in the file with an error "oldString not found in content".\n- The edit will FAIL if `oldString` is found multiple times in the file with an error "Found multiple matches for oldString. Provide more surrounding lines in oldString to identify the correct match." Either provide a larger string with more surrounding context to make it unique or use `replaceAll` to change every instance of `oldString`. \n- Use `replaceAll` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.\n';import Sc from"path";import{Effect as nI}from"effect";var qt=nI.fn("Tool.assertExternalDirectory")(function*(e,t,o){if(!t||o?.bypass)return!1;let n=yield*B.context,r=process.platform==="win32"?Se.normalizePath(t):t;if(fi(r,n))return!1;let a=(o?.kind??"file")==="directory"?r:Sc.dirname(r),c=process.platform==="win32"?Se.normalizePathPattern(Sc.join(a,"*")):Sc.join(a,"*").replaceAll("\\","/");return yield*e.ask({permission:"external_directory",patterns:[c],always:[c],metadata:{filepath:r,parentDir:a}}),!0});import{Effect as Up}from"effect";var jp=65279,rI=String.fromCharCode(jp);function yo(e){return e.charCodeAt(0)!==jp?{bom:!1,text:e}:{bom:!0,text:e.slice(1)}}s(yo,"split");function Qt(e,t){let o=yo(e).text;return t?rI+o:o}s(Qt,"join");var fn=Up.fn("Bom.readFile")(function*(e,t){return yo(new TextDecoder("utf-8",{ignoreBOM:!0}).decode(yield*e.readFile(t)))}),Bn=Up.fn("Bom.syncFile")(function*(e,t,o){let n=yield*fn(e,t);return n.bom===o||(yield*e.writeWithDirs(t,Qt(n.text,o))),n.text});function Fr(e){return e.replaceAll(`\r
1023
- `,`
1024
- `)}s(Fr,"normalizeLineEndings");function aI(e){return e.includes(`\r
1025
- `)?`\r
1026
- `:`
1027
- `}s(aI,"detectLineEnding");function Np(e,t){return t===`
1028
- `?e:e.replaceAll(`
1029
- `,`\r
1030
- `)}s(Np,"convertToLineEnding");var Fp=new Map;function cI(e){let t=Se.resolve(e),o=Fp.get(t);if(o)return o;let n=sI.makeUnsafe(1);return Fp.set(t,n),n}s(cI,"lock");var lI=Nr.Struct({filePath:Nr.String.annotate({description:"The absolute path to the file to modify"}),oldString:Nr.String.annotate({description:"The text to replace"}),newString:Nr.String.annotate({description:"The text to replace it with (must be different from oldString)"}),replaceAll:Nr.optional(Nr.Boolean).annotate({description:"Replace all occurrences of oldString (default false)"})}),Dc=We("edit",jr.gen(function*(){let e=yield*ut.Service,t=yield*Se.Service,o=yield*Xt.Service,n=yield*we.Service;return{description:_p,parameters:lI,execute:s((r,i)=>jr.gen(function*(){if(!r.filePath)throw new Error("filePath is required");if(r.oldString===r.newString)throw new Error("No changes to apply: oldString and newString are identical.");let a=yield*B.context,c=mn.isAbsolute(r.filePath)?r.filePath:mn.join(a.directory,r.filePath);yield*qt(i,c);let d="",u="",l="";yield*cI(c).withPermits(1)(jr.gen(function*(){if(r.oldString===""){if(yield*t.existsSafe(c))throw new Error("oldString cannot be empty when editing an existing file. Provide the exact text to replace, or use write for an intentional full-file replacement.");let _=yo(r.newString),W=_.bom;u="",l=_.text,d=Go(kc(c,c,u,l)),yield*i.ask({permission:"edit",patterns:[mn.relative(a.worktree,c)],always:["*"],metadata:{filepath:c,diff:d}}),yield*t.writeWithDirs(c,Qt(l,W)),(yield*o.file(c))&&(l=yield*Bn(t,c,W)),yield*n.publish(Sn.Event.Edited,{file:c}),yield*n.publish($o.Event.Updated,{file:c,event:"add"});return}let S=yield*t.stat(c).pipe(jr.catch(()=>jr.succeed(void 0)));if(!S)throw new Error(`File ${c} not found`);if(S.type==="Directory")throw new Error(`Path is a directory, not a file: ${c}`);let y=yield*fn(t,c);u=y.text;let v=aI(u),P=Np(Fr(r.oldString),v),b=Np(Fr(r.newString),v),T=yo(xI(u,P,b,r.replaceAll)),E=y.bom||T.bom;l=T.text,d=Go(kc(c,c,Fr(u),Fr(l))),yield*i.ask({permission:"edit",patterns:[mn.relative(a.worktree,c)],always:["*"],metadata:{filepath:c,diff:d}}),yield*t.writeWithDirs(c,Qt(l,E)),(yield*o.file(c))&&(l=yield*Bn(t,c,E)),yield*n.publish(Sn.Event.Edited,{file:c}),yield*n.publish($o.Event.Updated,{file:c,event:"change"}),d=Go(kc(c,c,Fr(u),Fr(l)))}).pipe(jr.orDie));let m=0,h=0;for(let S of iI(u,l))S.added&&(m+=S.count||0),S.removed&&(h+=S.count||0);let g={file:c,patch:d,additions:m,deletions:h};yield*i.metadata({metadata:{diff:d,filediff:g,diagnostics:{}}});let w="Edit applied successfully.";yield*e.touchFile(c,"document");let k=yield*e.diagnostics(),p=Se.normalizePath(c),f=ut.Diagnostic.report(c,k[p]??[]);return f&&(w+=`
1031
-
1032
- LSP errors detected in this file, please fix:
1033
- ${f}`),{metadata:{diagnostics:k,diff:d,filediff:g},title:`${mn.relative(a.worktree,c)}`,output:w}}),"execute")}})),Bp=.65,dI=.65;function $p(e,t){if(e===""||t==="")return Math.max(e.length,t.length);let o=Array.from({length:e.length+1},(n,r)=>Array.from({length:t.length+1},(i,a)=>r===0?a:a===0?r:0));for(let n=1;n<=e.length;n++)for(let r=1;r<=t.length;r++){let i=e[n-1]===t[r-1]?0:1;o[n][r]=Math.min(o[n-1][r]+1,o[n][r-1]+1,o[n-1][r-1]+i)}return o[e.length][t.length]}s($p,"levenshtein");var uI=s(function*(e,t){yield t},"SimpleReplacer"),pI=s(function*(e,t){let o=e.split(`
1034
- `),n=t.split(`
1035
- `);n[n.length-1]===""&&n.pop();for(let r=0;r<=o.length-n.length;r++){let i=!0;for(let a=0;a<n.length;a++){let c=o[r+a].trim(),d=n[a].trim();if(c!==d){i=!1;break}}if(i){let a=0;for(let d=0;d<r;d++)a+=o[d].length+1;let c=a;for(let d=0;d<n.length;d++)c+=o[r+d].length,d<n.length-1&&(c+=1);yield e.substring(a,c)}}},"LineTrimmedReplacer"),fI=s(function*(e,t){let o=e.split(`
1036
- `),n=t.split(`
1037
- `);if(n.length<3)return;n[n.length-1]===""&&n.pop();let r=n[0].trim(),i=n[n.length-1].trim(),a=n.length,c=Math.max(1,Math.floor(a*.25)),d=[];for(let m=0;m<o.length;m++)if(o[m].trim()===r){for(let h=m+2;h<o.length;h++)if(o[h].trim()===i){let g=h-m+1;Math.abs(g-a)<=c&&d.push({startLine:m,endLine:h});break}}if(d.length===0)return;if(d.length===1){let{startLine:m,endLine:h}=d[0],g=h-m+1,w=0,k=Math.min(a-2,g-2);if(k>0)for(let p=1;p<a-1&&p<g-1;p++){let f=o[m+p].trim(),S=n[p].trim(),y=Math.max(f.length,S.length);if(y===0)continue;let v=$p(f,S);if(w+=(1-v/y)/k,w>=Bp)break}else w=1;if(w>=Bp){let p=0;for(let S=0;S<m;S++)p+=o[S].length+1;let f=p;for(let S=m;S<=h;S++)f+=o[S].length,S<h&&(f+=1);yield e.substring(p,f)}return}let u=null,l=-1;for(let m of d){let{startLine:h,endLine:g}=m,w=g-h+1,k=0,p=Math.min(a-2,w-2);if(p>0){for(let f=1;f<a-1&&f<w-1;f++){let S=o[h+f].trim(),y=n[f].trim(),v=Math.max(S.length,y.length);if(v===0)continue;let P=$p(S,y);k+=1-P/v}k/=p}else k=1;k>l&&(l=k,u=m)}if(l>=dI&&u){let{startLine:m,endLine:h}=u,g=0;for(let k=0;k<m;k++)g+=o[k].length+1;let w=g;for(let k=m;k<=h;k++)w+=o[k].length,k<h&&(w+=1);yield e.substring(g,w)}},"BlockAnchorReplacer"),mI=s(function*(e,t){let o=s(a=>a.replace(/\s+/g," ").trim(),"normalizeWhitespace"),n=o(t),r=e.split(`
1038
- `);for(let a=0;a<r.length;a++){let c=r[a];if(o(c)===n)yield c;else if(o(c).includes(n)){let u=t.trim().split(/\s+/);if(u.length>0){let l=u.map(m=>m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\s+");try{let m=new RegExp(l),h=c.match(m);h&&(yield h[0])}catch{}}}}let i=t.split(`
1039
- `);if(i.length>1)for(let a=0;a<=r.length-i.length;a++){let c=r.slice(a,a+i.length);o(c.join(`
1040
- `))===n&&(yield c.join(`
1041
- `))}},"WhitespaceNormalizedReplacer"),hI=s(function*(e,t){let o=s(a=>{let c=a.split(`
1042
- `),d=c.filter(l=>l.trim().length>0);if(d.length===0)return a;let u=Math.min(...d.map(l=>{let m=l.match(/^(\s*)/);return m?m[1].length:0}));return c.map(l=>l.trim().length===0?l:l.slice(u)).join(`
1043
- `)},"removeIndentation"),n=o(t),r=e.split(`
1044
- `),i=t.split(`
1045
- `);for(let a=0;a<=r.length-i.length;a++){let c=r.slice(a,a+i.length).join(`
1046
- `);o(c)===n&&(yield c)}},"IndentationFlexibleReplacer"),gI=s(function*(e,t){let o=s(a=>a.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g,(c,d)=>{switch(d){case"n":return`
1047
- `;case"t":return" ";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case`
1048
- `:return`
1049
- `;case"$":return"$";default:return c}}),"unescapeString"),n=o(t);e.includes(n)&&(yield n);let r=e.split(`
1050
- `),i=n.split(`
1051
- `);for(let a=0;a<=r.length-i.length;a++){let c=r.slice(a,a+i.length).join(`
1052
- `);o(c)===n&&(yield c)}},"EscapeNormalizedReplacer"),yI=s(function*(e,t){let o=0;for(;;){let n=e.indexOf(t,o);if(n===-1)break;yield t,o=n+t.length}},"MultiOccurrenceReplacer"),wI=s(function*(e,t){let o=t.trim();if(o===t)return;e.includes(o)&&(yield o);let n=e.split(`
1053
- `),r=t.split(`
1054
- `);for(let i=0;i<=n.length-r.length;i++){let a=n.slice(i,i+r.length).join(`
1055
- `);a.trim()===o&&(yield a)}},"TrimmedBoundaryReplacer"),bI=s(function*(e,t){let o=t.split(`
1056
- `);if(o.length<3)return;o[o.length-1]===""&&o.pop();let n=e.split(`
1057
- `),r=o[0].trim(),i=o[o.length-1].trim();for(let a=0;a<n.length;a++)if(n[a].trim()===r){for(let c=a+2;c<n.length;c++)if(n[c].trim()===i){let d=n.slice(a,c+1),u=d.join(`
1058
- `);if(d.length===o.length){let l=0,m=0;for(let h=1;h<d.length-1;h++){let g=d[h].trim(),w=o[h].trim();(g.length>0||w.length>0)&&(m++,g===w&&l++)}if(m===0||l/m>=.5){yield u;break}}break}}},"ContextAwareReplacer");function Go(e){let t=e.split(`
1059
- `),o=t.filter(i=>(i.startsWith("+")||i.startsWith("-")||i.startsWith(" "))&&!i.startsWith("---")&&!i.startsWith("+++"));if(o.length===0)return e;let n=1/0;for(let i of o){let a=i.slice(1);if(a.trim().length>0){let c=a.match(/^(\s*)/);c&&(n=Math.min(n,c[1].length))}}return n===1/0||n===0?e:t.map(i=>{if((i.startsWith("+")||i.startsWith("-")||i.startsWith(" "))&&!i.startsWith("---")&&!i.startsWith("+++")){let a=i[0],c=i.slice(1);return a+c.slice(n)}return i}).join(`
1060
- `)}s(Go,"trimDiff");function xI(e,t,o,n=!1){if(t===o)throw new Error("No changes to apply: oldString and newString are identical.");if(t==="")throw new Error("oldString cannot be empty when editing an existing file. Provide the exact text to replace, or use write for an intentional full-file replacement.");let r=!0;for(let i of[uI,pI,fI,mI,hI,gI,wI,bI,yI])for(let a of i(e,t)){let c=e.indexOf(a);if(c===-1)continue;if(r=!1,vI(a,t))throw new Error("Refusing replacement because the matched span is much larger than oldString. Re-read the file and provide the full exact oldString for the intended replacement.");if(n)return e.replaceAll(a,o);let d=e.lastIndexOf(a);if(c===d)return e.substring(0,c)+o+e.substring(c+a.length)}throw r?new Error("Could not find oldString in the file. It must match exactly, including whitespace, indentation, and line endings."):new Error("Found multiple matches for oldString. Provide more surrounding context to make the match unique.")}s(xI,"replace");function vI(e,t){let o=t.split(`
1061
- `).length;return e.split(`
1062
- `).length>=Math.max(o+3,o*2)?!0:o===1?!1:e.trim().length>Math.max(t.trim().length+500,t.trim().length*4)}s(vI,"isDisproportionateMatch");import Xi from"path";import{Effect as Cs,Schema as Qi}from"effect";var Wp=`- Fast file pattern matching tool that works with any codebase size
1063
- - Supports glob patterns like "**/*.js" or "src/**/*.ts"
1064
- - Returns matching file paths
1065
- - Use this tool when you need to find files by name patterns
1066
- - When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the Task tool instead
1067
- - You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.
1068
- `;var II=Qi.Struct({pattern:Qi.String.annotate({description:"The glob pattern to match files against"}),path:Qi.optional(Qi.String).annotate({description:'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.'})}),qp=We("glob",Cs.gen(function*(){let e=yield*Se.Service,t=yield*on.Service;return{description:Wp,parameters:II,execute:s((o,n)=>Cs.gen(function*(){let r=yield*B.context;yield*n.ask({permission:"glob",patterns:[o.pattern],always:["*"],metadata:{pattern:o.pattern,path:o.path}});let i=o.path??r.directory;if(i=Xi.isAbsolute(i)?i:Xi.resolve(r.directory,i),(yield*e.stat(i).pipe(Cs.catch(()=>Cs.succeed(void 0))))?.type==="File")throw new Error(`glob path must be a directory: ${i}`);yield*qt(n,i,{bypass:!1,kind:"directory"});let c=100,d=yield*t.glob({cwd:i,pattern:o.pattern,limit:c}),u=d.length===c,l=[];return d.length===0&&l.push("No files found"),d.length>0&&(l.push(...d.map(m=>Xi.resolve(i,m.path))),u&&(l.push(""),l.push(`(Results are truncated: showing first ${c} results. Consider using a more specific path or pattern.)`))),{title:Xi.relative(r.worktree,i),metadata:{count:d.length,truncated:u},output:l.join(`
1069
- `)}}).pipe(Cs.orDie),"execute")}}));import Ms from"path";import{Effect as $n,Schema as Br}from"effect";var Vp=`- Fast content search tool that works with any codebase size
1070
- - Searches file contents using regular expressions
1071
- - Supports full regex syntax (eg. "log.*Error", "function\\s+\\w+", etc.)
1072
- - Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")
1073
- - Returns file paths and line numbers with matching lines
1074
- - Use this tool when you need to find files containing specific patterns
1075
- - If you need to identify/count the number of matches within files, use the Bash tool with \`rg\` (ripgrep) directly. Do NOT use \`grep\`.
1076
- - When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the Task tool instead
1077
- `;var SI=Br.Struct({pattern:Br.String.annotate({description:"The regex pattern to search for in file contents"}),path:Br.optional(Br.String).annotate({description:"The directory to search in. Defaults to the current working directory."}),include:Br.optional(Br.String).annotate({description:'File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")'})}),zp=We("grep",$n.gen(function*(){let e=yield*Se.Service,t=yield*on.Service;return{description:Vp,parameters:SI,execute:s((o,n)=>$n.gen(function*(){let r={title:o.pattern,metadata:{matches:0,truncated:!1},output:"No files found"};if(!o.pattern)throw new Error("pattern is required");yield*n.ask({permission:"grep",patterns:[o.pattern],always:["*"],metadata:{pattern:o.pattern,path:o.path,include:o.include}});let i=yield*B.context,a=Ms.isAbsolute(o.path??i.directory)?o.path??i.directory:Ms.join(i.directory,o.path??"."),c=yield*e.stat(a).pipe($n.catch(()=>$n.succeed(void 0)));yield*qt(n,a,{bypass:!1,kind:c?.type==="Directory"?"directory":"file"});let d=Se.resolve(a),l=(yield*e.stat(d).pipe($n.catch(()=>$n.succeed(void 0))))?.type==="Directory"?d:Ms.dirname(d),m=yield*t.grep({cwd:l,pattern:o.pattern,include:o.include,limit:100});if(m.length===0)return r;let h=m.map(v=>({path:Ms.resolve(c?.type==="Directory"?a:Ms.dirname(a),v.entry.path),line:v.line,text:v.text})),g=100,w=h.length===g,k=h;if(k.length===0)return r;let p=h.length,f=w||m.length===g,S=[`Found ${p} matches${f?" (more matches available)":""}`],y="";for(let v of k)y!==v.path&&(y!==""&&S.push(""),y=v.path,S.push(`${v.path}:`)),S.push(` Line ${v.line}: ${v.text}`);return w&&(S.push(""),S.push("(Results truncated. Consider using a more specific path or pattern.)")),{title:o.pattern,metadata:{matches:p,truncated:w},output:S.join(`
1078
- `)}}).pipe($n.orDie),"execute")}}));import{Effect as ze,Option as kI,Schema as Os,Scope as DI,Stream as Ec}from"effect";import*as _t from"path";var Gp=`Read a file or directory from the local filesystem. If the path does not exist, an error is returned.
1079
-
1080
- Usage:
1081
- - The filePath parameter should be an absolute path.
1082
- - By default, this tool returns up to 2000 lines from the start of the file.
1083
- - The offset parameter is the line number to start from (1-indexed).
1084
- - To read later sections, call this tool again with a larger offset.
1085
- - Use the grep tool to find specific content in large files or files with long lines.
1086
- - If you are unsure of the correct file path, use the glob tool to look up filenames by glob pattern.
1087
- - Contents are returned with each line prefixed by its line number as \`<line>: <content>\`. For example, if a file has contents "foo\\n", you will receive "1: foo\\n". For directories, entries are returned one per line (without line numbers) with a trailing \`/\` for subdirectories.
1088
- - Any line longer than 2000 characters is truncated.
1089
- - Call this tool in parallel when you know there are multiple files you want to read.
1090
- - Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.
1091
- - This tool can read image files and PDFs and return them as file attachments.
1092
- `;var Hp=2e3,Tc=2e3,EI=`... (line truncated to ${Tc} chars)`,Yp=50*1024,TI=`${Yp/1024} KB`,PI=4096,RI=new Set(["image/jpeg","image/png","image/gif","image/webp"]),Zi=class extends Os.TaggedErrorClass()("ReadStop",{}){static{s(this,"ReadStop")}},AI=Os.Struct({filePath:Os.String.annotate({description:"The absolute path to the file or directory to read"}),offset:Os.optional(bo).annotate({description:"The line number to start reading from (1-indexed)"}),limit:Os.optional(bo).annotate({description:"The maximum number of lines to read (defaults to 2000)"})}),Kp=We("read",ze.gen(function*(){let e=yield*Se.Service,t=yield*Lo.Service,o=yield*ut.Service,n=yield*DI.Scope,r=ze.fn("ReadTool.miss")(function*(m){let h=_t.dirname(m),g=_t.basename(m),w=yield*e.readDirectory(h).pipe(ze.map(k=>k.filter(p=>p.toLowerCase().includes(g.toLowerCase())||g.toLowerCase().includes(p.toLowerCase())).map(p=>_t.join(h,p)).slice(0,3)),ze.catch(()=>ze.succeed([])));return w.length>0?yield*ze.fail(new Error(`File not found: ${m}
1093
-
1094
- Did you mean one of these?
1095
- ${w.join(`
1096
- `)}`)):yield*ze.fail(new Error(`File not found: ${m}`))}),i=ze.fn("ReadTool.list")(function*(m){let h=yield*e.readDirectoryEntries(m);return yield*ze.forEach(h,ze.fnUntraced(function*(g){return g.type==="directory"?g.name+"/":g.type!=="symlink"?g.name:(yield*e.stat(_t.join(m,g.name)).pipe(ze.catch(()=>ze.void)))?.type==="Directory"?g.name+"/":g.name}),{concurrency:"unbounded"}).pipe(ze.map(g=>g.sort((w,k)=>w.localeCompare(k))))}),a=ze.fn("ReadTool.warm")(function*(m){yield*o.touchFile(m).pipe(ze.ignoreCause,ze.forkIn(n))}),c=ze.fn("ReadTool.readSample")(function*(m,h,g){return h===0?new Uint8Array:yield*ze.scoped(ze.gen(function*(){let w=yield*e.open(m,{flag:"r"});return kI.getOrElse(yield*w.readAlloc(Math.min(g,h)),()=>new Uint8Array)}))}),d=ze.fn("ReadTool.lines")(function*(m,h){let g=h.offset-1,w=[],k={bytes:0,count:0,cut:!1,more:!1,done:!1},p=new TextDecoder("utf-8");return yield*e.stream(m).pipe(Ec.map(f=>p.decode(f,{stream:!0})),Ec.splitLines,Ec.runForEach(f=>ze.gen(function*(){if(k.done)return yield*new Zi;if(k.count+=1,k.count<=g)return;if(w.length>=h.limit){k.more=!0;return}let S=f.length>Tc?f.substring(0,Tc)+EI:f,y=Buffer.byteLength(S,"utf-8")+(w.length>0?1:0);if(k.bytes+y<=Yp){w.push(S),k.bytes+=y;return}return k.cut=!0,k.more=!0,k.done=!0,yield*new Zi})),ze.catchTag("ReadStop",()=>ze.void)),{raw:w,count:k.count,cut:k.cut,more:k.more,offset:h.offset}}),u=s((m,h)=>{switch(_t.extname(m).toLowerCase()){case".zip":case".tar":case".gz":case".exe":case".dll":case".so":case".class":case".jar":case".war":case".7z":case".doc":case".docx":case".xls":case".xlsx":case".ppt":case".pptx":case".odt":case".ods":case".odp":case".bin":case".dat":case".obj":case".o":case".a":case".lib":case".wasm":case".pyc":case".pyo":return!0}if(h.length===0)return!1;let w=0;for(let k=0;k<h.length;k++){if(h[k]===0)return!0;(h[k]<9||h[k]>13&&h[k]<32)&&w++}return w/h.length>.3},"isBinaryFile"),l=ze.fn("ReadTool.execute")(function*(m,h){let g=yield*B.context,w=m.filePath;_t.isAbsolute(w)||(w=_t.resolve(g.directory,w)),process.platform==="win32"&&(w=Se.normalizePath(w));let k=_t.relative(g.worktree,w),p=yield*e.stat(w).pipe(ze.catchIf(_=>"reason"in _&&_.reason._tag==="NotFound",()=>ze.succeed(void 0)));if(yield*qt(h,w,{bypass:!!h.extra?.bypassCwdCheck,kind:p?.type==="Directory"?"directory":"file"}),yield*h.ask({permission:"read",patterns:[_t.relative(g.worktree,w)],always:["*"],metadata:{}}),!p)return yield*r(w);if(p.type==="Directory"){let _=yield*i(w),W=m.limit??Hp,ie=m.offset||1,M=ie-1,$=_.slice(M,M+W),x=M+$.length<_.length;return{title:k,output:[`<path>${w}</path>`,"<type>directory</type>","<entries>",$.join(`
1097
- `),x?`
1098
- (Showing ${$.length} of ${_.length} entries. Use 'offset' parameter to read beyond entry ${ie+$.length})`:`
1099
- (${_.length} entries)`,"</entries>"].join(`
1100
- `),metadata:{preview:$.slice(0,20).join(`
1101
- `),truncated:x,loaded:[],display:{type:"directory",path:w,entries:$,offset:ie,totalEntries:_.length,truncated:x}}}}let f=yield*t.resolve(h.messages,w,h.messageID),S=yield*c(w,Number(p.size),PI),y=Xl(S,Se.mimeType(w));if(RI.has(y)||_a(y)){let _=yield*e.readFile(w),W=_a(y)?"PDF read successfully":"Image read successfully";return{title:k,output:W,metadata:{preview:W,truncated:!1,loaded:f.map(ie=>ie.filepath)},attachments:[{type:"file",mime:y,url:`data:${y};base64,${Buffer.from(_).toString("base64")}`}]}}if(u(w,S))return yield*ze.fail(new Error(`Cannot read binary file: ${w}`));let P=yield*d(w,{limit:m.limit??Hp,offset:m.offset||1});if(P.count<P.offset&&!(P.count===0&&P.offset===1))return yield*ze.fail(new Error(`Offset ${P.offset} is out of range for this file (${P.count} lines)`));let b=[`<path>${w}</path>`,"<type>file</type>",`<content>
1102
- `].join(`
1103
- `);b+=P.raw.map((_,W)=>`${W+P.offset}: ${_}`).join(`
1104
- `);let T=P.offset+P.raw.length-1,E=T+1,j=P.more||P.cut;return P.cut?b+=`
1105
-
1106
- (Output capped at ${TI}. Showing lines ${P.offset}-${T}. Use offset=${E} to continue.)`:P.more?b+=`
1107
-
1108
- (Showing lines ${P.offset}-${T} of ${P.count}. Use offset=${E} to continue.)`:b+=`
1109
-
1110
- (End of file - total ${P.count} lines)`,b+=`
1111
- </content>`,yield*a(w),f.length>0&&(b+=`
1112
-
1113
- <system-reminder>
1114
- ${f.map(_=>_.content).join(`
1115
-
1116
- `)}
1117
- </system-reminder>`),{title:k,output:b,metadata:{preview:P.raw.slice(0,20).join(`
1118
- `),truncated:j,loaded:f.map(_=>_.filepath),display:{type:"file",path:w,text:P.raw.join(`
1119
- `),lineStart:P.offset,lineEnd:T,totalLines:P.count,truncated:j}}}});return{description:Gp,parameters:AI,execute:s((m,h)=>l(m,h).pipe(ze.orDie),"execute")}}));var Pc=`WHEN TO USE: research and exploration (synchronous, returns findings directly). For implementation work \u2014 file edits, feature changes, bug fixes \u2014 spawn a coder via subagent_operations spawn instead.
1120
-
1121
- Launch a new agent to handle complex, multistep tasks autonomously.
1122
-
1123
- When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
1124
-
1125
- When to use the Task tool:
1126
- - For research and exploration: codebase questions, finding usages, understanding how a system works. The agent runs synchronously and returns findings directly \u2014 use this when you need information before deciding what to do, not for the doing itself.
1127
-
1128
- When NOT to use the Task tool:
1129
- - If you want to read a specific file path, use the Read or Glob tool instead of the Task tool, to find the match more quickly
1130
- - If you are searching for a specific class definition like "class Foo", use the Grep tool instead, to find the match more quickly
1131
- - If you are searching for code within a specific file or set of 2-3 files, use the Read tool instead of the Task tool, to find the match more quickly
1132
- - If no available agent is a good fit for the task, use other tools directly
1133
-
1134
-
1135
- Usage notes:
1136
- 1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
1137
- 2. Once you have delegated work to an agent, do not duplicate that work yourself. Continue with non-overlapping tasks, or wait for the result. For background tasks, you will be notified automatically when the result is ready.
1138
- 3. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result. The output includes a task_id you can reuse later to continue the same subagent session.
1139
- 4. Each agent invocation starts with a fresh context unless you provide task_id to resume the same subagent session (which continues with its previous messages and tool outputs). When starting fresh, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
1140
- 5. The agent's outputs should generally be trusted
1141
- 6. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands).
1142
- 7. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
1143
- `;var Wn={};ae(Wn,{ToolJsonSchema:()=>Wn,fromSchema:()=>Xp,fromTool:()=>OI});import{JsonSchema as CI,Schema as MI}from"effect";var Jp=new WeakMap;function Xp(e){let t=Jp.get(e);if(t)return t;let o=MI.toJsonSchemaDocument(e,{additionalProperties:!0}),n=Ho({$schema:CI.META_SCHEMA_URI_DRAFT_2020_12,...o.schema,...Object.keys(o.definitions).length>0?{$defs:o.definitions}:{}}),r=NI(ea(n));if(!LI(r))throw new Error("tool JSON Schema helper produced a non-schema value");return Jp.set(e,r),r}s(Xp,"fromSchema");function OI(e){return e.jsonSchema??Xp(e.parameters)}s(OI,"fromTool");function Ho(e,t={}){if(Array.isArray(e))return e.map(r=>Ho(r));if(!Vt(e))return e;let o=Array.isArray(e.required)?new Set(e.required.filter(r=>typeof r=="string")):void 0,n=Object.fromEntries(Object.entries(e).map(([r,i])=>[r,r==="properties"&&Vt(i)?Object.fromEntries(Object.entries(i).map(([a,c])=>[a,Ho(c,{stripNull:!o?.has(a)})])):Ho(i)]));if(n.additionalProperties===!0&&delete n.additionalProperties,t.stripNull&&Array.isArray(n.anyOf)){let r=n.anyOf.filter(i=>!Vt(i)||i.type!=="null");if(r.length!==n.anyOf.length)return Ho({...n,anyOf:r})}if(Array.isArray(n.anyOf)){let r=n.anyOf,i=r.find(c=>Vt(c)&&c.type==="number"),a=r.filter(c=>Vt(c)&&Array.isArray(c.enum)&&c.enum.every(d=>_I(d)));if(i&&a.length===r.length-1){let{anyOf:c,...d}=n;return Ho({...i,...d})}if(UI(r)){let{anyOf:c,...d}=n;return Ho({type:"object",properties:{},...d})}if(r.length===1&&Vt(r[0])){let{anyOf:c,...d}=n;return Ho({...r[0],...d})}}if(Array.isArray(n.allOf)&&n.allOf.every(Vt)&&jI(n.allOf,n)){let{allOf:r,...i}=n;return Ho({...Object.assign({},...r),...i})}return n.type==="integer"&&n.maximum===void 0?{minimum:Number.MIN_SAFE_INTEGER,...n,maximum:Number.MAX_SAFE_INTEGER}:n}s(Ho,"normalize");function Vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Vt,"isRecord");function LI(e){return typeof e=="boolean"||Vt(e)}s(LI,"isJsonSchema");function _I(e){return e==="NaN"||e==="Infinity"||e==="-Infinity"}s(_I,"isNonFiniteNumber");function UI(e){return e.length===2&&e.some(t=>Vt(t)&&t.type==="object"&&t.properties===void 0)&&e.some(t=>Vt(t)&&t.type==="array"&&t.items===void 0)}s(UI,"isEmptyStructUnion");function jI(e,t){let o=new Set(Object.keys(t).filter(n=>n!=="allOf"));return e.every(n=>Object.keys(n).every(r=>o.has(r)?!1:(o.add(r),!0)))}s(jI,"canFlattenAllOf");function ea(e,t,o=new Set){if(Array.isArray(e))return e.map(r=>ea(r,t,o));if(!Vt(e))return e;let n=t??(Vt(e.$defs)?e.$defs:void 0);if(typeof e.$ref=="string"&&n){let r=e.$ref.match(/^#\/\$defs\/(.+)$/)?.[1]??e.$ref.match(/^#\/definitions\/(.+)$/)?.[1];if(r&&!o.has(r)){let i=n[r];if(i){let{$ref:a,...c}=e;return ea({...Vt(i)?i:{},...c},n,new Set(o).add(r))}}}return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,ea(i,n,o)]))}s(ea,"inlineLocalReferences");function NI(e){if(!Vt(e)||Rc(e))return e;let{$defs:t,definitions:o,...n}=e;return n}s(NI,"dropDefinitionsIfResolved");function Rc(e){return Array.isArray(e)?e.some(Rc):Vt(e)?typeof e.$ref=="string"&&(e.$ref.startsWith("#/$defs/")||e.$ref.startsWith("#/definitions/"))?!0:Object.values(e).some(Rc):!1}s(Rc,"hasLocalReference");function Qp(e){let t=e.subagent.permission.some(n=>n.permission==="task"),o=e.subagent.permission.some(n=>n.permission==="todowrite");return[...e.parentSessionPermission.filter(n=>n.permission==="external_directory"||n.action==="deny"),...o?[]:[{permission:"todowrite",pattern:"*",action:"deny"}],...t?[]:[{permission:"task",pattern:"*",action:"deny"}]]}s(Qp,"deriveSubagentSessionPermission");import{Effect as Oe,Exit as FI,Schema as Do,Scope as BI}from"effect";var Ls="task",$I=["Background mode: background=true launches the subagent asynchronously and returns immediately.","Foreground is the default; use it when you need the result before continuing.","Use background only for independent work that can run while you continue elsewhere.","You will be notified automatically when it finishes."].join(" "),WI=["The task is working in the background. You will be notified automatically when it finishes.","DO NOT sleep, poll for progress, ask the task for status, or duplicate this task's work \u2014 avoid working with the same files or topics it is using.","Work on non-overlapping tasks, or briefly tell the user what you launched and end your response."].join(`
1144
- `),qI=["Additional context sent to the running background task.","The task is still working in the background. You will be notified automatically when it finishes.","DO NOT sleep, poll for progress, ask the task for status, or duplicate this task's work \u2014 avoid working with the same files or topics it is using.","Work on non-overlapping tasks, or briefly tell the user what you sent and end your response."].join(`
1145
- `),Zp={description:Do.String.annotate({description:"A short (3-5 words) description of the task"}),prompt:Do.String.annotate({description:"The task for the agent to perform"}),subagent_type:Do.String.annotate({description:"The type of specialized agent to use for this task"}),task_id:Do.optional(Do.String).annotate({description:"This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)"}),command:Do.optional(Do.String).annotate({description:"The command that triggered this task"})},VI=Do.Struct(Zp),zI=Do.Struct({...Zp,background:Do.optional(Do.Boolean).annotate({description:"Run the agent in the background. You will be notified when it completes. DO NOT sleep, poll, or proactively check on its progress"})});function ta(e){let t=e.state==="error"?"task_error":"task_result";return[`<task id="${e.sessionID}" state="${e.state}">`,...e.summary?[`<summary>${e.summary}</summary>`]:[],`<${t}>`,e.text,`</${t}>`,"</task>"].join(`
1146
- `)}s(ta,"renderOutput");var qn=We(Ls,Oe.gen(function*(){let e=yield*Nt.Service,t=yield*Tn.Service,o=yield*De.Service,n=yield*ce.Service,r=yield*BI.Scope,i=yield*Me.Service,a=yield*Xe.Service,c=Oe.fn("TaskTool.execute")(function*(d,u){let l=yield*o.get(),m=d.background===!0;if(m&&!i.experimentalBackgroundSubagents)return yield*Oe.fail(new Error("Background subagents require OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true"));let h=yield*n.get(u.sessionID),g=h,w=0;for(;g.parentID;)w++,g=yield*n.get(g.parentID);if(w>=(l.subagent_depth??1))return yield*Oe.fail(new Error(`Subagent depth limit reached (${l.subagent_depth??1}). Increase "subagent_depth" to allow nested subagents.`));u.extra?.bypassAgentCheck||(yield*u.ask({permission:Ls,patterns:[d.subagent_type],always:["*"],metadata:{description:d.description,subagent_type:d.subagent_type}}));let k=yield*e.get(d.subagent_type);if(!k)return yield*Oe.fail(new Error(`Unknown agent type: ${d.subagent_type} is not a valid agent type`));let p=d.task_id?yield*n.get(Et.make(d.task_id)).pipe(Oe.catchCause(()=>Oe.succeed(void 0))):void 0,f=Qp({parentSessionPermission:h.permission??[],subagent:k}),S=[...k.permission.some(A=>A.permission==="todowrite")?[]:[{permission:"todowrite",pattern:"*",action:"deny"}],...k.permission.some(A=>A.permission===Ls)?[]:[{permission:Ls,pattern:"*",action:"deny"}],...l.experimental?.primary_tools?.map(A=>({permission:A,pattern:"*",action:"deny"}))??[]],y=p??(yield*n.create({parentID:u.sessionID,title:d.description+` (@${k.name} subagent)`,agent:k.name,metadata:{agentType:k.name,spawnedBy:"task-tool",callerSessionId:u.sessionID},permission:[...f,...S.filter(A=>!f.some(O=>O.permission===A.permission&&O.pattern===A.pattern&&O.action===A.action))]})),v=yield*Qe.get({sessionID:u.sessionID,messageID:u.messageID}).pipe(Oe.provideService(Xe.Service,a),Oe.orDie);if(v.info.role!=="assistant")return yield*Oe.fail(new Error("Not an assistant message"));let P=v.info.variant,b=k.model??{modelID:v.info.modelID,providerID:v.info.providerID},T={parentSessionId:u.sessionID,sessionId:y.id,model:b,...m?{background:!0}:{}};yield*u.metadata({title:d.description,metadata:T});let E=u.extra?.promptOps;if(!E)return yield*Oe.fail(new Error("TaskTool requires promptOps in ctx.extra"));let j=Oe.fn("TaskTool.runTask")(function*(){let A=yield*E.resolvePromptParts(d.prompt),O=yield*E.prompt({messageID:it.ascending(),sessionID:y.id,model:{modelID:b.modelID,providerID:b.providerID},variant:k.model?void 0:P,agent:k.name,parts:A});if(O.info.role==="assistant"&&O.info.error){let U="message"in O.info.error.data&&typeof O.info.error.data.message=="string"?O.info.error.data.message:O.info.error.name;return yield*Oe.fail(new Error(`Subagent failed (task_id: ${y.id}): ${U}`))}let F=O.parts.findLast(U=>U.type==="tool"&&U.state.status==="error");return F?.type==="tool"&&F.state.status==="error"?yield*Oe.fail(new Error(`Subagent failed (task_id: ${y.id}): ${F.state.error}`)):O.parts.findLast(U=>U.type==="text")?.text??""}),_=Oe.fn("TaskTool.injectBackgroundResult")(function*(A,O){let F=yield*n.get(u.sessionID);yield*E.prompt({sessionID:u.sessionID,agent:F.agent??u.agent,variant:P,parts:[{type:"text",synthetic:!0,text:ta({sessionID:y.id,state:A,summary:A==="completed"?`Background task completed: ${d.description}`:`Background task failed: ${d.description}`,text:O})}]}).pipe(Oe.ignore,Oe.forkIn(r,{startImmediately:!0}))}),W=Oe.fn("TaskTool.notifyBackgroundResult")(function*(A){yield*t.wait({id:A}).pipe(Oe.flatMap(O=>O.info?.status==="completed"?_("completed",O.info.output??""):O.info?.status==="error"?_("error",O.info.error??""):Oe.void),Oe.forkIn(r,{startImmediately:!0}))});if(yield*t.extend({id:y.id,run:j()}))return{title:d.description,metadata:{...T,background:!0,jobId:y.id},output:ta({sessionID:y.id,state:"running",summary:"Background task updated",text:qI})};let ie=yield*t.start({id:y.id,type:Ls,title:d.description,metadata:T,onPromote:Oe.all([u.metadata({title:d.description,metadata:{...T,background:!0,jobId:y.id}}),W(y.id)]),run:j().pipe(Oe.onInterrupt(()=>E.cancel(y.id)))});function M(){return{title:d.description,metadata:{...T,background:!0,jobId:ie.id},output:ta({sessionID:y.id,state:"running",summary:"Background task started",text:WI})}}if(s(M,"backgroundResult"),m)return yield*W(ie.id),M();let $=yield*Yt.make(),x=E.cancel(y.id);function R(){$.fork(x)}return s(R,"onAbort"),yield*Oe.acquireUseRelease(Oe.sync(()=>{u.abort.addEventListener("abort",R)}),()=>Oe.gen(function*(){let A=yield*Oe.raceFirst(t.wait({id:y.id}).pipe(Oe.map(O=>O.info)),t.waitForPromotion(y.id));return A?.metadata?.background===!0?M():A?.status==="error"?yield*Oe.fail(new Error(A.error??"Task failed")):A?.status==="cancelled"?yield*Oe.fail(new Error("Task cancelled")):{title:d.description,metadata:T,output:ta({sessionID:y.id,state:"completed",text:A?.output??""})}}),(A,O)=>Oe.gen(function*(){FI.hasInterrupts(O)&&(yield*Oe.all([x,t.cancel(y.id)],{discard:!0}))}).pipe(Oe.ensuring(Oe.sync(()=>{u.abort.removeEventListener("abort",R)}))))});return{description:i.experimentalBackgroundSubagents?[Pc,$I].join(`
1147
-
1148
- `):Pc,parameters:zI,jsonSchema:i.experimentalBackgroundSubagents?void 0:Wn.fromSchema(VI),execute:s((d,u)=>c(d,u).pipe(Oe.orDie),"execute")}}));import{Effect as tf,Schema as Ac}from"effect";var ef=`Create and maintain a structured task list for the current coding session. Tracks progress, organizes multi-step work, and surfaces status to the user.
1149
-
1150
- ## When to use
1151
- Use proactively when:
1152
- - The task requires 3+ distinct steps or actions (not just 3 tool calls for a single conceptual step)
1153
- - The work is non-trivial and benefits from planning
1154
- - The user provides multiple tasks (numbered or comma-separated) or explicitly asks for a todo list
1155
- - New instructions arrive - capture them as todos
1156
- - You start a task - mark it \`in_progress\` (only one at a time) before working
1157
- - You finish a task - mark it \`completed\` and add any follow-ups discovered during the work
1158
-
1159
- ## When NOT to use
1160
- Skip when:
1161
- - The work is a single, straightforward task (or <3 trivial steps)
1162
- - The request is purely informational or conversational
1163
- - Tracking adds no organizational value
1164
-
1165
- ## States
1166
- - \`pending\` - not started
1167
- - \`in_progress\` - actively working (exactly ONE at a time)
1168
- - \`completed\` - finished successfully
1169
- - \`cancelled\` - no longer needed
1170
-
1171
- ## Rules
1172
- - Update status in real time; don't batch completions
1173
- - Mark \`completed\` only after the required work is actually done, including any required verification. Never based on intent.
1174
- - Keep exactly one \`in_progress\` while work remains
1175
- - If blocked or partial, keep it \`in_progress\` and add a follow-up todo describing the blocker
1176
- - Preserve user-provided commands verbatim (flags, args, order)
1177
- - Items should be specific and actionable; break large work into smaller steps
1178
-
1179
- ## Examples
1180
-
1181
- Use it:
1182
- - "Add a dark mode toggle and run the tests" -> multi-step feature + explicit verification
1183
- - "Rename getCwd -> getCurrentWorkingDirectory across the repo" -> grep reveals 15 occurrences in 8 files
1184
- - "Implement registration, catalog, cart, checkout" -> multiple complex features
1185
-
1186
- Skip it:
1187
- - "How do I print Hello World in Python?" -> informational
1188
- - "Add a comment to calculateTotal" -> single edit
1189
- - "Run npm install and tell me what happened" -> one command
1190
-
1191
- When in doubt, use it.
1192
- `;var GI=Ac.Struct({todos:Ac.mutable(Ac.Array(cn.Info)).annotate({description:"The updated todo list"})}),of=We("todowrite",tf.gen(function*(){let e=yield*cn.Service;return{description:ef,parameters:GI,execute:s((t,o)=>tf.gen(function*(){return yield*o.ask({permission:"todowrite",patterns:["*"],always:["*"],metadata:{}}),yield*e.update({sessionID:o.sessionID,todos:t.todos}),{title:`${t.todos.filter(n=>n.status!=="completed").length} todos`,output:JSON.stringify(t.todos,null,2),metadata:{todos:t.todos}}}),"execute")}}));import{Effect as Wr,Schema as $r}from"effect";import XI from"turndown";var nf="Fetch a URL (http is upgraded to https) and return its content as markdown (default), text or html; very large pages may be summarized. Read-only. The result starts with a ready `Source:` line and its read time: a text that rests on the page ends with that line.\n";import{lookup as HI}from"node:dns/promises";import{isIP as rf}from"node:net";function sf(e){let[t,o]=e.split(".").map(n=>Number(n));return t===0||t===10||t===127||t===100&&o>=64&&o<=127||t===169&&o===254||t===172&&o>=16&&o<=31||t===192&&o===168||t===198&&(o===18||o===19)||t>=224}s(sf,"v4Blocked");function YI(e){let t=e.toLowerCase();if(t==="::"||t==="::1")return!0;let o=t.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);return o?sf(o[1]):!!(/^f[cd]/.test(t)||/^fe[89ab]/.test(t)||/^ff/.test(t))}s(YI,"v6Blocked");function KI(e){let t=rf(e);return t===4?sf(e):t===6?YI(e):!0}s(KI,"isNonPublicAddress");async function JI(e){let t=new URL(e),o=t.hostname.replace(/^\[|\]$/g,"");if(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||o.endsWith(".internal"))throw new Error(`webfetch reaches the public web only; ${t.host} is on this machine or its network`);let n=rf(o)?[o]:(await HI(o,{all:!0})).map(r=>r.address);if(n.length===0||n.some(KI))throw new Error(`webfetch reaches the public web only; ${t.host} resolves to an address on this machine or its network`)}s(JI,"assertPublicUrl");async function Cc(e,t,o=5){let n=e;for(let r=0;r<=o;r++){await JI(n);let i=await fetch(n,{...t,redirect:"manual"}),a=i.headers.get("location");if(i.status>=300&&i.status<400&&a){n=new URL(a,n).toString();continue}return i}throw new Error(`webfetch stopped after ${o} redirects`)}s(Cc,"fetchPublic");var af=5*1024*1024,QI=30*1e3,ZI=120*1e3,eS=$r.Struct({url:$r.String,format:$r.Literals(["text","markdown","html"]).annotate({description:"Default markdown",default:"markdown"}).pipe($r.withDecodingDefault(Wr.succeed("markdown"))),timeout:$r.optional($r.Number).annotate({description:"Seconds, max 120"})}),df=We("webfetch",Wr.gen(function*(){return{description:nf,parameters:eS,execute:s((e,t)=>Wr.gen(function*(){if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("URL must start with http:// or https://");yield*t.ask({permission:"webfetch",patterns:[e.url],always:["*"],metadata:{url:e.url,format:e.format,timeout:e.timeout}});let o=Math.min((e.timeout??QI/1e3)*1e3,ZI),n="*/*";switch(e.format){case"markdown":n="text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1";break;case"text":n="text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1";break;case"html":n="text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1";break;default:n="text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"}let r={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",Accept:n,"Accept-Language":"en-US,en;q=0.9"},i=AbortSignal.any([AbortSignal.timeout(o),...t.abort?[t.abort]:[]]),a=yield*Wr.promise(async()=>{let S=await Cc(e.url,{signal:i,headers:r});return S.status===403&&S.headers.get("cf-mitigated")==="challenge"?await Cc(e.url,{signal:i,headers:{...r,"User-Agent":"opencode"}}):S});if(!a.ok)throw new Error(`Request failed with status code: ${a.status}`);let c=a.headers.get("content-length");if(c&&parseInt(c)>af)throw new Error("Response too large (exceeds 5MB limit)");let d=yield*Wr.promise(()=>a.arrayBuffer());if(d.byteLength>af)throw new Error("Response too large (exceeds 5MB limit)");let u=a.headers.get("content-type")||"",l=u.split(";")[0]?.trim().toLowerCase()||"",m=`${e.url} (${u})`;if(Jl(l)){let S=Buffer.from(d).toString("base64");return{title:m,output:"Image fetched successfully",metadata:{},attachments:[{type:"file",mime:l,url:`data:${l};base64,${S}`}]}}let h=new TextDecoder().decode(d),g=u.includes("text/html"),w=a.url||e.url,k=g?tS(h):l.includes("markdown")?(/^#\s+(.+)$/m.exec(h.slice(0,2e3))?.[1]??"").trim().slice(0,200):"",p={status:a.status,finalUrl:w,...k?{title:k}:{}},f=oS(k,w,a.status);switch(e.format){case"markdown":return{output:`${f}
1193
-
1194
- ${g?sS(h):h}`,title:m,metadata:p};case"text":return{output:`${f}
1195
-
1196
- ${g?uf(h):h}`,title:m,metadata:p};default:return{output:h,title:m,metadata:p}}}).pipe(Wr.orDie),"execute")}}));function tS(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(e);return t?uf(t[1]).replace(/\s+/g," ").trim().slice(0,200):""}s(tS,"titleOfHTML");function oS(e,t,o,n=new Date){return`Source: [${(e||t).replace(/[\[\]]/g,"")}](${t})
1197
- Read: ${n.toISOString().slice(0,16).replace("T"," ")} UTC, HTTP ${o}`}s(oS,"sourceHead");var nS=/<(script|style|noscript|iframe|object|embed|template|svg|head)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,rS=/<\/?(p|div|br|hr|li|ul|ol|tr|table|thead|tbody|h[1-6]|section|article|header|footer|nav|main|aside|pre|blockquote|dl|dt|dd|figure|figcaption|form|title)\b[^>]*>/gi,cf={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ndash:"\u2013",mdash:"\u2014",hellip:"\u2026",copy:"\xA9",reg:"\xAE",trade:"\u2122",euro:"\u20AC",pound:"\xA3",laquo:"\xAB",raquo:"\xBB",middot:"\xB7",bull:"\u2022",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",times:"\xD7",deg:"\xB0",rarr:"\u2192",larr:"\u2190"};function lf(e,t){return Number.isInteger(e)&&e>0&&e<=1114111&&!(e>=55296&&e<=57343)?String.fromCodePoint(e):t}s(lf,"codePoint");function uf(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(nS," ").replace(/<t[dh]\b[^>]*>/gi," ").replace(rS,`
1198
- `).replace(/<[^>]*>/g,"").replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z][a-z0-9]*));/gi,(t,o,n,r)=>o?lf(Number(o),t):n?lf(parseInt(n,16),t):cf[r]??cf[r.toLowerCase()]??t).replace(/[ \t\f\v ]+/g," ").replace(/ ?\n ?/g,`
1199
- `).replace(/\n{3,}/g,`
1200
-
1201
- `).trim()}s(uf,"extractTextFromHTML");function sS(e){let t=new XI({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",emDelimiter:"*"});return t.remove(["script","style","meta","link"]),t.turndown(e)}s(sS,"convertHTMLToMarkdown");import{Schema as Mc}from"effect";import*as Vn from"path";import{Effect as Oc}from"effect";import{createTwoFilesPatch as iS}from"diff";var pf=`Writes a file to the local filesystem.
1202
-
1203
- Usage:
1204
- - This tool will overwrite the existing file if there is one at the provided path.
1205
- - If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.
1206
- - ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
1207
- - NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
1208
- - Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.
1209
- `;var aS=5,cS=Mc.Struct({content:Mc.String.annotate({description:"The content to write to the file"}),filePath:Mc.String.annotate({description:"The absolute path to the file to write (must be absolute, not relative)"})}),Lc=We("write",Oc.gen(function*(){let e=yield*ut.Service,t=yield*Se.Service,o=yield*we.Service,n=yield*Xt.Service;return{description:pf,parameters:cS,execute:s((r,i)=>Oc.gen(function*(){let a=yield*B.context,c=Vn.isAbsolute(r.filePath)?r.filePath:Vn.join(a.directory,r.filePath);yield*qt(i,c);let d=yield*t.existsSafe(c),u=d?yield*fn(t,c):{bom:!1,text:""},l=yo(r.content),m=u.bom||l.bom,h=u.text,g=l.text,w=Go(iS(c,c,h,g));yield*i.ask({permission:"edit",patterns:[Vn.relative(a.worktree,c)],always:["*"],metadata:{filepath:c,diff:w}}),yield*t.writeWithDirs(c,Qt(g,m)),(yield*n.file(c))&&(yield*Bn(t,c,m)),yield*o.publish(Sn.Event.Edited,{file:c}),yield*o.publish($o.Event.Updated,{file:c,event:d?"change":"add"});let k="Wrote file successfully.";yield*e.touchFile(c,"document");let p=yield*e.diagnostics(),f=Se.normalizePath(c),S=0;for(let[y,v]of Object.entries(p)){let P=y===f;if(!P&&S>=aS)continue;let b=ut.Diagnostic.report(P?c:y,v);if(b){if(P){k+=`
1210
-
1211
- LSP errors detected in this file, please fix:
1212
- ${b}`;continue}S++,k+=`
1213
-
1214
- LSP errors detected in other files:
1215
- ${b}`}}return{title:Vn.relative(a.worktree,c),metadata:{diagnostics:p,filepath:c,exists:d},output:k}}).pipe(Oc.orDie),"execute")}}));import{Effect as ff,Schema as _c}from"effect";var lS=_c.Struct({tool:_c.String,error:_c.String}),mf=We("invalid",ff.succeed({description:"Do not use",parameters:lS,execute:s(e=>ff.succeed({title:"Invalid Tool",output:`The arguments provided to the tool are invalid: ${e.error}`,metadata:{}}),"execute")}));import gf from"path";import{Effect as _s,Schema as yf}from"effect";var hf=`Load a specialized skill when the task at hand matches one of the skills listed in the system prompt.
1216
-
1217
- Use this tool to inject the skill's instructions and resources into current conversation. The output may contain detailed workflow guidance as well as references to scripts, files, etc in the same directory as the skill.
1218
-
1219
- The skill name must match one of the skills listed in your system prompt.
1220
- `;var dS=yf.Struct({name:yf.String.annotate({description:"The name of the skill from available_skills"})}),wf=We("skill",_s.gen(function*(){let e=yield*an.Service,t=yield*on.Service;return{description:hf,parameters:dS,execute:s((o,n)=>_s.gen(function*(){let r=yield*e.require(o.name).pipe(_s.catchTag("Skill.NotFoundError",d=>_s.die(new Error(d.message))));yield*n.ask({permission:"skill",patterns:[o.name],always:[o.name],metadata:{}});let i=gf.dirname(r.location),a=i,c=yield*t.find({cwd:i,pattern:"!**/SKILL.md",hidden:!0,follow:!1,signal:n.abort,limit:10});return{title:`Loaded skill: ${r.name}`,output:[`<skill_content name="${r.name}">`,`# Skill: ${r.name}`,"",r.content.trim(),"",`Base directory for this skill: ${a}`,"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.","Note: file list is sampled.","","<skill_files>",c.map(d=>`<file>${gf.resolve(i,d.path)}</file>`).join(`
1221
- `),"</skill_files>","</skill_content>"].join(`
1222
- `),metadata:{name:r.name,dir:i}}}).pipe(_s.orDie),"execute")}}));import{Schema as Nf}from"effect";import zc from"zod";import{Effect as zn,Schema as _o}from"effect";var bf=`Search the web and return summaries of the most relevant pages: current information beyond your knowledge cutoff. The current year is {{year}}: use it when searching for recent information. Summaries are not pages read: say which claims rest only on them.
1223
- `;var xf={exa:"websearch-exa",tavily:"websearch-tavily"},uS="https://mcp.exa.ai/mcp",pS="https://api.tavily.com/search",If=8,fS=1e4,mS=25e3,Sf=6e4,kf=10*6e4,Uc={"exa-key":"Exa",tavily:"Tavily",exa:"Exa, no key"},Gn=class extends Error{constructor(o){super("rate-limited");this.waitMs=o}waitMs;static{s(this,"RateLimited")}},Us=class extends Error{constructor(o){super(`key refused (HTTP ${o})`);this.status=o}status;static{s(this,"KeyRefused")}},oa=new Map;function Df(e){let t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?Math.min(t*1e3,kf):Sf}s(Df,"waitFrom");function hS(e){let t=[],o=/^Title: (.*)\r?\nURL: (\S+)/gm;for(let n=o.exec(e);n;n=o.exec(e))t.push({title:n[1].trim(),url:n[2].trim()});return t}s(hS,"hitsIn");async function vf(e,t,o){let n=await fetch(uS,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json",...t?{"x-api-key":t}:{}},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:e.query,type:e.type||"auto",numResults:e.numResults||If,livecrawl:e.livecrawl||"fallback",contextMaxCharacters:e.contextMaxCharacters}}}),signal:o});if(n.status===429)throw new Gn(Df(n));if(t&&(n.status===401||n.status===403))throw new Us(n.status);if(!n.ok)throw new Error(`Search error (${n.status}): ${await n.text()}`);for(let r of(await n.text()).split(`
1224
- `)){if(!r.startsWith("data: "))continue;let i=JSON.parse(r.substring(6));if(i.result?._meta?.["ai.exa/rateLimited"])throw new Gn(Sf);if(i.result?.isError)throw new Error(`Search failed: ${i.result.content?.[0]?.text??"the search service reported an error"}`);let a=i.result?.content?.[0]?.text;if(a)return a}return""}s(vf,"searchExa");async function gS(e,t,o){let n=await fetch(pS,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify({query:e.query,max_results:Math.min(e.numResults||If,20),search_depth:e.type==="fast"?"fast":"basic",include_published_date:!0}),signal:o});if(n.status===429)throw new Gn(Df(n));if(n.status===432||n.status===433)throw new Gn(kf);if(n.status===401||n.status===403)throw new Us(n.status);if(!n.ok)throw new Error(`Search error (${n.status}): ${await n.text()}`);let r=await n.json(),i=e.contextMaxCharacters||fS,a=(r.results??[]).filter(d=>d.url),c=Math.max(200,Math.floor(i/Math.max(a.length,1)));return a.map(d=>`Title: ${(d.title??"").trim()||d.url}
1225
- URL: ${d.url}
1226
- Published: ${d.published_date||"N/A"}
1227
- Author: N/A
1228
- Highlights:
1229
- ${(d.content??"").trim().slice(0,c)}`).join(`
1230
-
1231
- ---
1232
-
1233
- `)}s(gS,"searchTavily");function yS(e){let t=Math.max(1,Math.ceil(e/1e3));return t<90?`about ${t} seconds`:`about ${Math.ceil(t/60)} minutes`}s(yS,"waitWords");async function wS(e,t,o,n=Date.now){let r={exa:await o(xf.exa),tavily:await o(xf.tavily)},i=[...r.exa?[{backend:"exa-key",run:s(h=>vf(e,r.exa,h),"run")}]:[],...r.tavily?[{backend:"tavily",run:s(h=>gS(e,r.tavily,h),"run")}]:[],{backend:"exa",run:s(h=>vf(e,void 0,h),"run")}],a=[r.exa,r.tavily].filter(h=>!!h),c=s(h=>a.reduce((g,w)=>g.split(w).join("[key]"),h),"clean"),d=[],u,l=0;for(let{backend:h,run:g}of i){if((oa.get(h)??0)>n()){l++;continue}let w=AbortSignal.any([AbortSignal.timeout(mS),t]);try{let k=await g(w);return oa.delete(h),{text:k,backend:h,refused:d}}catch(k){if(t.aborted)throw k;k instanceof Gn?(oa.set(h,n()+k.waitMs),l++):k instanceof Us?d.push(`${Uc[h]} (HTTP ${k.status})`):k instanceof Error&&(k.name==="AbortError"||k.name==="TimeoutError")?u=new Error(`Search request timed out (${Uc[h]})`):u=new Error(c(k instanceof Error?k.message:String(k)))}}let m=d.length?` The search key in Settings was refused: ${d.join(", ")}.`:"";if(l>0&&!u){let h=Math.min(...i.map(g=>oa.get(g.backend)??1/0).filter(g=>g>n()))-n();throw new Error(`Search is rate-limited for the moment. Nothing was searched. Search again in ${yS(h)}, or open a page you already know.`+(a.length?"":" Free search allows a few searches a minute; a search key of the user's own (Settings, Providers) lifts the limit.")+m)}throw new Error(`${u?.message??"Search failed"}${m}`)}s(wS,"runSearch");function bS(e,t){let o=hS(e.text),n=e.refused.length?`
1234
-
1235
- Note for the user: the search key in Settings was refused (${e.refused.join(", ")}); this search ran without it.`:"",r=`Search results (${Uc[e.backend]}, ${new Date().toISOString().slice(0,16).replace("T"," ")} UTC). These are summaries; a page is read only when you open it.`;return{output:o.length||e.text?`${r}
1236
-
1237
- ${e.text}${n}`:`No search results found. Please try a different query.${n}`,title:`Web search: ${t}`,metadata:{backend:e.backend,resultCount:o.length,hits:o.slice(0,8)}}}s(bS,"searchResult");var xS=_o.Struct({query:_o.String.annotate({description:"Websearch query"}),numResults:_o.optional(_o.Number).annotate({description:"Default 8"}),livecrawl:_o.optional(_o.Literals(["fallback","preferred"])).annotate({description:"Live crawling as a fallback for uncached pages (default) or preferred"}),type:_o.optional(_o.Literals(["auto","fast","deep"])).annotate({description:"Default auto"}),contextMaxCharacters:_o.optional(_o.Number).annotate({description:"Default 10000"})});var jc=We("websearch",zn.gen(function*(){let e=yield*eo.Service,t=s(o=>zn.runPromise(e.get(o).pipe(zn.map(n=>n?.type==="api"&&n.key.trim()?n.key.trim():void 0),zn.orElseSucceed(()=>{}))),"keyOf");return{get description(){return bf.replace("{{year}}",new Date().getFullYear().toString())},parameters:xS,execute:s((o,n)=>zn.gen(function*(){yield*n.ask({permission:"websearch",patterns:[o.query],always:["*"],metadata:{query:o.query,numResults:o.numResults,livecrawl:o.livecrawl,type:o.type,contextMaxCharacters:o.contextMaxCharacters}});let r=yield*zn.promise(()=>wS(o,n.abort,t));return bS(r,o.query)}).pipe(zn.orDie),"execute")}}));import{Effect as Nc,Schema as Yo}from"effect";import Fc from"path";var Ef=`Interact with Language Server Protocol (LSP) servers to get code intelligence features.
1238
-
1239
- Supported operations:
1240
- - goToDefinition: Find where a symbol is defined
1241
- - findReferences: Find all references to a symbol
1242
- - hover: Get hover information (documentation, type info) for a symbol
1243
- - documentSymbol: Get all symbols (functions, classes, variables) in a document
1244
- - workspaceSymbol: List project-wide symbols matching a query string
1245
- - goToImplementation: Find implementations of an interface or abstract method
1246
- - prepareCallHierarchy: Get call hierarchy item at a position (functions/methods)
1247
- - incomingCalls: Find all functions/methods that call the function at a position
1248
- - outgoingCalls: Find all functions/methods called by the function at a position
1249
-
1250
- All operations require:
1251
- - filePath: The file to operate on
1252
- - line: The line number (1-based, as shown in editors)
1253
- - character: The character offset (1-based, as shown in editors)
1254
-
1255
- workspaceSymbol also accepts:
1256
- - query: A query string to filter symbols by. Empty string requests all symbols.
1257
-
1258
- For workspaceSymbol, filePath is not sent in the LSP workspace/symbol request. It is used by opencode to select and start the matching LSP server.
1259
-
1260
- Note: LSP servers must be configured for the file type. If no server is available, an error will be returned.
1261
- `;import{pathToFileURL as vS}from"url";var IS=["goToDefinition","findReferences","hover","documentSymbol","workspaceSymbol","goToImplementation","prepareCallHierarchy","incomingCalls","outgoingCalls"],SS=Yo.Struct({operation:Yo.Literals(IS).annotate({description:"The LSP operation to perform"}),filePath:Yo.String.annotate({description:"The absolute or relative path to the file"}),line:Yo.Int.check(Yo.isGreaterThanOrEqualTo(1)).annotate({description:"The line number (1-based, as shown in editors)"}),character:Yo.Int.check(Yo.isGreaterThanOrEqualTo(1)).annotate({description:"The character offset (1-based, as shown in editors)"}),query:Yo.optional(Yo.String).annotate({description:"Search query for workspaceSymbol. Empty string requests all symbols."})}),Tf=We("lsp",Nc.gen(function*(){let e=yield*ut.Service,t=yield*Se.Service;return{description:Ef,parameters:SS,execute:s((o,n)=>Nc.gen(function*(){let r=yield*B.context,i=Fc.isAbsolute(o.filePath)?o.filePath:Fc.join(r.directory,o.filePath);yield*qt(n,i);let a=o.operation==="workspaceSymbol"?{operation:o.operation}:o.operation==="documentSymbol"?{operation:o.operation,filePath:i}:{operation:o.operation,filePath:i,line:o.line,character:o.character};yield*n.ask({permission:"lsp",patterns:["*"],always:["*"],metadata:a});let c=vS(i).href,d={file:i,line:o.line-1,character:o.character-1},u=Fc.relative(r.worktree,i),l=o.operation==="workspaceSymbol"?"":o.operation==="documentSymbol"?u:`${u}:${o.line}:${o.character}`,m=l?`${o.operation} ${l}`:o.operation;if(!(yield*t.existsSafe(i)))throw new Error(`File not found: ${i}`);if(!(yield*e.hasClients(i)))throw new Error("No LSP server available for this file type.");yield*e.touchFile(i,"document");let w=yield*(()=>{switch(o.operation){case"goToDefinition":return e.definition(d);case"findReferences":return e.references(d);case"hover":return e.hover(d);case"documentSymbol":return e.documentSymbol(c);case"workspaceSymbol":return e.workspaceSymbol(o.query??"");case"goToImplementation":return e.implementation(d);case"prepareCallHierarchy":return e.prepareCallHierarchy(d);case"incomingCalls":return e.incomingCalls(d);case"outgoingCalls":return e.outgoingCalls(d)}})();return{title:m,metadata:{result:w},output:w.length===0?`No results found for ${o.operation}`:JSON.stringify(w,null,2)}}).pipe(Nc.orDie),"execute")}}));import*as Uo from"path";import{Effect as io,Schema as Uf}from"effect";var Vr={};ae(Vr,{ApplyPatchError:()=>Af,MaybeApplyPatch:()=>Cf,MaybeApplyPatchVerified:()=>Mf,Patch:()=>Vr,PatchSchema:()=>kS,applyHunksToFiles:()=>Lf,applyPatch:()=>MS,deriveNewContentsFromChunks:()=>$c,maybeParseApplyPatch:()=>Of,maybeParseApplyPatchVerified:()=>OS,parsePatch:()=>js});import{Effect as wo,Schema as Pf}from"effect";import*as qr from"path";var kS=Pf.Struct({patchText:Pf.String.annotate({description:"The full patch text that describes all changes to be made"})}),Af=(r=>(r.ParseError="ParseError",r.IoError="IoError",r.ComputeReplacements="ComputeReplacements",r.ImplicitInvocation="ImplicitInvocation",r))(Af||{}),Cf=(r=>(r.Body="Body",r.ShellParseError="ShellParseError",r.PatchParseError="PatchParseError",r.NotApplyPatch="NotApplyPatch",r))(Cf||{}),Mf=(r=>(r.Body="Body",r.ShellParseError="ShellParseError",r.CorrectnessError="CorrectnessError",r.NotApplyPatch="NotApplyPatch",r))(Mf||{});function DS(e,t){let o=e[t];if(o.startsWith("*** Add File:")){let n=o.slice(13).trim();return n?{filePath:n,nextIdx:t+1}:null}if(o.startsWith("*** Delete File:")){let n=o.slice(16).trim();return n?{filePath:n,nextIdx:t+1}:null}if(o.startsWith("*** Update File:")){let n=o.slice(16).trim(),r,i=t+1;return i<e.length&&e[i].startsWith("*** Move to:")&&(r=e[i].slice(12).trim(),i++),n?{filePath:n,movePath:r,nextIdx:i}:null}return null}s(DS,"parsePatchHeader");function ES(e,t){let o=[],n=t;for(;n<e.length&&!e[n].startsWith("***");)if(e[n].startsWith("@@")){let r=e[n].substring(2).trim();n++;let i=[],a=[],c=!1;for(;n<e.length&&!e[n].startsWith("@@")&&!e[n].startsWith("***");){let d=e[n];if(d==="*** End of File"){c=!0,n++;break}if(d.startsWith(" ")){let u=d.substring(1);i.push(u),a.push(u)}else d.startsWith("-")?i.push(d.substring(1)):d.startsWith("+")&&a.push(d.substring(1));n++}o.push({old_lines:i,new_lines:a,change_context:r||void 0,is_end_of_file:c||void 0})}else n++;return{chunks:o,nextIdx:n}}s(ES,"parseUpdateFileChunks");function TS(e,t){let o="",n=t;for(;n<e.length&&!e[n].startsWith("***");)e[n].startsWith("+")&&(o+=e[n].substring(1)+`
1262
- `),n++;return o.endsWith(`
1263
- `)&&(o=o.slice(0,-1)),{content:o,nextIdx:n}}s(TS,"parseAddFileContent");function PS(e){let t=e.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return t?t[2]:e}s(PS,"stripHeredoc");function js(e){let o=PS(e.trim()).split(`
1264
- `),n=[],r=0,i="*** Begin Patch",a="*** End Patch",c=o.findIndex(u=>u.trim()===i),d=o.findIndex(u=>u.trim()===a);if(c===-1||d===-1||c>=d)throw new Error("Invalid patch format: missing Begin/End markers");for(r=c+1;r<d;){let u=DS(o,r);if(!u){r++;continue}if(o[r].startsWith("*** Add File:")){let{content:l,nextIdx:m}=TS(o,u.nextIdx);n.push({type:"add",path:u.filePath,contents:l}),r=m}else if(o[r].startsWith("*** Delete File:"))n.push({type:"delete",path:u.filePath}),r=u.nextIdx;else if(o[r].startsWith("*** Update File:")){let{chunks:l,nextIdx:m}=ES(o,u.nextIdx);n.push({type:"update",path:u.filePath,move_path:u.movePath,chunks:l}),r=m}else r++}return{hunks:n}}s(js,"parsePatch");function Of(e){let t=["apply_patch","applypatch"];if(e.length===2&&t.includes(e[0]))try{let{hunks:o}=js(e[1]);return{type:"Body",args:{patch:e[1],hunks:o}}}catch(o){return{type:"PatchParseError",error:o}}if(e.length===3&&e[0]==="bash"&&e[1]==="-lc"){let n=e[2].match(/apply_patch\s*<<['"](\w+)['"]\s*\n([\s\S]*?)\n\1/);if(n){let r=n[2];try{let{hunks:i}=js(r);return{type:"Body",args:{patch:r,hunks:i}}}catch(i){return{type:"PatchParseError",error:i}}}}return{type:"NotApplyPatch"}}s(Of,"maybeParseApplyPatch");function $c(e,t,o){let n=yo(o),r=n.text.split(`
1265
- `);r.length>0&&r[r.length-1]===""&&r.pop();let i=RS(r,e,t),a=AS(r,i);(a.length===0||a[a.length-1]!=="")&&a.push("");let c=yo(a.join(`
1266
- `)),d=c.text;return{unified_diff:CS(n.text,d),content:d,bom:n.bom||c.bom}}s($c,"deriveNewContentsFromChunks");function RS(e,t,o){let n=[],r=0;for(let i of o){if(i.change_context){let u=Bc(e,[i.change_context],r);if(u===-1)throw new Error(`Failed to find context '${i.change_context}' in ${t}`);r=u+1}if(i.old_lines.length===0){let u=e.length>0&&e[e.length-1]===""?e.length-1:e.length;n.push([u,0,i.new_lines]);continue}let a=i.old_lines,c=i.new_lines,d=Bc(e,a,r,i.is_end_of_file);if(d===-1&&a.length>0&&a[a.length-1]===""&&(a=a.slice(0,-1),c.length>0&&c[c.length-1]===""&&(c=c.slice(0,-1)),d=Bc(e,a,r,i.is_end_of_file)),d!==-1)n.push([d,a.length,c]),r=d+a.length;else throw new Error(`Failed to find expected lines in ${t}:
1267
- ${i.old_lines.join(`
1268
- `)}`)}return n.sort((i,a)=>i[0]-a[0]),n}s(RS,"computeReplacements");function AS(e,t){let o=[...e];for(let n=t.length-1;n>=0;n--){let[r,i,a]=t[n];o.splice(r,i);for(let c=0;c<a.length;c++)o.splice(r+c,0,a[c])}return o}s(AS,"applyReplacements");function Rf(e){return e.replace(/[‘’‚‛]/g,"'").replace(/[“”„‟]/g,'"').replace(/[‐‑‒–—―]/g,"-").replace(/…/g,"...").replace(/ /g," ")}s(Rf,"normalizeUnicode");function na(e,t,o,n,r){if(r){let i=e.length-t.length;if(i>=o){let a=!0;for(let c=0;c<t.length;c++)if(!n(e[i+c],t[c])){a=!1;break}if(a)return i}}for(let i=o;i<=e.length-t.length;i++){let a=!0;for(let c=0;c<t.length;c++)if(!n(e[i+c],t[c])){a=!1;break}if(a)return i}return-1}s(na,"tryMatch");function Bc(e,t,o,n=!1){if(t.length===0)return-1;let r=na(e,t,o,(d,u)=>d===u,n);if(r!==-1)return r;let i=na(e,t,o,(d,u)=>d.trimEnd()===u.trimEnd(),n);if(i!==-1)return i;let a=na(e,t,o,(d,u)=>d.trim()===u.trim(),n);return a!==-1?a:na(e,t,o,(d,u)=>Rf(d.trim())===Rf(u.trim()),n)}s(Bc,"seekSequence");function CS(e,t){let o=e.split(`
1269
- `),n=t.split(`
1270
- `),r=`@@ -1 +1 @@
1271
- `,i=Math.max(o.length,n.length),a=!1;for(let c=0;c<i;c++){let d=o[c]||"",u=n[c]||"";d!==u?(d&&(r+=`-${d}
1272
- `),u&&(r+=`+${u}
1273
- `),a=!0):d&&(r+=` ${d}
1274
- `)}return a?r:""}s(CS,"generateUnifiedDiff");var Lf=wo.fn("Patch.applyHunksToFiles")(function*(e){if(e.length===0)return yield*wo.fail(new Error("No files were modified."));let t=yield*Se.Service,o=[],n=[],r=[];for(let i of e)switch(i.type){case"add":{yield*t.writeWithDirs(i.path,i.contents),o.push(i.path),yield*wo.logInfo(`Added file: ${i.path}`);break}case"delete":{yield*t.remove(i.path),r.push(i.path),yield*wo.logInfo(`Deleted file: ${i.path}`);break}case"update":{let a=yield*t.readFileString(i.path),c=$c(i.path,i.chunks,a);i.move_path?(yield*t.writeWithDirs(i.move_path,Qt(c.content,c.bom)),yield*t.remove(i.path),n.push(i.move_path),yield*wo.logInfo(`Moved file: ${i.path} -> ${i.move_path}`)):(yield*t.writeWithDirs(i.path,Qt(c.content,c.bom)),n.push(i.path),yield*wo.logInfo(`Updated file: ${i.path}`));break}}return{added:o,modified:n,deleted:r}}),MS=wo.fn("Patch.applyPatch")(function*(e){let{hunks:t}=js(e);return yield*Lf(t)}),OS=wo.fn("Patch.maybeParseApplyPatchVerified")(function*(e,t){if(e.length===1)try{return js(e[0]),{type:"CorrectnessError",error:new Error("ImplicitInvocation")}}catch{}let o=Of(e);switch(o.type){case"Body":{let n=yield*Se.Service,r=o.args,i=r.workdir?qr.resolve(t,r.workdir):t,a=new Map;for(let c of r.hunks){let d=qr.resolve(i,c.type==="update"&&c.move_path?c.move_path:c.path);switch(c.type){case"add":a.set(d,{type:"add",content:c.contents});break;case"delete":{let u=qr.resolve(i,c.path),l=yield*n.readFileString(u).pipe(wo.catch(()=>wo.succeed(void 0)));if(l===void 0)return{type:"CorrectnessError",error:new Error(`Failed to read file for deletion: ${u}`)};a.set(d,{type:"delete",content:l});break}case"update":{let u=qr.resolve(i,c.path),l=yield*n.readFileString(u).pipe(wo.catch(m=>wo.succeed(new Error(`Failed to read file ${u}: ${m}`,{cause:m}))));if(l instanceof Error)return{type:"CorrectnessError",error:l};try{let m=$c(u,c.chunks,l);a.set(d,{type:"update",unified_diff:m.unified_diff,move_path:c.move_path?qr.resolve(i,c.move_path):void 0,new_content:m.content})}catch(m){return{type:"CorrectnessError",error:m}}break}}}return{type:"Body",action:{changes:a,patch:r.patch,cwd:i}}}case"PatchParseError":return{type:"CorrectnessError",error:o.error};case"NotApplyPatch":return{type:"NotApplyPatch"}}});import{createTwoFilesPatch as Wc,diffLines as jf}from"diff";var _f=`Use the \`apply_patch\` tool to edit files. Your patch language is a stripped\u2011down, file\u2011oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high\u2011level envelope:
1275
-
1276
- *** Begin Patch
1277
- [ one or more file sections ]
1278
- *** End Patch
1279
-
1280
- Within that envelope, you get a sequence of file operations.
1281
- You MUST include a header to specify the action you are taking.
1282
- Each operation starts with one of three headers:
1283
-
1284
- *** Add File: <path> - create a new file. Every following line is a + line (the initial contents).
1285
- *** Delete File: <path> - remove an existing file. Nothing follows.
1286
- *** Update File: <path> - patch an existing file in place (optionally with a rename).
1287
-
1288
- Example patch:
1289
-
1290
- \`\`\`
1291
- *** Begin Patch
1292
- *** Add File: hello.txt
1293
- +Hello world
1294
- *** Update File: src/app.py
1295
- *** Move to: src/main.py
1296
- @@ def greet():
1297
- -print("Hi")
1298
- +print("Hello, world!")
1299
- *** Delete File: obsolete.txt
1300
- *** End Patch
1301
- \`\`\`
1302
-
1303
- It is important to remember:
1304
-
1305
- - You must include a header with your intended action (Add/Delete/Update)
1306
- - You must prefix new lines with \`+\` even when creating a new file
1307
- `;var LS=Uf.Struct({patchText:Uf.String.annotate({description:"The full patch text that describes all changes to be made"})}),qc=We("apply_patch",io.gen(function*(){let e=yield*ut.Service,t=yield*Se.Service,o=yield*Xt.Service,n=yield*we.Service,r=io.fn("ApplyPatchTool.execute")(function*(i,a){if(!i.patchText)return yield*io.fail(new Error("patchText is required"));let c;try{c=Vr.parsePatch(i.patchText).hunks}catch(f){return yield*io.fail(new Error(`apply_patch verification failed: ${f}`))}if(c.length===0)return i.patchText.replace(/\r\n/g,`
1308
- `).replace(/\r/g,`
1309
- `).trim()===`*** Begin Patch
1310
- *** End Patch`?yield*io.fail(new Error("patch rejected: empty patch")):yield*io.fail(new Error("apply_patch verification failed: no hunks found"));let d=yield*B.context,u=[],l="";for(let f of c){let S=Uo.resolve(d.directory,f.path);switch(yield*qt(a,S),f.type){case"add":{let v=f.contents.length===0||f.contents.endsWith(`
1311
- `)?f.contents:`${f.contents}
1312
- `,P=yo(v),b=Go(Wc(S,S,"",P.text)),T=0,E=0;for(let j of jf("",P.text))j.added&&(T+=j.count||0),j.removed&&(E+=j.count||0);u.push({filePath:S,oldContent:"",newContent:P.text,type:"add",diff:b,additions:T,deletions:E,bom:P.bom}),l+=b+`
1313
- `;break}case"update":{let y=yield*t.stat(S).pipe(io.catch(()=>io.succeed(void 0)));if(!y||y.type==="Directory")return yield*io.fail(new Error(`apply_patch verification failed: Failed to read file to update: ${S}`));let v=yield*fn(t,S),P=v.text,b=P,T=v.bom;try{let ie=Vr.deriveNewContentsFromChunks(S,f.chunks,Qt(v.text,v.bom));b=ie.content,T=ie.bom}catch(ie){return yield*io.fail(new Error(`apply_patch verification failed: ${ie}`))}let E=Go(Wc(S,S,P,b)),j=0,_=0;for(let ie of jf(P,b))ie.added&&(j+=ie.count||0),ie.removed&&(_+=ie.count||0);let W=f.move_path?Uo.resolve(d.directory,f.move_path):void 0;yield*qt(a,W),u.push({filePath:S,oldContent:P,newContent:b,type:f.move_path?"move":"update",movePath:W,diff:E,additions:j,deletions:_,bom:T}),l+=E+`
1314
- `;break}case"delete":{let y=yield*fn(t,S).pipe(io.catch(T=>io.fail(new Error(`apply_patch verification failed: ${T instanceof Error?T.message:String(T)}`)))),v=y.text,P=Go(Wc(S,S,v,"")),b=v.split(`
1315
- `).length;u.push({filePath:S,oldContent:v,newContent:"",type:"delete",diff:P,additions:0,deletions:b,bom:y.bom}),l+=P+`
1316
- `;break}}}let m=u.map(f=>({filePath:f.filePath,relativePath:Uo.relative(d.worktree,f.movePath??f.filePath).replaceAll("\\","/"),type:f.type,patch:f.diff,additions:f.additions,deletions:f.deletions,...f.movePath?{movePath:f.movePath}:{}})),h=u.map(f=>Uo.relative(d.worktree,f.filePath).replaceAll("\\","/"));yield*a.ask({permission:"edit",patterns:h,always:["*"],metadata:{filepath:h.join(", "),diff:l,files:m}});for(let f of u)xa.assert(f.filePath,"apply_patch"),f.movePath&&xa.assert(f.movePath,"apply_patch");let g=[];for(let f of u){let S=f.type==="delete"?void 0:f.movePath??f.filePath;switch(f.type){case"add":yield*t.writeWithDirs(f.filePath,Qt(f.newContent,f.bom)),g.push({file:f.filePath,event:"add"});break;case"update":yield*t.writeWithDirs(f.filePath,Qt(f.newContent,f.bom)),g.push({file:f.filePath,event:"change"});break;case"move":f.movePath&&(yield*t.writeWithDirs(f.movePath,Qt(f.newContent,f.bom)),yield*t.remove(f.filePath),g.push({file:f.filePath,event:"unlink"}),g.push({file:f.movePath,event:"add"}));break;case"delete":yield*t.remove(f.filePath),g.push({file:f.filePath,event:"unlink"});break}S&&((yield*o.file(S))&&(yield*Bn(t,S,f.bom)),yield*n.publish(Sn.Event.Edited,{file:S}))}for(let f of g)yield*n.publish($o.Event.Updated,f);for(let f of u){if(f.type==="delete")continue;let S=f.movePath??f.filePath;yield*e.touchFile(S,"document")}let w=yield*e.diagnostics(),p=`Success. Updated the following files:
1317
- ${u.map(f=>{if(f.type==="add")return`A ${Uo.relative(d.worktree,f.filePath).replaceAll("\\","/")}`;if(f.type==="delete")return`D ${Uo.relative(d.worktree,f.filePath).replaceAll("\\","/")}`;let S=f.movePath??f.filePath;return`M ${Uo.relative(d.worktree,S).replaceAll("\\","/")}`}).join(`
1318
- `)}`;for(let f of u){if(f.type==="delete")continue;let S=f.movePath??f.filePath,y=ut.Diagnostic.report(S,w[Se.normalizePath(S)]??[]);if(!y)continue;let v=Uo.relative(d.worktree,S).replaceAll("\\","/");p+=`
1319
-
1320
- LSP errors detected in ${v}, please fix:
1321
- ${y}`}return{title:p,metadata:{diff:l,files:m,diagnostics:w},output:p}});return{description:_f,parameters:LS,execute:s((i,a)=>r(i,a).pipe(io.orDie),"execute")}}));import Ff from"path";import{pathToFileURL as _S}from"url";import{Effect as Ut,Layer as US,Context as jS}from"effect";function $f(e,t={exa:!1,parallel:!1}){return e===co.ID.opencode||e===co.ID.make("opencode-go")||t.exa||t.parallel}s($f,"webSearchEnabled");var zr=class extends jS.Service()("@opencode/ToolRegistry"){static{s(this,"Service")}},NS=US.effect(zr,Ut.gen(function*(){let e=yield*De.Service,t=yield*dt.Service,o=yield*Nt.Service,n=yield*ed,r=yield*Me.Service,i=yield*uo.Service,a=yield*mf,c=yield*qn,d=yield*Kp,u=yield*Lp,l=yield*of,m=yield*Tf,h=yield*Mp,g=yield*df,w=yield*jc,k=yield*qp,p=yield*Lc,f=yield*Dc,S=yield*zp,y=yield*qc,v=yield*wf,P=yield*Nt.Service,b=r.experimentalCodeMode?yield*Ut.promise(()=>import("./code-mode-7BQJUARW.js")):void 0,T=b?yield*b.CodeModeTool:void 0,E=yield*B.make(Ut.fn("ToolRegistry.state")(function*(x){let R=[];function A(Z,Q){let D=Q.args??{},N=Object.entries(D),te=N.every(zt=>Wf(zt[1]))?zc.object(D):void 0,Fe=te?WS(te):$S(N),ft=te?Nf.declare(zt=>te.safeParse(zt).success):Nf.Unknown;return{id:Z,parameters:ft,jsonSchema:Fe,description:Q.description,execute:s((zt,It)=>Ut.gen(function*(){let bn=yield*Yt.make(),I={...It,ask:s(H=>bn.promise(It.ask(H)),"ask"),directory:x.directory,worktree:x.worktree},z=yield*Ut.promise(()=>Q.execute(zt,I)),ue=typeof z=="string"?z:z.output,se=typeof z=="string"?{}:z.metadata??{},J=typeof z=="string"?void 0:z.attachments,ee=yield*P.get(It.agent),oe=yield*n.output(ue,{},ee);return{title:typeof z=="string"?"":z.title??"",output:oe.truncated?oe.content:ue,attachments:J,metadata:{...se,truncated:oe.truncated,...oe.truncated&&{outputPath:oe.outputPath}}}}).pipe(Ut.withSpan("Tool.execute",{attributes:{"tool.name":Z,"session.id":It.sessionID,"message.id":It.messageID,...It.callID?{"tool.call_id":It.callID}:{}}})),"execute")}}s(A,"fromPlugin");let F=(yield*e.directories()).flatMap(Z=>fl.scanSync("{tool,tools}/*.{js,ts}",{cwd:Z,absolute:!0,dot:!0,symlink:!0}));F.length&&(yield*e.waitForDependencies());for(let Z of F){let Q=Ff.basename(Z,Ff.extname(Z)),D=yield*Ut.promise(()=>import(_S(Z).href));for(let[N,q]of Object.entries(D))FS(q)&&R.push(A(N==="default"?Q:`${Q}_${N}`,q))}let U=yield*t.list();for(let Z of U)for(let[Q,D]of Object.entries(Z.tool??{}))R.push(A(Q,D));yield*e.get();let pe=!r.alchemyLab&&["app","cli","desktop"].includes(r.client)||r.enableQuestionTool,re=yield*Ut.all({invalid:Tt(a),read:Tt(d),glob:Tt(k),grep:Tt(S),edit:Tt(f),write:Tt(p),task:Tt(c),fetch:Tt(g),todo:Tt(l),search:Tt(w),skill:Tt(v),patch:Tt(y),question:Tt(u),lsp:Tt(m),plan:Tt(h),...T?{execute:Tt(T)}:{}});return{custom:R,builtin:[re.invalid,...pe?[re.question]:[],re.read,re.glob,re.grep,re.edit,re.write,re.task,re.fetch,re.todo,re.search,re.skill,re.patch,...re.execute?[re.execute]:[],...r.experimentalLspTool?[re.lsp]:[],...r.experimentalPlanMode&&!r.alchemyLab&&r.client==="cli"?[re.plan]:[]],task:re.task,read:re.read}})),j=Ut.fn("ToolRegistry.all")(function*(){let x=yield*B.get(E);return[...x.builtin,...x.custom]}),_=Ut.fn("ToolRegistry.ids")(function*(){return(yield*j()).map(x=>x.id)}),W=Ut.fn("ToolRegistry.describeTask")(function*(x){return["Available agent types and the tools they have access to:",(yield*o.list()).filter(U=>U.mode!=="primary").filter(U=>Ye.evaluate("task",U.name,x.permission).action!=="deny").toSorted((U,pe)=>U.name.localeCompare(pe.name)).map(U=>`- ${U.name}: ${U.description??"This subagent should only be called manually by the user."}`).join(`
1322
- `)].join(`
1323
- `)}),ie=Ut.fn("ToolRegistry.describeCodeMode")(function*(x){if(!b)return;let R=Ye.merge(x.agent.permission,x.permission??[]),A=Ye.visibleTools(yield*i.tools(),R);if(Object.keys(A).length!==0)return b.describeCatalog(A,Object.keys(yield*i.clients()).map(gi.sanitize))}),M=Ut.fn("ToolRegistry.tools")(function*(x){let R=(yield*j()).filter(F=>{if(F.id===jc.id)return $f(x.providerID,{exa:r.enableExa,parallel:r.enableParallel});let U=x.modelID.includes("gpt-")&&!x.modelID.includes("oss")&&!x.modelID.includes("gpt-4");return F.id===qc.id?U:F.id===Dc.id||F.id===Lc.id?!U:!0}),A=R.some(F=>F.id==="execute")?yield*ie(x):void 0,O=R.filter(F=>F.id!=="execute"||A);return yield*Ut.forEach(O,Ut.fnUntraced(function*(F){let U={description:F.description,parameters:F.parameters,jsonSchema:F.jsonSchema};yield*t.trigger("tool.definition",{toolID:F.id},U);let pe=U.parameters===F.parameters||U.jsonSchema!==F.jsonSchema?U.jsonSchema:void 0;return{id:F.id,description:[U.description,F.id===qn.id?yield*W(x.agent):void 0,F.id==="execute"?A:void 0].filter(Boolean).join(`
1324
- `),parameters:U.parameters,jsonSchema:pe,execute:F.execute,formatValidationError:F.formatValidationError}}),{concurrency:"unbounded"})}),$=Ut.fn("ToolRegistry.named")(function*(){let x=yield*B.get(E);return{task:x.task,read:x.read}});return zr.of({ids:_,all:j,named:$,tools:M})}));function Wf(e){return typeof e=="object"&&e!==null&&"_zod"in e}s(Wf,"isZodType");function FS(e){return typeof e=="object"&&e!==null&&"args"in e&&"description"in e&&"execute"in e}s(FS,"isPluginTool");function BS(e){return typeof e=="boolean"||typeof e=="object"&&e!==null&&!Array.isArray(e)}s(BS,"isJsonSchemaDefinition");function $S(e){let t=Object.fromEntries(e.filter(o=>BS(o[1])));return{type:"object",properties:t,required:Object.keys(t)}}s($S,"legacyJsonSchema");function WS(e){let t=Vc(zc.toJSONSchema(e,{io:"input",metadata:qS(e)}));if(!Bf(t))throw new Error("plugin tool Zod schema produced a non-object JSON Schema");let{$defs:o,...n}=t;return o&&Bf(o)?{...n,definitions:o}:n}s(WS,"zodJsonSchema");function qS(e){let t=zc.registry(),o=new WeakSet,n=s(r=>{if(!(typeof r!="object"||r===null)&&!o.has(r)){if(o.add(r),Wf(r)){let i=typeof r.meta=="function"?r.meta():void 0,a=typeof r.description=="string"?r.description:void 0,c={...i&&typeof i=="object"?i:{},...a?{description:a}:{}};Object.keys(c).length&&t.add(r,c),n(r._zod.def);return}for(let i of Object.values(r))n(i)}},"collect");return n(e),t}s(qS,"zodMetadataRegistry");function Vc(e){return Array.isArray(e)?e.map(t=>Vc(t)):typeof e!="object"||e===null?e:Object.fromEntries(Object.entries(e).filter(t=>!((t[0]==="exclusiveMaximum"||t[0]==="exclusiveMinimum")&&typeof t[1]=="boolean")).map(([t,o])=>[t,Vc(o)]))}s(Vc,"normalizeZodJsonSchema");function Bf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Bf,"isJsonSchemaObject");var VS=ge.make({service:zr,layer:NS,deps:[De.node,dt.node,to.node,cn.node,Nt.node,an.node,ce.node,Tn.node,yt.node,ut.node,Lo.node,Se.node,we.node,Co,si.node,Xt.node,td,Me.node,uo.node,Xe.node,on.node,eo.node]});var Yr={};ae(Yr,{CommandInput:()=>Pk,LoopInput:()=>Xc,PromptInput:()=>Ek,Service:()=>Hr,SessionPrompt:()=>Yr,ShellInput:()=>Tk,createStructuredOutputTool:()=>lm,node:()=>Mk});import nm from"path";import ck from"os";import{tool as lk,jsonSchema as dk}from"ai";import{ulid as rm}from"ulid";import{ChildProcess as uk,ChildProcessSpawner as pk}from"effect/unstable/process";import*as jo from"effect/Stream";import{pathToFileURL as fk,fileURLToPath as Yc}from"url";var Ns={};ae(Ns,{ShellID:()=>Ns,ToolID:()=>KS,toKind:()=>YS});var zS=["bash","pwsh","powershell","cmd"],GS=new Set(zS);function HS(e){return GS.has(e)}s(HS,"isKind");function YS(e){return HS(e)?e:"bash"}s(YS,"toKind");var KS="bash";function qf(e){let t=e.indexOf(",");if(t===-1)return"";let o=e.slice(0,t),n=e.slice(t+1);return o.includes(";base64")?Buffer.from(n,"base64").toString("utf8"):decodeURIComponent(n)}s(qf,"decodeDataUrl");import{Cause as To,Effect as C,Exit as hn,Latch as mk,Layer as hk,Option as Kc,Scope as gk,Context as yk,Schema as ye}from"effect";import{eq as wk}from"drizzle-orm";var Fs={};ae(Fs,{SessionReminders:()=>Fs,apply:()=>XS});import JS from"path";import{Effect as Gc}from"effect";var Vf=`<system-reminder>
1325
- # Plan Mode - System Reminder
1326
-
1327
- CRITICAL: Plan mode ACTIVE - you are in READ-ONLY phase. STRICTLY FORBIDDEN:
1328
- ANY file edits, modifications, or system changes. Do NOT use sed, tee, echo, cat,
1329
- or ANY other bash command to manipulate files - commands may ONLY read/inspect.
1330
- This ABSOLUTE CONSTRAINT overrides ALL other instructions, including direct user
1331
- edit requests. You may ONLY observe, analyze, and plan. Any modification attempt
1332
- is a critical violation. ZERO exceptions.
1333
-
1334
- ---
1335
-
1336
- ## Responsibility
1337
-
1338
- Your current responsibility is to think, read, search, and delegate explore agents to construct a well-formed plan that accomplishes the goal the user wants to achieve. Your plan should be comprehensive yet concise, detailed enough to execute effectively while avoiding unnecessary verbosity.
1339
-
1340
- Ask the user clarifying questions or ask for their opinion when weighing tradeoffs.
1341
-
1342
- **NOTE:** At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
1343
-
1344
- ---
1345
-
1346
- ## Important
1347
-
1348
- The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
1349
- </system-reminder>
1350
- `;var ra=`<system-reminder>
1351
- Your operational mode has changed from plan to build.
1352
- You are no longer in read-only mode.
1353
- You are permitted to make file changes, run shell commands, and utilize your arsenal of tools as needed.
1354
- </system-reminder>
1355
- `;var zf=`<system-reminder>
1356
- Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
1357
-
1358
- ## Plan File Info:
1359
- \${planInfo}
1360
- You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
1361
-
1362
- ## Plan Workflow
1363
-
1364
- ### Phase 1: Initial Understanding
1365
- Goal: Gain a comprehensive understanding of the user's request by reading through code and asking them questions. Critical: In this phase you should only use the explore subagent type.
1366
-
1367
- 1. Focus on understanding the user's request and the code associated with their request
1368
-
1369
- 2. **Launch up to 3 explore agents IN PARALLEL** (single message, multiple tool calls) to efficiently explore the codebase.
1370
- - Use 1 agent when the task is isolated to known files, the user provided specific file paths, or you're making a small targeted change.
1371
- - Use multiple agents when: the scope is uncertain, multiple areas of the codebase are involved, or you need to understand existing patterns before planning.
1372
- - Quality over quantity - 3 agents maximum, but you should try to use the minimum number of agents necessary (usually just 1)
1373
- - If using multiple agents: Provide each agent with a specific search focus or area to explore. Example: One agent searches for existing implementations, another explores related components, a third investigates testing patterns
1374
-
1375
- 3. After exploring the code, use the question tool to clarify ambiguities in the user request up front.
1376
-
1377
- ### Phase 2: Design
1378
- Goal: Design an implementation approach.
1379
-
1380
- Launch general agent(s) to design the implementation based on the user's intent and your exploration results from Phase 1.
1381
-
1382
- You can launch up to 1 agent(s) in parallel.
1383
-
1384
- **Guidelines:**
1385
- - **Default**: Launch at least 1 Plan agent for most tasks - it helps validate your understanding and consider alternatives
1386
- - **Skip agents**: Only for truly trivial tasks (typo fixes, single-line changes, simple renames)
1387
-
1388
- Examples of when to use multiple agents:
1389
- - The task touches multiple parts of the codebase
1390
- - It's a large refactor or architectural change
1391
- - There are many edge cases to consider
1392
- - You'd benefit from exploring different approaches
1393
-
1394
- Example perspectives by task type:
1395
- - New feature: simplicity vs performance vs maintainability
1396
- - Bug fix: root cause vs workaround vs prevention
1397
- - Refactoring: minimal change vs clean architecture
1398
-
1399
- In the agent prompt:
1400
- - Provide comprehensive background context from Phase 1 exploration including filenames and code path traces
1401
- - Describe requirements and constraints
1402
- - Request a detailed implementation plan
1403
-
1404
- ### Phase 3: Review
1405
- Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
1406
- 1. Read the critical files identified by agents to deepen your understanding
1407
- 2. Ensure that the plans align with the user's original request
1408
- 3. Use question tool to clarify any remaining questions with the user
1409
-
1410
- ### Phase 4: Final Plan
1411
- Goal: Write your final plan to the plan file (the only file you can edit).
1412
- - Include only your recommended approach, not all alternatives
1413
- - Ensure that the plan file is concise enough to scan quickly, but detailed enough to execute effectively
1414
- - Include the paths of critical files to be modified
1415
- - Include a verification section describing how to test the changes end-to-end (run the code, use MCP tools, run tests)
1416
-
1417
- ### Phase 5: Call plan_exit tool
1418
- At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call plan_exit to indicate to the user that you are done planning.
1419
- This is critical - your turn should only end with either asking the user a question or calling plan_exit. Do not stop unless it's for these 2 reasons.
1420
-
1421
- **Important:** Use question tool to clarify requirements/approach, use plan_exit to request plan approval. Do NOT use question tool to ask "Is this plan okay?" - that's what plan_exit does.
1422
-
1423
- NOTE: At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
1424
- </system-reminder>
1425
- `;var XS=Gc.fn("SessionReminders.apply")(function*(e){let t=yield*Me.Service,o=yield*Se.Service,n=yield*ce.Service,r=e.messages.findLast(l=>l.info.role==="user");if(!r)return e.messages;if(!t.experimentalPlanMode)return e.agent.name==="plan"&&r.parts.push({id:Ce.ascending(),messageID:r.info.id,sessionID:r.info.sessionID,type:"text",text:Vf,synthetic:!0}),e.messages.some(m=>m.info.role==="assistant"&&m.info.agent==="plan")&&e.agent.name==="build"&&r.parts.push({id:Ce.ascending(),messageID:r.info.id,sessionID:r.info.sessionID,type:"text",text:ra,synthetic:!0}),e.messages;let i=e.messages.findLast(l=>l.info.role==="assistant");if(e.agent.name!=="plan"&&i?.info.agent==="plan"){let l=yield*B.context,m=ce.plan(e.session,l),h=yield*o.existsSafe(m),g=yield*n.updatePart({id:Ce.ascending(),messageID:r.info.id,sessionID:r.info.sessionID,type:"text",text:h?`${ra}
1426
-
1427
- A plan file exists at ${m}. You should execute on the plan defined within it`:ra,synthetic:!0});return r.parts.push(g),e.messages}if(e.agent.name!=="plan"||i?.info.agent==="plan")return e.messages;let a=yield*B.context,c=ce.plan(e.session,a),d=yield*o.existsSafe(c);d||(yield*o.ensureDir(JS.dirname(c)).pipe(Gc.catch(Gc.die)));let u=yield*n.updatePart({id:Ce.ascending(),messageID:r.info.id,sessionID:r.info.sessionID,type:"text",text:zf.replace("${planInfo}",()=>d?`A plan file already exists at ${c}. You can read it and make incremental edits using the edit tool.`:`No plan file exists yet. You should create your plan at ${c} using the write tool.`),synthetic:!0});return r.parts.push(u),e.messages});var Ws={};ae(Ws,{SessionTools:()=>Ws,resolve:()=>ZS});import{tool as sa,jsonSchema as Bs,asSchema as QS}from"ai";import{Effect as Eo}from"effect";var Jo={list:"list_mcp_resources",listTemplates:"list_mcp_resource_templates",read:"read_mcp_resource"},ia=10*1024*1024,Yf=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),ZS=Eo.fn("SessionTools.resolve")(function*(e){let t={},o=yield*Yt.make(),n=yield*dt.Service,r=yield*Ye.Service,i=yield*Ko.Service,a=yield*uo.Service,c=yield*Pn.Service,d=yield*Me.Service,u=s((m,h)=>({sessionID:e.session.id,abort:h.abortSignal,messageID:e.processor.message.id,callID:h.toolCallId,extra:{model:e.model,bypassAgentCheck:e.bypassAgentCheck,promptOps:e.promptOps},agent:e.agent.name,messages:e.messages,metadata:s(g=>e.processor.updateToolCall(h.toolCallId,w=>["running","pending"].includes(w.state.status)?{...w,state:{title:g.title,metadata:g.metadata,status:"running",input:m,time:w.state.status==="running"?w.state.time:{start:Date.now()}}}:w),"metadata"),ask:s(g=>r.ask({...g,sessionID:e.session.id,tool:{messageID:e.processor.message.id,callID:h.toolCallId},ruleset:Ye.merge(e.agent.permission,e.session.permission??[])}).pipe(Eo.orDie),"ask")}),"context");for(let m of yield*i.tools({modelID:xn.ID.make(e.model.api.id),providerID:e.model.providerID,agent:e.agent,permission:e.session.permission})){let h=Ke.schema(e.model,Wn.fromTool(m));t[m.id]=sa({description:m.description,inputSchema:Bs(h),execute(g,w){return Jt.run(e.gate,()=>o.promise(Eo.gen(function*(){let k=u(g,w);yield*n.trigger("tool.execute.before",{tool:m.id,sessionID:k.sessionID,callID:k.callID},{args:g});let p=yield*m.execute(g,k),f={...p,attachments:p.attachments?.map(S=>({...S,id:Ce.ascending(),sessionID:k.sessionID,messageID:e.processor.message.id}))};return yield*n.trigger("tool.execute.after",{tool:m.id,sessionID:k.sessionID,callID:k.callID,args:g},f),w.abortSignal?.aborted&&(yield*e.processor.completeToolCall(w.toolCallId,f)),f})))}})}if(Object.values(yield*a.clients()).some(m=>!!m.getServerCapabilities()?.resources)&&(t[Jo.list]=sa({description:"Lists resources provided by connected MCP servers. Resources provide context such as files, database schemas, or application-specific information.",inputSchema:Bs(Ke.schema(e.model,{type:"object",properties:{server:{type:"string",description:"Optional MCP server name. When omitted, lists resources from every connected server."}},additionalProperties:!1})),execute(m,h){return o.promise(Eo.gen(function*(){let g=Gf(m),w=u($s(m),h),k=yield*a.clients(),p=Object.entries(k).filter(T=>!!T[1].getServerCapabilities()?.resources).map(T=>T[0]).sort((T,E)=>T.localeCompare(E));if(g.server&&!p.includes(g.server))throw new Error(p.length===0?`MCP server "${g.server}" does not support resources`:`MCP server "${g.server}" does not support resources. Available resource servers: ${p.join(", ")}`);let f=g.server?[`mcp:${g.server}:*`]:p.map(T=>`mcp:${T}:*`);yield*n.trigger("tool.execute.before",{tool:Jo.list,sessionID:w.sessionID,callID:h.toolCallId},{args:m}),yield*w.ask({permission:"read",metadata:g.server?{server:g.server}:{},patterns:f,always:f});let y=Object.values(yield*a.resources(g.server)).filter(T=>!g.server||T.client===g.server).toSorted((T,E)=>(T.client+"\0"+T.name+"\0"+T.uri).localeCompare(E.client+"\0"+E.name+"\0"+E.uri)),v=JSON.stringify({resources:y.map(tk)},null,2),P=yield*c.output(v,{},e.agent),b={title:g.server?`MCP resources: ${g.server}`:"MCP resources",metadata:{count:y.length,servers:p,...g.server?{server:g.server}:{},truncated:P.truncated,...P.truncated&&{outputPath:P.outputPath}},output:P.content};return yield*n.trigger("tool.execute.after",{tool:Jo.list,sessionID:w.sessionID,callID:h.toolCallId,args:m},b),h.abortSignal?.aborted&&(yield*e.processor.completeToolCall(h.toolCallId,b)),b}))}}),t[Jo.listTemplates]=sa({description:"Lists resource templates provided by connected MCP servers. Resource templates are parameterized resources that can be read after filling in their URI template.",inputSchema:Bs(Ke.schema(e.model,{type:"object",properties:{server:{type:"string",description:"Optional MCP server name. When omitted, lists resource templates from every connected server."}},additionalProperties:!1})),execute(m,h){return o.promise(Eo.gen(function*(){let g=Gf(m),w=u($s(m),h),k=yield*a.clients(),p=Object.entries(k).filter(T=>!!T[1].getServerCapabilities()?.resources).map(T=>T[0]).sort((T,E)=>T.localeCompare(E));if(g.server&&!p.includes(g.server))throw new Error(p.length===0?`MCP server "${g.server}" does not support resources`:`MCP server "${g.server}" does not support resources. Available resource servers: ${p.join(", ")}`);let f=g.server?[`mcp:${g.server}:*`]:p.map(T=>`mcp:${T}:*`);yield*n.trigger("tool.execute.before",{tool:Jo.listTemplates,sessionID:w.sessionID,callID:h.toolCallId},{args:m}),yield*w.ask({permission:"read",metadata:g.server?{server:g.server}:{},patterns:f,always:f});let y=Object.values(yield*a.resourceTemplates(g.server)).filter(T=>!g.server||T.client===g.server).toSorted((T,E)=>(T.client+"\0"+T.name+"\0"+T.uriTemplate).localeCompare(E.client+"\0"+E.name+"\0"+E.uriTemplate)),v=JSON.stringify({resourceTemplates:y.map(ok)},null,2),P=yield*c.output(v,{},e.agent),b={title:g.server?`MCP resource templates: ${g.server}`:"MCP resource templates",metadata:{count:y.length,servers:p,...g.server?{server:g.server}:{},truncated:P.truncated,...P.truncated&&{outputPath:P.outputPath}},output:P.content};return yield*n.trigger("tool.execute.after",{tool:Jo.listTemplates,sessionID:w.sessionID,callID:h.toolCallId,args:m},b),h.abortSignal?.aborted&&(yield*e.processor.completeToolCall(h.toolCallId,b)),b}))}}),t[Jo.read]=sa({description:"Read a specific resource from an MCP server using the server name and resource URI. The URI is an MCP identifier and does not need to be a file URL.",inputSchema:Bs(Ke.schema(e.model,{type:"object",properties:{server:{type:"string",description:"MCP server name exactly as returned by list_mcp_resources."},uri:{type:"string",description:"Resource URI to read. Use the exact URI string returned by list_mcp_resources."}},required:["server","uri"],additionalProperties:!1})),execute(m,h){return o.promise(Eo.gen(function*(){let g=ek(m),w=u($s(m),h),p=(yield*a.clients())[g.server];if(!p)throw new Error(`MCP server "${g.server}" is not connected`);if(!p.getServerCapabilities()?.resources)throw new Error(`MCP server "${g.server}" does not support resources`);yield*n.trigger("tool.execute.before",{tool:Jo.read,sessionID:w.sessionID,callID:h.toolCallId},{args:m}),yield*w.ask({permission:"read",metadata:{server:g.server,uri:g.uri},patterns:[`mcp:${g.server}:${g.uri}`],always:[`mcp:${g.server}:*`]});let f=yield*a.readResource(g.server,g.uri);if(!f)throw new Error(`Failed to read MCP resource: ${g.server}/${g.uri}`);let S=nk(g.server,g.uri,f),y=yield*c.output(S.text,{},e.agent),v={title:`MCP resource: ${g.uri}`,metadata:{server:g.server,uri:g.uri,contents:S.contents,attachments:S.attachments.length,truncated:y.truncated,...y.truncated&&{outputPath:y.outputPath}},output:y.content,attachments:S.attachments.map(P=>({...P,id:Ce.ascending(),sessionID:w.sessionID,messageID:e.processor.message.id}))};return yield*n.trigger("tool.execute.after",{tool:Jo.read,sessionID:w.sessionID,callID:h.toolCallId,args:m},v),h.abortSignal?.aborted&&(yield*e.processor.completeToolCall(h.toolCallId,v)),v}))}})),d.experimentalCodeMode)return t;for(let[m,h]of Object.entries(yield*a.tools())){let g=gi.convertTool(h.def,h.client,h.timeout),w=g.execute;if(!w)continue;let k=yield*Eo.promise(()=>Promise.resolve(QS(g.inputSchema).jsonSchema)),p=Ke.schema(e.model,{...k,properties:k.properties??{}});g.inputSchema=Bs(p),g.execute=(f,S)=>Jt.run(e.gate,()=>o.promise(Eo.gen(function*(){let y=u(f,S);yield*n.trigger("tool.execute.before",{tool:m,sessionID:y.sessionID,callID:S.toolCallId},{args:f});let v=yield*Eo.gen(function*(){yield*y.ask({permission:m,metadata:{},patterns:["*"],always:["*"]});let _={sessionId:y.sessionID,messageId:e.processor.message.id};return yield*Eo.promise(()=>w(f,{...S,callContext:_}))}).pipe(Eo.withSpan("Tool.execute",{attributes:{"tool.name":m,"tool.call_id":S.toolCallId,"session.id":y.sessionID,"message.id":e.processor.message.id}}));yield*n.trigger("tool.execute.after",{tool:m,sessionID:y.sessionID,callID:S.toolCallId,args:f},v);let P=[],b=[];for(let _ of v.content)if(_.type==="text")P.push(_.text);else if(_.type==="image")b.push({type:"file",mime:_.mimeType,url:`data:${_.mimeType};base64,${_.data}`});else if(_.type==="resource"){let{resource:W}=_;if(W.text&&P.push(W.text),W.blob){let ie=W.mimeType??"application/octet-stream",M=Jf(W.blob);if(!Yf.has(ie)){P.push(`[Binary MCP resource omitted: ${W.uri} (${ie}, ${Gr(M)}) is not a supported attachment type]`);continue}if(M>ia){P.push(`[Binary MCP resource omitted: ${W.uri} (${ie}, ${Gr(M)}) exceeds ${Gr(ia)}]`);continue}b.push({type:"file",mime:ie,url:`data:${ie};base64,${W.blob}`,filename:W.uri})}}let T=yield*c.output(P.join(`
1428
-
1429
- `),{},e.agent),j={title:"",metadata:{...v.metadata,truncated:T.truncated,...T.truncated&&{outputPath:T.outputPath}},output:T.content,attachments:b.map(_=>({..._,id:Ce.ascending(),sessionID:y.sessionID,messageID:e.processor.message.id})),content:v.content};return S.abortSignal?.aborted&&(yield*e.processor.completeToolCall(S.toolCallId,j)),j}))),t[m]=g}return t});function $s(e){return lt(e)?e:{}}s($s,"toRecord");function Gf(e){let t=$s(e);return{server:Kf(t,"server")}}s(Gf,"parseListMcpResourcesArgs");function ek(e){let t=$s(e);return{server:Hf(t,"server"),uri:Hf(t,"uri")}}s(ek,"parseReadMcpResourceArgs");function Kf(e,t){let o=e[t];if(!(o==null||o==="")){if(typeof o!="string")throw new Error(`${t} must be a string`);return o}}s(Kf,"optionalString");function Hf(e,t){let o=Kf(e,t);if(o)return o;throw new Error(`${t} is required`)}s(Hf,"requiredString");function tk(e){return{...Object.fromEntries(Object.entries(e).filter(o=>o[0]!=="client")),server:e.client}}s(tk,"formatMcpResource");function ok(e){return{...Object.fromEntries(Object.entries(e).filter(o=>o[0]!=="client")),server:e.client}}s(ok,"formatMcpResourceTemplate");function nk(e,t,o){let n=(Array.isArray(o.contents)?o.contents:[o.contents]).filter(lt),r=[],i=[];for(let a of n){let c=typeof a.uri=="string"?a.uri:t,d=typeof a.mimeType=="string"?a.mimeType:"application/octet-stream";if(typeof a.text=="string"){r.push(`Resource: ${c}
1430
- MIME: ${d}
1431
- ${a.text}`);continue}if(typeof a.blob=="string"){let u=Jf(a.blob);if(!Yf.has(d)){r.push(`[Binary MCP resource omitted: ${c} (${d}, ${Gr(u)}) is not a supported attachment type]`);continue}if(u>ia){r.push(`[Binary MCP resource omitted: ${c} (${d}, ${Gr(u)}) exceeds ${Gr(ia)}]`);continue}r.push(`[Binary MCP resource attached: ${c} (${d})]`),i.push({type:"file",mime:d,url:`data:${d};base64,${a.blob}`,filename:c});continue}r.push(`[MCP resource content without text or blob: ${c}]`)}return{contents:n.length,attachments:i,text:r.join(`
1432
-
1433
- `)||`MCP resource ${t} from ${e} returned no contents.`}}s(nk,"formatMcpResourceContent");function Jf(e){let t=e.replace(/\s/g,""),o=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-o)}s(Jf,"base64Size");function Gr(e){return e<1024?`${e} B`:e<1024*1024?`${Math.ceil(e/1024)} KB`:`${Math.ceil(e/(1024*1024))} MB`}s(Gr,"formatBytes");var rk=new Set(["inbox-chat","via-herald"]);function Xf(e){let t=e.map(o=>o?.metadata?.alchemy?.kind).filter(o=>typeof o=="string"&&o.length>0);return t.length===0?!0:t.some(o=>rk.has(o))}s(Xf,"writtenByAPerson");var sk="[from AlchemyLab, not a user message]";function Qf(e){let t=e.startsWith(sk);return["<system-reminder>",t?"This note reached you while you worked:":"The user sent the following message:",e,"",t?"Take it into account and continue with your tasks.":"Please address this message and continue with your tasks.","</system-reminder>"].join(`
1434
- `)}s(Qf,"raisedMidTurn");var ik=/\bto=functions\.|^\s*functions\.[A-Za-z_]+\s*[({]/m;function Zf(e){let t=e.filter(r=>r.type==="text"),o=t.filter(r=>(r.text??"").trim().length>0&&!ik.test(r.text??"")),n=o.length>0?o[o.length-1]:void 0;return{drop:t.filter(r=>r!==n).map(r=>r.id),answered:n!==void 0}}s(Zf,"asideTextToDrop");function em(e){let t=e.filter(r=>!(r.info.role==="assistant"&&r.info.aside)&&!(r.info.role==="user"&&r.info.quiet)),o=Qe.latest(t),n=o.user?void 0:Qe.latest(e.filter(r=>r.info.role==="user")).user;return{lastUser:o.user??n,lastAssistant:o.assistant,lastFinished:o.finished,tasks:o.tasks}}s(em,"scanForLoop");import tm from"fs";import ak from"path";var aa={info:s((e,t)=>process.stderr.write(`level=INFO service=session.pause message=${JSON.stringify(e)} ${JSON.stringify(t??{})}
1435
- `),"info"),warn:s((e,t)=>process.stderr.write(`level=WARN service=session.pause message=${JSON.stringify(e)} ${JSON.stringify(t??{})}
1436
- `),"warn")},om=ak.join(me.Path.state,"pause.json"),Hn=!1,Yn=new Set;try{let e=JSON.parse(tm.readFileSync(om,"utf8"));Hn=e?.paused===!0;for(let t of Array.isArray(e?.waiting)?e.waiting:[])typeof t=="string"&&Yn.add(t)}catch{}function Hc(){try{tm.writeFileSync(om,JSON.stringify({paused:Hn,waiting:[...Yn]}))}catch(e){aa.warn("could not save the pause state",{error:String(e)})}}s(Hc,"save");var Kn;(i=>{function e(){return Hn}i.isPaused=e,s(e,"isPaused");function t(a){Yn.has(a)||(Yn.add(a),aa.info("turn held while paused",{sessionID:a}),Hc())}i.hold=t,s(t,"hold");function o(){Hn||(Hn=!0,aa.info("paused"),Hc())}i.pause=o,s(o,"pause");function n(){let a=[...Yn];return Hn=!1,Yn.clear(),aa.info("resumed",{waiting:a.length}),Hc(),a}i.resume=n,s(n,"resume");function r(){return{paused:Hn,waiting:[...Yn]}}i.state=r,s(r,"state")})(Kn||={});globalThis.AI_SDK_LOG_WARNINGS=!1;var bk=ye.decodeUnknownExit(ct.Info),xk=ye.decodeUnknownExit(ct.Part),sm=10*1024*1024,vk=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),Ik=`Use this tool to return your final response in the requested structured format.
1437
-
1438
- IMPORTANT:
1439
- - You MUST call this tool exactly once at the end of your response
1440
- - The input must be valid JSON matching the required schema
1441
- - Complete all necessary research and tool calls BEFORE calling this tool
1442
- - This tool provides your final answer - no further actions are taken after calling it`,Sk="IMPORTANT: The user has requested structured output. You MUST use the StructuredOutput tool to provide your final response. Do NOT respond with plain text - you MUST call the StructuredOutput tool with your answer formatted according to the schema.";function kk(e){let t=e.replace(/\s/g,""),o=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-o)}s(kk,"mcpResourceBase64Size");function Jc(e){return e<1024?`${e} B`:e<1024*1024?`${Math.ceil(e/1024)} KB`:`${Math.ceil(e/(1024*1024))} MB`}s(Jc,"formatMcpResourceBytes");function im(e){return e.state.status==="error"&&e.state.metadata?.interrupted===!0}s(im,"isOrphanedInterruptedTool");var Hr=class extends yk.Service()("@opencode/SessionPrompt"){static{s(this,"Service")}},Dk=hk.effect(Hr,C.gen(function*(){let e=yield*po.Service,t=yield*ce.Service,o=yield*Nt.Service,n=yield*yt.Service,r=yield*zo.Service,i=yield*Pr.Service,a=yield*dt.Service,c=yield*yi.Service,d=yield*De.Service,u=yield*Ye.Service,l=yield*Se.Service,m=yield*uo.Service,h=yield*ut.Service,g=yield*Ko.Service,w=yield*Pn.Service,k=yield*ko.Service,p=yield*pk.ChildProcessSpawner,f=yield*gk.Scope,S=yield*Lo.Service,y=yield*qo.Service,v=yield*Ar.Service,P=yield*ho.Service,b=yield*un.Service,T=yield*mo.Service,E=yield*we.Service,j=yield*Me.Service,_=yield*Xe.Service,{db:W}=_,ie=C.fn("SessionPrompt.ops")(function*(){return{cancel:s(I=>M(I),"cancel"),resolvePromptParts:s(I=>R(I),"resolvePromptParts"),prompt:s(I=>N(I).pipe(C.catch(C.die)),"prompt")}}),M=C.fn("SessionPrompt.cancel")(function*(I){yield*C.logInfo("cancel",{"session.id":I}),yield*y.cancel(I)}),$=new Map,x=C.fn("SessionPrompt.stopForPause")(function*(){let I=yield*y.busy();for(let z of I)Kn.hold(z);return yield*C.forEach(I,z=>y.cancel(z),{concurrency:"unbounded",discard:!0}),I}),R=C.fn("SessionPrompt.resolvePromptParts")(function*(I){let z=yield*B.context,ue=[{type:"text",text:I}],se=Ra.files(I),J=new Set;return yield*C.forEach(se,C.fnUntraced(function*(ee){let oe=ee[1];if(!oe||J.has(oe))return;J.add(oe);let H=oe.startsWith("~/")?nm.join(ck.homedir(),oe.slice(2)):nm.resolve(z.worktree,oe),Le=yield*l.stat(H).pipe(C.option);if(Kc.isNone(Le)){let _e=yield*o.get(oe);_e&&ue.push({type:"agent",name:_e.name});return}let mt=Le.value;ue.push({type:"file",url:fk(H).href,filename:oe,mime:mt.type==="Directory"?"application/x-directory":"text/plain"})}),{concurrency:"unbounded",discard:!0}),ue}),A=C.fn("SessionPrompt.ensureTitle")(function*(I){if(I.session.parentID||!ce.isDefaultTitle(I.session.title))return;let z=s(G=>G.info.role==="user"&&!G.parts.every($e=>"synthetic"in $e&&$e.synthetic),"real"),ue=I.history.findIndex(z);if(ue===-1||I.history.filter(z).length!==1)return;let se=I.history.slice(0,ue+1),J=se[ue];if(!J||J.info.role!=="user")return;let ee=J.info,oe=J.parts.filter(G=>G.type==="subtask"),H=oe.length>0&&J.parts.every(G=>G.type==="subtask"),Le=yield*o.get("title");if(!Le)return;let mt=Le.model?yield*n.getModel(Le.model.providerID,Le.model.modelID):(yield*n.getSmallModel(I.providerID))??(yield*n.getModel(I.providerID,I.modelID)),_e=H?[{role:"user",content:oe.map(G=>G.prompt).join(`
1443
- `)}]:yield*Qe.toModelMessagesEffect(se,mt),fe=(yield*T.stream({agent:Le,user:ee,system:[],small:!0,tools:{},model:mt,sessionID:I.session.id,retries:2,messages:[{role:"user",content:`Generate a title for this conversation:
1444
- `},..._e]}).pipe(jo.filter(nt.is.textDelta),jo.map(G=>G.text),jo.mkString,C.orDie)).replace(/<think>[\s\S]*?<\/think>\s*/g,"").split(`
1445
- `).map(G=>G.trim()).find(G=>G.length>0);if(!fe)return;let Ge=fe.length>100?fe.substring(0,97)+"...":fe;yield*t.setTitle({sessionID:I.session.id,title:Ge}).pipe(C.catchCause(G=>C.logError("failed to generate title",{error:To.squash(G)})))}),O=C.fn("SessionPrompt.handleSubtask")(function*(I){let{task:z,model:ue,lastUser:se,sessionID:J,session:ee,msgs:oe}=I,H=yield*B.context,Le=yield*ie(),{task:mt}=yield*g.named(),_e=z.model?yield*U(z.model.providerID,z.model.modelID,J):ue,et=yield*t.updateMessage({id:it.ascending(),role:"assistant",parentID:se.id,sessionID:J,mode:z.agent,agent:z.agent,variant:se.model.variant,path:{cwd:H.directory,root:H.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:_e.id,providerID:_e.providerID,time:{created:Date.now()}}),fe=yield*t.updatePart({id:Ce.ascending(),messageID:et.id,sessionID:et.sessionID,type:"tool",callID:rm(),tool:qn.id,state:{status:"running",input:{prompt:z.prompt,description:z.description,subagent_type:z.agent,command:z.command},time:{start:Date.now()}}}),Ge={prompt:z.prompt,description:z.description,subagent_type:z.agent,command:z.command};yield*a.trigger("tool.execute.before",{tool:qn.id,sessionID:J,callID:fe.id},{args:Ge});let G=yield*o.get(z.agent);if(!G){let Te=(yield*o.list()).filter(he=>!he.hidden).map(he=>he.name),ke=Te.length?` Available agents: ${Te.join(", ")}`:"",ne=new Mo.Unknown({message:`Agent not found: "${z.agent}".${ke}`});throw yield*E.publish(ce.Event.Error,{sessionID:J,error:ne.toObject()}),ne}let $e,Ae=new AbortController,ve=yield*mt.execute(Ge,{agent:z.agent,messageID:et.id,sessionID:J,abort:Ae.signal,callID:fe.callID,extra:{bypassAgentCheck:!0,promptOps:Le},messages:oe,metadata:s(Te=>C.gen(function*(){fe=yield*t.updatePart({...fe,type:"tool",state:{...fe.state,...Te}})}),"metadata"),ask:s(Te=>u.ask({...Te,sessionID:J,ruleset:Ye.merge(G.permission,ee.permission??[])}).pipe(C.orDie),"ask")}).pipe(C.catchCause(Te=>{let ke=To.squash(Te);return $e=ke instanceof Error?ke:new Error(String(ke)),C.logError("subtask execution failed",{error:$e,agent:z.agent,description:z.description})}),C.onInterrupt(()=>C.gen(function*(){Ae.abort(),et.finish="tool-calls",et.time.completed=Date.now(),yield*t.updateMessage(et),fe.state.status==="running"&&(yield*t.updatePart({...fe,state:{status:"error",error:"Cancelled",time:{start:fe.state.time.start,end:Date.now()},metadata:fe.state.metadata,input:fe.state.input}}))}))),ht=ve?.attachments?.map(Te=>({...Te,id:Ce.ascending(),sessionID:J,messageID:et.id}));if(yield*a.trigger("tool.execute.after",{tool:qn.id,sessionID:J,callID:fe.id,args:Ge},ve),et.finish="tool-calls",et.time.completed=Date.now(),yield*t.updateMessage(et),ve&&fe.state.status==="running"&&(yield*t.updatePart({...fe,state:{status:"completed",input:fe.state.input,title:ve.title,metadata:ve.metadata,output:ve.output,attachments:ht,time:{...fe.state.time,end:Date.now()}}})),ve||(yield*t.updatePart({...fe,state:{status:"error",error:$e?`Tool execution failed: ${$e.message}`:"Tool execution failed",time:{start:fe.state.status==="running"?fe.state.time.start:Date.now(),end:Date.now()},metadata:fe.state.status==="pending"?void 0:fe.state.metadata,input:fe.state.input}})),!z.command)return;let Mt={id:it.ascending(),sessionID:J,role:"user",time:{created:Date.now()},agent:se.agent,model:se.model};yield*t.updateMessage(Mt),yield*t.updatePart({id:Ce.ascending(),messageID:Mt.id,sessionID:J,type:"text",text:"Summarize the task tool output above and continue with your task.",synthetic:!0})}),F=C.fn("SessionPrompt.shellImpl")(function*(I,z){return yield*C.uninterruptibleMask(ue=>C.gen(function*(){let se=z?z.open.pipe(C.asVoid):C.void,{msg:J,part:ee,cwd:oe}=yield*C.gen(function*(){let G=yield*B.context,$e=yield*t.get(I.sessionID).pipe(C.orDie);$e.revert&&(yield*v.cleanup($e));let Ae=yield*o.get(I.agent);if(!Ae){let he=(yield*o.list()).filter(ot=>!ot.hidden).map(ot=>ot.name),Ue=he.length?` Available agents: ${he.join(", ")}`:"",He=new Mo.Unknown({message:`Agent not found: "${I.agent}".${Ue}`});throw yield*E.publish(ce.Event.Error,{sessionID:I.sessionID,error:He.toObject()}),He}let ve=I.model??Ae.model??(yield*pe(I.sessionID)),ht={id:I.messageID??it.ascending(),sessionID:I.sessionID,time:{created:Date.now()},role:"user",agent:I.agent,model:{providerID:ve.providerID,modelID:ve.modelID}};yield*t.updateMessage(ht);let Mt={type:"text",id:Ce.ascending(),messageID:ht.id,sessionID:I.sessionID,text:"The following tool was executed by the user",synthetic:!0};yield*t.updatePart(Mt);let Te={id:it.ascending(),sessionID:I.sessionID,parentID:ht.id,mode:I.agent,agent:I.agent,cost:0,path:{cwd:G.directory,root:G.worktree},time:{created:Date.now()},role:"assistant",tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:ve.modelID,providerID:ve.providerID};yield*t.updateMessage(Te);let ke=Date.now(),ne={type:"tool",id:Ce.ascending(),messageID:Te.id,sessionID:I.sessionID,tool:Ns.ToolID,callID:rm(),state:{status:"running",time:{start:ke},input:{command:I.command}}};return yield*t.updatePart(ne),{msg:Te,part:ne,cwd:G.directory}}).pipe(C.ensuring(se)),H=yield*d.get(),Le=li.preferred(H.shell),mt=li.args(Le,I.command,oe),_e="",et=!1,fe=C.uninterruptible(C.gen(function*(){et&&(_e+=`
1446
-
1447
- `+["<metadata>","User aborted the command","</metadata>"].join(`
1448
- `));let G=Date.now();J.time.completed||(J.time.completed=G,yield*t.updateMessage(J)),ee.state.status==="running"&&(ee.state={status:"completed",time:{...ee.state.time,end:G},input:ee.state.input,title:"",metadata:{output:_e},output:_e},yield*t.updatePart(ee))})),Ge=yield*ue(C.gen(function*(){let G=yield*a.trigger("shell.env",{cwd:oe,sessionID:I.sessionID,callID:ee.callID},{env:{}}),$e=uk.make(Le,mt,{cwd:oe,extendEnv:!0,env:{...G.env,TERM:"dumb"},stdin:"ignore",forceKillAfter:"3 seconds"}),Ae=yield*p.spawn($e);yield*jo.runForEach(jo.decodeText(Ae.all),ve=>C.gen(function*(){_e+=ve,ee.state.status==="running"&&(ee.state.metadata={output:_e},yield*t.updatePart(ee))})),yield*Ae.exitCode}).pipe(C.scoped,C.orDie)).pipe(C.exit);return hn.isFailure(Ge)&&To.hasInterrupts(Ge.cause)&&!To.hasDies(Ge.cause)&&(et=!0),yield*fe,hn.isFailure(Ge)&&!et&&!To.hasInterruptsOnly(Ge.cause)?yield*C.failCause(Ge.cause):{info:J,parts:[ee]}}))}),U=C.fn("SessionPrompt.getModel")(function*(I,z,ue){let se=yield*n.getModel(I,z).pipe(C.exit);if(hn.isSuccess(se))return se.value;let J=To.squash(se.cause);if(yt.ModelNotFoundError.isInstance(J)){let ee=J.suggestions?.length?` Did you mean: ${J.suggestions.join(", ")}?`:"";yield*E.publish(ce.Event.Error,{sessionID:ue,error:new Mo.Unknown({message:`Model not found: ${J.providerID}/${J.modelID}.${ee}`}).toObject()})}return yield*C.die(J)}),pe=C.fnUntraced(function*(I){let z=yield*W.select({model:Dt.model}).from(Dt).where(wk(Dt.id,I)).get().pipe(C.orDie);if(z?.model)return{providerID:co.ID.make(z.model.providerID),modelID:xn.ID.make(z.model.id),...z.model.variant&&z.model.variant!=="default"?{variant:z.model.variant}:{}};let ue=yield*t.findMessage(I,se=>se.info.role==="user"&&!!se.info.model).pipe(C.orDie);return Kc.isSome(ue)&&ue.value.info.role==="user"?ue.value.info.model:yield*n.defaultModel().pipe(C.orDie)}),re=C.fn("SessionPrompt.createUserMessage")(function*(I){let z=I.agent?void 0:(yield*t.get(I.sessionID).pipe(C.orElseSucceed(()=>{})))?.agent,ue=I.agent||(z&&(yield*o.get(z))?z:void 0),se=ue?yield*o.get(ue):yield*o.defaultInfo();if(!se){let G=(yield*o.list()).filter(ve=>!ve.hidden).map(ve=>ve.name),$e=G.length?` Available agents: ${G.join(", ")}`:"",Ae=new Mo.Unknown({message:`Agent not found: "${ue}".${$e}`});throw yield*E.publish(ce.Event.Error,{sessionID:I.sessionID,error:Ae.toObject()}),Ae}let J=I.model??se.model??(yield*pe(I.sessionID)),ee=!I.variant&&se.variant?yield*n.getModel(J.providerID,J.modelID).pipe(C.catchIf(yt.ModelNotFoundError.isInstance,()=>C.succeed(void 0))):void 0,oe=I.variant??Ke.nearestVariant(se.variant,Object.keys(ee?.variants??{})),H={id:I.messageID??it.ascending(),role:"user",sessionID:I.sessionID,time:{created:Date.now()},tools:I.tools,...I.noReply===!0?{quiet:!0}:{},agent:se.name,model:{providerID:J.providerID,modelID:J.modelID,variant:oe},system:I.system,format:I.format},Le=yield*t.get(I.sessionID).pipe(C.orDie);(Le.agent!==H.agent||Le.model?.providerID!==H.model.providerID||Le.model?.id!==H.model.modelID||(Le.model?.variant==="default"?void 0:Le.model?.variant)!==H.model.variant)&&(yield*t.setAgentModel({sessionID:I.sessionID,agent:H.agent,model:{id:H.model.modelID,providerID:H.model.providerID,variant:H.model.variant??"default"},time:H.time.created})),yield*C.addFinalizer(()=>S.clear(H.id));let mt=s(G=>({...G,id:G.id?Ce.make(G.id):Ce.ascending()}),"assign"),_e=C.fn("SessionPrompt.resolveUserPart")(function*(G){if(G.type==="file"){if(G.source?.type==="resource"){let{clientName:Ae,uri:ve}=G.source;yield*C.logInfo("mcp resource",{clientName:Ae,uri:ve,mime:G.mime});let ht=[{messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`Reading MCP resource: ${G.filename} (${ve})`}],Mt=yield*m.readResource(Ae,ve).pipe(C.exit);if(hn.isSuccess(Mt)){let Te=Mt.value;if(!Te)throw new Error(`Resource not found: ${Ae}/${ve}`);let ke=Array.isArray(Te.contents)?Te.contents:[Te.contents];for(let ne of ke)if(!(!ne||typeof ne!="object")){if("text"in ne&&typeof ne.text=="string"&&ne.text)ht.push({messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:ne.text});else if("blob"in ne&&typeof ne.blob=="string"&&ne.blob){let he="mimeType"in ne&&typeof ne.mimeType=="string"?ne.mimeType:G.mime,Ue="uri"in ne&&typeof ne.uri=="string"?ne.uri:G.filename,He=kk(ne.blob);if(!vk.has(he)){ht.push({messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`[Binary MCP resource omitted: ${Ue??ve} (${he}, ${Jc(He)}) is not a supported attachment type]`});continue}if(He>sm){ht.push({messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`[Binary MCP resource omitted: ${Ue??ve} (${he}, ${Jc(He)}) exceeds ${Jc(sm)}]`});continue}ht.push({messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`[Binary MCP resource attached: ${Ue??ve} (${he})]`}),ht.push({messageID:H.id,sessionID:I.sessionID,type:"file",mime:he,filename:Ue,url:`data:${he};base64,${ne.blob}`})}}}else{let Te=To.squash(Mt.cause);yield*C.logError("failed to read MCP resource",{error:Te,clientName:Ae,uri:ve});let ke=Te instanceof Error?Te.message:String(Te);ht.push({messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`Failed to read MCP resource ${G.filename}: ${ke}`})}return ht}let $e=new URL(G.url);switch($e.protocol){case"data:":if(G.mime==="text/plain")return[{messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify({filePath:G.filename})}`},{messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:qf(G.url)},{...G,messageID:H.id,sessionID:I.sessionID}];break;case"file:":{yield*C.logInfo("file",{mime:G.mime});let Ae=Yc(G.url),ve=(yield*l.isDir(Ae))?"application/x-directory":G.mime,{read:ht}=yield*g.named(),Mt=s((Te,ke)=>{let ne=new AbortController;return ht.execute(Te,{sessionID:I.sessionID,abort:ne.signal,agent:I.agent,messageID:H.id,extra:{bypassCwdCheck:!0,...ke},messages:[],metadata:s(()=>C.void,"metadata"),ask:s(()=>C.void,"ask")}).pipe(C.onInterrupt(()=>C.sync(()=>ne.abort())))},"execRead");if(ve==="text/plain"){let Te,ke,ne={start:$e.searchParams.get("start"),end:$e.searchParams.get("end")};if(ne.start!=null){let ot=G.url.split("?")[0],Zt=parseInt(ne.start),en=ne.end?parseInt(ne.end):void 0;if(Zt===en){let ei=yield*h.documentSymbol(ot).pipe(C.catch(()=>C.succeed([])));for(let ns of ei){let St;if("range"in ns?St=ns.range:"location"in ns&&(St=ns.location.range),St?.start?.line&&St?.start?.line===Zt){Zt=St.start.line,en=St?.end?.line??Zt;break}}}Te=Math.max(Zt,1),en&&(ke=en-(Te-1))}let he={filePath:Ae,offset:Te,limit:ke},Ue=[{messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(he)}`}],He=yield*n.getModel(H.model.providerID,H.model.modelID).pipe(C.flatMap(ot=>Mt(he,{model:ot})),C.exit);if(hn.isSuccess(He)){let ot=He.value;Ue.push({messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:ot.output}),ot.attachments?.length?Ue.push(...ot.attachments.map(Zt=>({...Zt,synthetic:!0,filename:Zt.filename??G.filename,messageID:H.id,sessionID:I.sessionID}))):Ue.push({...G,mime:ve,messageID:H.id,sessionID:I.sessionID})}else{let ot=To.squash(He.cause);yield*C.logError("failed to read file",{error:ot,filepath:Ae});let Zt=ot instanceof Error?ot.message:String(ot);yield*E.publish(ce.Event.Error,{sessionID:I.sessionID,error:new Mo.Unknown({message:Zt}).toObject()}),Ue.push({messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${Ae} with the following error: ${Zt}`})}return Ue}if(ve==="application/x-directory"){let Te={filePath:Ae},ke=yield*Mt(Te).pipe(C.exit);if(hn.isFailure(ke)){let ne=To.squash(ke.cause);yield*C.logError("failed to read directory",{error:ne,filepath:Ae});let he=ne instanceof Error?ne.message:String(ne);return yield*E.publish(ce.Event.Error,{sessionID:I.sessionID,error:new Mo.Unknown({message:he}).toObject()}),[{messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${Ae} with the following error: ${he}`}]}return[{messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(Te)}`},{messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:ke.value.output},{...G,mime:ve,messageID:H.id,sessionID:I.sessionID}]}return[{messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: {"filePath":"${Ae}"}`},{id:G.id,messageID:H.id,sessionID:I.sessionID,type:"file",url:`data:${ve};base64,`+Buffer.from(yield*l.readFile(Ae).pipe(C.catch(C.die))).toString("base64"),mime:ve,filename:G.filename,source:G.source}]}}}if(G.type==="agent"){let Ae=Ye.evaluate("task",G.name,se.permission).action==="deny"?" . Invoked by user; guaranteed to exist.":"";return[{...G,messageID:H.id,sessionID:I.sessionID},{messageID:H.id,sessionID:I.sessionID,type:"text",synthetic:!0,text:" Use the above message and context to generate a prompt and call the task tool with subagent: "+G.name+Ae}]}return[{...G,messageID:H.id,sessionID:I.sessionID}]}),et=yield*C.forEach(I.parts,_e,{concurrency:"unbounded"}).pipe(C.map(G=>G.flat().map(mt)));yield*a.trigger("chat.message",{sessionID:I.sessionID,agent:I.agent,model:I.model,messageID:I.messageID,variant:I.variant},{message:H,parts:et});let fe=yield*C.forEach(et,G=>G.type==="file"&&G.mime.startsWith("image/")?k.normalize(G).pipe(C.catchIf($e=>$e instanceof ko.ResizerUnavailableError,()=>C.succeed(G))):C.succeed(G)),Ge=bk(H,{errors:"all",propertyOrder:"original"});hn.isFailure(Ge)&&(yield*C.logError("invalid user message before save",{sessionID:I.sessionID,messageID:H.id,agent:H.agent,model:H.model,cause:To.pretty(Ge.cause)}));for(let[G,$e]of fe.entries()){let Ae=xk($e,{errors:"all",propertyOrder:"original"});hn.isSuccess(Ae)||(yield*C.logError("invalid user part before save",{sessionID:I.sessionID,messageID:H.id,partID:$e.id,partType:$e.type,index:G,cause:To.pretty(Ae.cause),part:$e}))}yield*t.updateMessage(H);for(let G of fe)yield*t.updatePart(G);return{info:H,parts:fe}},C.scoped),Z=C.fn("SessionPrompt.inFlightTool")(function*(I){let z=yield*Qe.filterCompactedEffect(I).pipe(C.provideService(Xe.Service,_));for(let ue=z.length-1;ue>=0;ue--){let se=z[ue];if(se.info.role!=="assistant"||se.info.aside)continue;let J=se.parts.find(ee=>ee.type==="tool"&&(ee.state.status==="running"||ee.state.status==="pending"));return J&&J.type==="tool"?J.tool:null}return null}),Q=["A tool you called is still running and its result has not arrived. The user just wrote to you.","Answer them now, in a sentence or two, from what you already know. You cannot use tools until the run returns, so do not promise to look anything up.","Do not restate at length what you are doing; if their message changes the work, say what you will do once the run returns."].join(" "),D=C.fn("SessionPrompt.aside")(function*(I){let z=yield*B.context,ue=yield*Qe.filterCompactedEffect(I.sessionID).pipe(C.provideService(Xe.Service,_)),se=yield*U(I.user.model.providerID,I.user.model.modelID,I.sessionID),J=yield*o.get(I.user.agent);if(!J)return null;let ee={id:it.ascending(),parentID:I.user.id,role:"assistant",mode:J.name,agent:J.name,variant:I.user.model.variant,path:{cwd:z.directory,root:z.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:se.id,providerID:se.providerID,time:{created:Date.now()},sessionID:I.sessionID,aside:!0};yield*t.updateMessage(ee);let oe=yield*r.create({assistantMessage:ee,sessionID:I.sessionID,model:se}),[H,Le,mt]=yield*C.all([b.environment(se),S.system().pipe(C.orDie),Qe.toModelMessagesEffect(ue,se,{runningToolNote:`[${I.running} is still running. You are answering the user beside it; its result arrives when it finishes.]`})]);yield*C.logInfo("aside",{"session.id":I.sessionID,running:I.running,messageID:ee.id}),yield*oe.process({user:I.user,agent:J,permission:I.session.permission,sessionID:I.sessionID,parentSessionID:I.session.parentID,system:[...H,...Le,Q],messages:mt,tools:{},model:se});let _e=yield*q(I.sessionID);if(_e.info.id!==ee.id)return _e;let{drop:et,answered:fe}=Zf(_e.parts);if(!fe)return yield*C.logWarning("aside wrote no usable answer; the message waits for the run",{"session.id":I.sessionID,messageID:ee.id}),yield*t.removeMessage({sessionID:I.sessionID,messageID:ee.id}),null;for(let Ge of et)yield*t.removePart({sessionID:I.sessionID,messageID:ee.id,partID:Ge});return et.length>0?yield*q(I.sessionID):_e}),N=C.fn("SessionPrompt.prompt")(function*(I){let z=yield*t.get(I.sessionID).pipe(C.orDie);yield*v.cleanup(z);let ue=yield*re(I);yield*t.touch(I.sessionID);let se=[];for(let[oe,H]of Object.entries(I.tools??{}))se.push({permission:oe,action:H?"allow":"deny",pattern:"*"});if(se.length>0&&(z.permission=se,yield*t.setPermission({sessionID:z.id,permission:se})),I.noReply===!0)return ue;let J=(yield*y.busy()).includes(I.sessionID);if(J&&Xf(ue.parts)){let oe=Jt.endForPerson(I.sessionID),H=oe?null:yield*Z(I.sessionID);if($.set(ue.info.id,{sessionID:I.sessionID,at:Date.now(),how:oe?"step ended":H?`in ${H}`:"between steps"}),H){let Le=yield*D({sessionID:I.sessionID,session:z,user:ue.info,running:H}).pipe(C.catchCause(mt=>C.logWarning("aside failed; the message waits for the run",{"session.id":I.sessionID,cause:String(mt)}).pipe(C.as(null))));if(Le)return Le}}let ee=yield*zt({sessionID:I.sessionID});return J&&Ma.compareAscending(ee.info.id,ue.info.id)<0&&(ee=yield*zt({sessionID:I.sessionID})),ee}),q=C.fnUntraced(function*(I){let z=yield*t.findMessage(I,se=>se.info.role!=="user").pipe(C.orDie);if(Kc.isSome(z))return z.value;let ue=yield*t.messages({sessionID:I,limit:1}).pipe(C.orDie);if(ue.length>0)return ue[0];throw new Error("Impossible")}),te=C.fn("SessionPrompt.turnPrefix")(function*(I){let z=yield*ie(),ue=yield*Ws.resolve({...I,promptOps:z}).pipe(C.provideService(dt.Service,a),C.provideService(Ye.Service,u),C.provideService(Ko.Service,g),C.provideService(uo.Service,m),C.provideService(Pn.Service,w),C.provideService(Me.Service,j)),[se,J,ee,oe]=yield*C.all([b.skills(I.agent),b.environment(I.model),S.system().pipe(C.orDie),b.mcp(I.agent,I.session.permission)]),H=[...J,...ee,...oe?[oe]:[],...se?[se]:[]];return{tools:ue,system:H}}),Fe=s((I,z,ue)=>se=>C.gen(function*(){let J=ue.find(mt=>mt.info.id===se.parentID)?.info;if(!J||J.role!=="user"||J.format?.type==="json_schema")return;let ee=yield*o.get(se.agent);if(!ee)return;let{tools:oe,system:H}=yield*te({agent:ee,session:I,model:z,processor:{message:{id:se.id},updateToolCall:s(()=>C.succeed(void 0),"updateToolCall"),completeToolCall:s(()=>C.void,"completeToolCall")},bypassAgentCheck:!1,messages:ue}),Le=Object.fromEntries(Object.entries(oe).map(([mt,_e])=>[mt,{..._e,execute:s(async()=>"Not run: this step only writes the summary.","execute")}]));return{agent:ee,user:J,system:H,tools:Le,permission:I.permission,parentSessionID:I.parentID}}).pipe(C.catchCause(J=>C.logWarning("compaction: the session's prefix could not be rebuilt; summarizing without it",{"session.id":I.id,cause:String(J).slice(0,500)}).pipe(C.as(void 0)))),"compactionPrefix"),ft=C.fn("SessionPrompt.run")(function*(I){let z=yield*B.context,ue,se=0,J=yield*t.get(I).pipe(C.orDie);for(;;){if(Kn.isPaused()){Kn.hold(I);break}yield*e.set(I,{type:"busy"}),yield*C.logInfo("loop",{"session.id":I,step:se});let ee=yield*Qe.filterCompactedEffect(I).pipe(C.provideService(Xe.Service,_)),{lastUser:oe,lastAssistant:H,lastFinished:Le,tasks:mt}=em(ee);if(!oe)throw new Error("No user message found in stream. This should never happen.");let _e=ee.findLast(he=>he.info.role==="assistant"&&he.info.id===H?.id),et=_e?.parts.some(he=>he.type==="tool"&&!he.metadata?.providerExecuted&&!im(he))??!1;if(H?.finish&&!["tool-calls","unknown"].includes(H.finish)&&!et&&H.parentID===oe.id){let he=_e?.parts.find(Ue=>Ue.type==="tool"&&im(Ue));he&&(yield*C.logWarning("loop exit with orphaned interrupted tool",{"session.id":I,messageID:H.id,tool:he.tool,callID:he.callID})),yield*C.logInfo("exiting loop",{"session.id":I});break}se++,se===1&&(yield*A({session:J,modelID:oe.model.modelID,providerID:oe.model.providerID,history:ee}).pipe(C.ignore,C.forkIn(f)));let fe=yield*U(oe.model.providerID,oe.model.modelID,I),Ge=mt.pop();if(Ge?.type==="subtask"){yield*O({task:Ge,model:fe,lastUser:oe,sessionID:I,session:J,msgs:ee});continue}if(Ge?.type==="compaction"){if((yield*i.process({messages:ee,parentID:oe.id,sessionID:I,auto:Ge.auto,overflow:Ge.overflow,prefix:Fe(J,fe,ee)}))==="stop")break;continue}if(Le&&Le.summary!==!0&&(yield*i.isOverflow({tokens:Le.tokens,model:fe}))){yield*i.create({sessionID:I,agent:oe.agent,model:oe.model,auto:!0});continue}let G=yield*o.get(oe.agent);if(!G){let he=(yield*o.list()).filter(ot=>!ot.hidden).map(ot=>ot.name),Ue=he.length?` Available agents: ${he.join(", ")}`:"",He=new Mo.Unknown({message:`Agent not found: "${oe.agent}".${Ue}`});throw yield*E.publish(ce.Event.Error,{sessionID:I,error:He.toObject()}),He}let $e=G.steps??1/0,Ae=se>=$e;ee=yield*Fs.apply({messages:ee,agent:G,session:J}).pipe(C.provideService(Me.Service,j),C.provideService(Se.Service,l),C.provideService(ce.Service,t));let ve={id:it.ascending(),parentID:oe.id,role:"assistant",mode:G.name,agent:G.name,variant:oe.model.variant,path:{cwd:z.directory,root:z.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:fe.id,providerID:fe.providerID,time:{created:Date.now()},sessionID:I};yield*t.updateMessage(ve);for(let[he,Ue]of $)Ue.sessionID===I&&($.delete(he),yield*C.logWarning("person message read",{"session.id":I,messageID:he,how:Ue.how,waitedMs:Date.now()-Ue.at}));let ht=Promise.withResolvers(),Mt=Jt.open(I,()=>ht.resolve()),Te=C.gen(function*(){ve.time.completed||(ve.error??=Qe.fromError(new DOMException("Aborted","AbortError"),{providerID:ve.providerID,aborted:!0}),ve.time.completed=Date.now(),yield*t.updateMessage(ve))}),ke=yield*r.create({assistantMessage:ve,sessionID:I,model:fe,preempt:C.promise(()=>ht.promise)}).pipe(C.onInterrupt(()=>Te));if((yield*C.gen(function*(){let Ue=ee.findLast(St=>St.info.role==="user")?.parts.some(St=>St.type==="agent")??!1,{tools:He,system:ot}=yield*te({agent:G,session:J,model:fe,processor:ke,bypassAgentCheck:Ue,messages:ee,gate:Mt});if(oe.format?.type==="json_schema"&&(He.StructuredOutput=lm({schema:oe.format.schema,onSuccess(St){ue=St}})),se===1&&(yield*P.summarize({sessionID:I,messageID:oe.id}).pipe(C.ignore,C.forkIn(f))),se>1&&Le){let St=new Set(ee.filter(Ot=>Ot.info.role==="assistant"&&Ot.info.aside).map(Ot=>Ot.info.parentID));for(let Ot of ee)if(!(Ot.info.role!=="user"||Ma.compareAscending(Ot.info.id,Le.id)<=0)&&!St.has(Ot.info.id))for(let Ro of Ot.parts)Ro.type!=="text"||Ro.ignored||Ro.synthetic||Ro.text.trim()&&(Ro.text=Qf(Ro.text))}yield*a.trigger("experimental.chat.messages.transform",{},{messages:ee});let Zt=yield*Qe.toModelMessagesEffect(ee,fe),en=oe.format??{type:"text"};en.type==="json_schema"&&ot.push(Sk);let ei=yield*ke.process({user:oe,agent:G,permission:J.permission,sessionID:I,parentSessionID:J.parentID,system:ot,messages:[...Zt,...Ae?[{role:"assistant",content:zl}]:[]],tools:He,model:fe,toolChoice:en.type==="json_schema"?"required":void 0,storeSystem:rt.on()?St=>C.gen(function*(){let Ot=rt.newestStored(ee),Ro=ee.at(-1)?.info.id;if(!Ot||!Ro)return;let ba=Ot.value.system?.at(-1);if(ba&&ba.after===Ro&&ba.text===St)return;let _m=rt.withSystem(Ot.value,{after:Ro,text:St});Ot.part.metadata={...Ot.part.metadata,[rt.METADATA_KEY]:_m},yield*t.updatePart(Ot.part)}):void 0});if(ue!==void 0)return ke.message.structured=ue,ke.message.finish=ke.message.finish??"stop",yield*t.updateMessage(ke.message),"break";if(ke.message.finish&&!["tool-calls","unknown"].includes(ke.message.finish)&&!ke.message.error){if(ke.message.finish==="content-filter")return ke.message.error=new ct.ContentFilterError({message:"The response was blocked by the provider's content filter"}).toObject(),yield*t.updateMessage(ke.message),yield*E.publish(ce.Event.Error,{sessionID:I,error:ke.message.error}),"break";if(en.type==="json_schema")return ke.message.error=new ct.StructuredOutputError({message:"Model did not produce structured output",retries:0}).toObject(),yield*t.updateMessage(ke.message),"break"}return ei==="stop"?"break":(ei==="compact"&&(yield*i.create({sessionID:I,agent:oe.agent,model:oe.model,auto:!0,overflow:!ke.message.finish})),"continue")}).pipe(C.ensuring(C.sync(()=>Jt.close(I,Mt))),C.ensuring(S.clear(ke.message.id)),C.onInterrupt(()=>Te)))==="break")break}return yield*i.prune({sessionID:I}).pipe(C.ignore,C.forkIn(f)),yield*q(I)}),zt=C.fn("SessionPrompt.loop")(function*(I){return Kn.isPaused()?(Kn.hold(I.sessionID),yield*q(I.sessionID)):yield*y.ensureRunning(I.sessionID,q(I.sessionID),ft(I.sessionID))}),It=C.fn("SessionPrompt.shell")(function*(I){let z=yield*mk.make();return yield*y.startShell(I.sessionID,q(I.sessionID),F(I,z),z)}),bn=C.fn("SessionPrompt.command")(function*(I){yield*C.logInfo("command",{"session.id":I.sessionID,command:I.command,agent:I.agent});let z=yield*c.get(I.command);if(!z){let ne=(yield*c.list()).map(He=>He.name),he=ne.length?` Available commands: ${ne.join(", ")}`:"",Ue=new Mo.Unknown({message:`Command not found: "${I.command}".${he}`});throw yield*E.publish(ce.Event.Error,{sessionID:I.sessionID,error:Ue.toObject()}),Ue}let ue=z.agent??I.agent,J=(I.arguments.match(Ak)??[]).map(ne=>ne.replace(Ck,"")),ee=yield*C.promise(async()=>z.template),oe=ee.match(am)??[],H=0;for(let ne of oe){let he=Number(ne.slice(1));he>H&&(H=he)}let Le=ee.replaceAll(am,(ne,he)=>{let Ue=Number(he),He=Ue-1;return He>=J.length?"":Ue===H?J.slice(He).join(" "):J[He]}),mt=ee.includes("$ARGUMENTS"),_e=Le.replaceAll("$ARGUMENTS",I.arguments);oe.length===0&&!mt&&I.arguments.trim()&&(_e=_e+`
1449
-
1450
- `+I.arguments);let et=Ra.shell(_e);if(et.length>0){let ne=yield*d.get(),he=li.preferred(ne.shell),Ue=yield*C.promise(()=>Promise.all(et.map(async([,ot])=>(await st.text([ot],{shell:he,nothrow:!0})).text))),He=0;_e=_e.replace(Rk,()=>Ue[He++])}_e=_e.trim();let fe=yield*C.gen(function*(){if(z.model)return yt.parseModel(z.model);if(z.agent){let ne=yield*o.get(z.agent);if(ne?.model)return ne.model}return I.model?yt.parseModel(I.model):yield*pe(I.sessionID)});yield*U(fe.providerID,fe.modelID,I.sessionID);let Ge=ue?yield*o.get(ue):yield*o.defaultInfo();if(!Ge){let ne=(yield*o.list()).filter(He=>!He.hidden).map(He=>He.name),he=ne.length?` Available agents: ${ne.join(", ")}`:"",Ue=new Mo.Unknown({message:`Agent not found: "${ue}".${he}`});throw yield*E.publish(ce.Event.Error,{sessionID:I.sessionID,error:Ue.toObject()}),Ue}let G=yield*R(_e),$e=new Set(I.parts?.filter(ne=>new URL(ne.url).protocol==="file:").map(ne=>Yc(ne.url))),Ae=G.filter(ne=>ne.type!=="file"||!$e.has(Yc(ne.url))),ve=Ge.mode==="subagent"&&z.subtask!==!1||z.subtask===!0,ht=ve?[{type:"subtask",agent:Ge.name,description:z.description??"",command:I.command,model:{providerID:fe.providerID,modelID:fe.modelID},prompt:G.find(ne=>ne.type==="text")?.text??""}]:[...Ae,...I.parts??[]],Mt=ve?I.agent??(yield*o.defaultInfo()).name:Ge.name,Te=ve?I.model?yt.parseModel(I.model):yield*pe(I.sessionID):fe;yield*a.trigger("command.execute.before",{command:I.command,sessionID:I.sessionID,arguments:I.arguments},{parts:ht});let ke=yield*N({sessionID:I.sessionID,messageID:I.messageID,model:Te,agent:Mt,parts:ht,variant:I.variant});return yield*E.publish(yi.Event.Executed,{name:I.command,sessionID:I.sessionID,arguments:I.arguments,messageID:ke.info.id}),ke});return Hr.of({cancel:M,stopForPause:x,prompt:N,loop:zt,shell:It,command:bn,resolvePromptParts:R})})),cm=ye.Struct({providerID:co.ID,modelID:xn.ID}),Ek=ye.Struct({sessionID:Et,messageID:ye.optional(it),model:ye.optional(cm),agent:ye.optional(ye.String),noReply:ye.optional(ye.Boolean),tools:ye.optional(ye.Record(ye.String,ye.Boolean)).annotate({description:"@deprecated tools and permissions have been merged, you can set permissions on the session itself now"}),format:ye.optional(ct.Format),system:ye.optional(ye.String),variant:ye.optional(ye.String),parts:ye.Array(ye.Union([ct.TextPartInput,ct.FilePartInput,ct.AgentPartInput,ct.SubtaskPartInput]).annotate({discriminator:"type"}))}),Xc=class extends ye.Class("SessionPrompt.LoopInput")({sessionID:Et}){static{s(this,"LoopInput")}},Tk=ye.Struct({sessionID:Et,messageID:ye.optional(it),agent:ye.String,model:ye.optional(cm),command:ye.String}),Pk=ye.Struct({messageID:ye.optional(it),sessionID:Et,agent:ye.optional(ye.String),model:ye.optional(ye.String),arguments:ye.String,command:ye.String,variant:ye.optional(ye.String),parts:ye.optional(ye.Array(ye.Union([ye.Struct({id:ye.optional(Ce),type:ye.Literal("file"),mime:ye.String,filename:ye.optional(ye.String),url:ye.String,source:ye.optional(ct.FilePartSource)})]).annotate({discriminator:"type"})))});function lm(e){let{$schema:t,...o}=e.schema;return lk({description:Ik,inputSchema:dk(o),async execute(n){return e.onSuccess(n),{output:"Structured output captured successfully.",title:"Structured Output",metadata:{valid:!0}}},toModelOutput({output:n}){return{type:"text",value:n.output}}})}s(lm,"createStructuredOutputTool");var Rk=/!`([^`]+)`/g,Ak=/(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi,am=/\$(\d+)/g,Ck=/^["']|["']$/g,Mk=ge.make({service:Hr,layer:Dk,deps:[po.node,ce.node,Nt.node,yt.node,zo.node,Pr.node,dt.node,yi.node,De.node,Ye.node,Se.node,uo.node,ut.node,Ko.node,Pn.node,ko.node,si.node,Lo.node,qo.node,Ar.node,ho.node,un.node,mo.node,we.node,Me.node,Xe.node]});var Jn={};ae(Jn,{ApplyInput:()=>tD,ApplyResult:()=>oD,Event:()=>hm,FileDiff:()=>Zk,FileStatus:()=>eD,Info:()=>Qk,Mode:()=>Xk,PatchApplyError:()=>zs,Service:()=>gn,Vcs:()=>Jn,node:()=>tl});import{Effect as qe,Layer as _k,Context as Uk,Schema as tt,Scope as jk}from"effect";import{formatPatch as Nk,structuredPatch as Fk}from"diff";var qs={};ae(qs,{BranchUpdated:()=>dm,Definitions:()=>Lk,VcsEvent:()=>qs});import{Schema as Ok}from"effect";var dm=kt.define({type:"vcs.branch.updated",schema:{branch:xo(Ok.String)}}),Lk=kt.inventory(dm);var Qc=2147483647,um=1e7,el=1e7,ca=s(e=>Nk(Fk(e,e,"","","","",{context:0})),"emptyPatch"),pm=s(e=>new Map(e.map(t=>[t.file,{additions:t.additions,deletions:t.deletions}])),"nums"),Bk=s((...e)=>{let t=new Map;return e.flat().forEach(o=>{t.has(o.file)||t.set(o.file,o)}),[...t.values()]},"merge"),$k=s(()=>({patches:new Map,capped:!1}),"emptyBatch"),Zc=s(e=>{let t="";for(let o=1;o<e.length;o++){let n=e[o];if(n==='"')return{value:t,end:o+1};if(n!=="\\"){t+=n;continue}let r=e[++o];r==="t"?t+=" ":r==="n"?t+=`
1451
- `:r==="r"?t+="\r":r==='"'||r==="\\"?t+=r:t+=r??""}},"parseQuotedPath"),Wk=s(e=>e.startsWith('"')?Zc(e)?.value??e:e.split(" ")[0],"parsePathToken"),Vs=s(e=>{if(!e||e==="/dev/null")return;let t=Wk(e);return t.startsWith("a/")||t.startsWith("b/")?t.slice(2):t},"fileFromDiffPath"),qk=s(e=>{if(e.startsWith('"')){let o=Zc(e),n=o?e.slice(o.end).trimStart():void 0;return n?n.startsWith('"')?Vs(Zc(n)?.value):Vs(n):void 0}let t=e.indexOf(" b/");if(t!==-1)return Vs(e.slice(t+1))},"fileFromGitHeader"),Vk=s(e=>{let t=/^\+\+\+ (.+)$/m.exec(e)?.[1],o=/^--- (.+)$/m.exec(e)?.[1],n=Vs(t)??Vs(o);if(n)return n;let r=/^diff --git (.+)$/m.exec(e)?.[1];return qk(r??"")},"fileFromPatchChunk"),zk=s(e=>{let t=[...e.text.matchAll(/(?:^|\n)diff --git /g)].map(n=>n[0].startsWith(`
1452
- `)?n.index+1:n.index),o=t.map((n,r)=>e.text.slice(n,t[r+1]??e.text.length));return e.truncated?o.slice(0,-1):o},"splitGitPatch"),Gk=qe.fnUntraced(function*(e,t,o,n,r){if(n.length===0)return{patches:new Map,capped:!1};let i=yield*e.patchAll(t,o,{context:r?.context??Qc,maxOutputBytes:el});return{patches:zk(i).reduce((a,c,d)=>{let u=Vk(c)??n[d]?.file;return u&&a.set(u,(a.get(u)??"")+c),a},new Map),capped:i.truncated}}),Hk=qe.fnUntraced(function*(e,t,o,n,r){let i=n.code==="??"||!o?yield*e.patchUntracked(t,n.file,{context:r?.context??Qc,maxOutputBytes:um}):yield*e.patch(t,o,n.file,{context:r?.context??Qc,maxOutputBytes:um});return!i.truncated&&i.text?i.text:ca(n.file)}),Yk=s((e,t,o)=>o+Buffer.byteLength(t)<=el?{patch:t,capped:!1}:{patch:ca(e),capped:!0},"totalPatch"),Kk=qe.fnUntraced(function*(e,t,o,n,r,i,a){if(i)return ca(n.file);let c=r.patches.get(n.file);return c!==void 0?c:n.code!=="??"&&r.capped?ca(n.file):yield*Hk(e,t,o,n,a)}),fm=qe.fnUntraced(function*(e,t,o,n,r,i,a){let c=[],d=0,u=!1;for(let l of n.toSorted((m,h)=>m.file.localeCompare(h.file))){let m=r.get(l.file)??(l.status==="added"?yield*e.statUntracked(t,l.file):void 0),h=yield*Kk(e,t,o,l,i,u,a),g=u?{patch:h,capped:!0}:Yk(l.file,h,d);u=u||g.capped,u||(d+=Buffer.byteLength(g.patch),u=d>=el),c.push({file:l.file,patch:g.patch,additions:m?.additions??0,deletions:m?.deletions??0,status:l.status})}return c}),mm=qe.fnUntraced(function*(e,t,o,n){let[r,i,a]=yield*qe.all([e.diff(t,o),e.stats(t,o),e.status(t)],{concurrency:3});return yield*fm(e,t,o,Bk(r,a.filter(c=>c.code==="??")),pm(i),yield*Gk(e,t,o,r,n),n)}),Jk=qe.fnUntraced(function*(e,t,o,n){return o?yield*mm(e,t,o,n):yield*fm(e,t,o,yield*e.status(t),new Map,$k(),n)}),Xk=tt.Literals(["git","branch"]),hm=qs,Qk=tt.Struct({branch:tt.optional(tt.String),default_branch:tt.optional(tt.String)}).annotate({identifier:"VcsInfo"}),Zk=tt.Struct({file:tt.String,patch:tt.optional(tt.String),additions:tt.Finite,deletions:tt.Finite,status:tt.optional(tt.Literals(["added","deleted","modified"]))}).annotate({identifier:"VcsFileDiff"}),eD=tt.Struct({file:tt.String,additions:tt.Finite,deletions:tt.Finite,status:tt.Literals(["added","deleted","modified"])}).annotate({identifier:"VcsFileStatus"}),tD=tt.Struct({patch:tt.String}),oD=tt.Struct({applied:tt.Boolean}),zs=class extends tt.TaggedErrorClass()("VcsPatchApplyError",{message:tt.String,reason:tt.Literals(["non-git","not-clean"])}){static{s(this,"PatchApplyError")}},gn=class extends Uk.Service()("@opencode/Vcs"){static{s(this,"Service")}},nD=_k.effect(gn,qe.gen(function*(){let e=yield*Oa.Service,t=yield*we.Service,o=yield*jk.Scope,n=yield*B.make(qe.fn("Vcs.state")(function*(r){if(r.project.vcs!=="git")return{current:void 0,root:void 0};let i=qe.fnUntraced(function*(){return yield*e.branch(r.directory)}),[a,c]=yield*qe.all([e.branch(r.directory),e.defaultBranch(r.directory)],{concurrency:2}),d={current:a,root:c},u=yield*t.listen(l=>l.type!==$o.Event.Updated.type||l.location?.directory!==r.directory?qe.void:l.data.file.endsWith("HEAD")?qe.gen(function*(){let h=yield*i();h!==d.current&&(d.current=h,yield*t.publish(hm.BranchUpdated,{branch:h}))}):qe.void);return yield*qe.addFinalizer(()=>u),d}));return gn.of({init:qe.fn("Vcs.init")(function*(){yield*B.get(n).pipe(qe.forkIn(o))}),branch:qe.fn("Vcs.branch")(function*(){return yield*B.use(n,r=>r.current)}),defaultBranch:qe.fn("Vcs.defaultBranch")(function*(){return yield*B.use(n,r=>r.root?.name)}),status:qe.fn("Vcs.status")(function*(){let r=yield*B.context;if(r.project.vcs!=="git")return[];let i=(yield*e.hasHead(r.directory))?"HEAD":void 0,[a,c]=yield*qe.all([e.status(r.directory),i?e.stats(r.directory,i):qe.succeed([])],{concurrency:2}),d=pm(c);return yield*qe.forEach(a.toSorted((u,l)=>u.file.localeCompare(l.file)),u=>qe.gen(function*(){let l=d.get(u.file)??(u.status==="added"?yield*e.statUntracked(r.worktree,u.file):void 0);return{file:u.file,additions:l?.additions??0,deletions:l?.deletions??0,status:u.status}}))}),diff:qe.fn("Vcs.diff")(function*(r,i){let a=yield*B.get(n),c=yield*B.context;if(c.project.vcs!=="git")return[];if(r==="git")return yield*Jk(e,c.directory,(yield*e.hasHead(c.directory))?"HEAD":void 0,i);if(!a.root)return[];if(a.current&&a.current===a.root.name)return[];let d=yield*e.mergeBase(c.directory,a.root.ref);return d?yield*mm(e,c.directory,d,i):[]}),diffRaw:qe.fn("Vcs.diffRaw")(function*(){let r=yield*B.context;if(r.project.vcs!=="git")return"";let[i,a]=yield*qe.all([e.hasHead(r.directory),e.status(r.directory)],{concurrency:2}),c=i?(yield*e.patchAll(r.directory,"HEAD")).text:"",d=yield*qe.forEach(a.filter(u=>u.code==="??"),u=>e.patchUntracked(r.directory,u.file).pipe(qe.map(l=>l.text)));return[c,...d].filter(Boolean).join(`
1453
- `)}),apply:qe.fn("Vcs.apply")(function*(r){let i=yield*B.context;return i.project.vcs!=="git"?yield*new zs({message:"Patch can't be applied because the project is not git-based",reason:"non-git"}):(yield*e.applyPatch(i.directory,r.patch)).exitCode!==0?yield*new zs({message:"Patch can't be applied",reason:"not-clean"}):{applied:!0}})})})),tl=ge.make({service:gn,layer:nD,deps:[Oa.node,we.node]});var Qo={};ae(Qo,{Service:()=>Qn,ShareNext:()=>Qo,node:()=>mD,use:()=>dD});import{Effect as Ee,Exit as sD,Layer as iD,Option as gm,Schema as da,Scope as ym,Context as aD}from"effect";import{HttpClient as wm,HttpClientRequest as Xo,HttpClientResponse as cD}from"effect/unstable/http";import{eq as bm}from"drizzle-orm";import{sqliteTable as rD,text as la}from"drizzle-orm/sqlite-core";var Xn=rD("session_share",{session_id:la().primaryKey().references(()=>Dt.id,{onDelete:"cascade"}),id:la().notNull(),secret:la().notNull(),url:la().notNull(),...El});var Kr=process.env.OPENCODE_DISABLE_SHARE==="true"||process.env.OPENCODE_DISABLE_SHARE==="1",lD=da.Struct({id:da.String,url:da.String,secret:da.String}),Qn=class extends aD.Service()("@opencode/ShareNext"){static{s(this,"Service")}},dD=Gt(Qn);function vm(e){return{create:`/api/${e}`,sync:s(t=>`/api/${e}/${t}/sync`,"sync"),remove:s(t=>`/api/${e}/${t}`,"remove"),data:s(t=>`/api/${e}/${t}/data`,"data")}}s(vm,"api");var uD=vm("share"),pD=vm("shares");function xm(e){switch(e.type){case"session":return"session";case"message":return`message/${e.data.id}`;case"part":return`part/${e.data.messageID}/${e.data.id}`;case"session_diff":return"session_diff";case"model":return"model"}}s(xm,"key");var fD=iD.effect(Qn,Ee.gen(function*(){let e=yield*Pa.Service,t=yield*we.Service,o=yield*De.Service,{db:n}=yield*Xe.Service,r=yield*wm.HttpClient,i=wm.filterStatusOk(r),a=yield*yt.Service,c=yield*ce.Service;function d(y,v){return Ee.gen(function*(){if(Kr||!(yield*h(y)))return;let b=yield*B.get(u),T=b.queue.get(y);if(T){for(let j of v)T.set(xm(j),j);return}let E=new Map(v.map(j=>[xm(j),j]));b.queue.set(y,E),yield*g(y).pipe(Ee.delay(1e3),Ee.catchCause(j=>Ee.logError("share flush failed",{sessionID:y,cause:j})),Ee.forkIn(b.scope))})}s(d,"sync");let u=yield*B.make(Ee.fn("ShareNext.state")(function*(y){let v={queue:new Map,scope:yield*ym.make(),shared:new Map};if(yield*Ee.addFinalizer(()=>ym.close(v.scope,sD.void).pipe(Ee.andThen(Ee.sync(()=>{v.queue.clear(),v.shared.clear()})))),Kr)return v;let P=s((b,T)=>t.listen(E=>E.type!==b.type||E.location?.directory!==y.directory?Ee.void:T(E.data).pipe(Ee.catchCause(j=>Ee.logError("share subscriber failed",{type:b.type,cause:j})))),"watch");return yield*P(ce.Event.Updated,b=>Ee.gen(function*(){let T=b.info;yield*d(T.id,[{type:"session",data:structuredClone(T)}])})),yield*P(Qe.Event.Updated,b=>Ee.gen(function*(){let T=b.info;if(yield*d(T.sessionID,[{type:"message",data:structuredClone(T)}]),T.role!=="user")return;let E=yield*a.getModel(T.model.providerID,T.model.modelID);yield*d(T.sessionID,[{type:"model",data:[E]}])})),yield*P(Qe.Event.PartUpdated,b=>d(b.part.sessionID,[{type:"part",data:structuredClone(b.part)}])),yield*P(ce.Event.Diff,b=>d(b.sessionID,[{type:"session_diff",data:structuredClone(b.diff)}])),yield*P(ce.Event.Deleted,b=>S(b.sessionID)),v})),l=Ee.fn("ShareNext.request")(function*(){let y={},v=yield*e.active();if(gm.isNone(v)||!v.value.active_org_id){let b=(yield*o.get()).enterprise?.url??"https://opncd.ai";return{headers:y,api:uD,baseUrl:b}}let P=yield*e.token(v.value.id);if(gm.isNone(P))throw new Error("No active account token available for sharing");return y.authorization=`Bearer ${P.value}`,y["x-org-id"]=v.value.active_org_id,{headers:y,api:pD,baseUrl:v.value.url}}),m=Ee.fnUntraced(function*(y){let v=yield*n.select().from(Xn).where(bm(Xn.session_id,y)).get().pipe(Ee.orDie);if(v)return{id:v.id,secret:v.secret,url:v.url}}),h=Ee.fnUntraced(function*(y){let v=yield*B.get(u);if(v.shared.has(y)){let b=v.shared.get(y);return b===null?void 0:b}let P=yield*m(y);return v.shared.set(y,P??null),P}),g=Ee.fn("ShareNext.flush")(function*(y){if(Kr)return;let v=yield*B.get(u),P=v.queue.get(y);if(!P)return;v.queue.delete(y);let b=yield*h(y);if(!b)return;let T=yield*l(),E=yield*Xo.post(`${T.baseUrl}${T.api.sync(b.id)}`).pipe(Xo.setHeaders(T.headers),Xo.bodyJson({secret:b.secret,data:Array.from(P.values())}),Ee.flatMap(j=>r.execute(j)));E.status>=400&&(yield*Ee.logWarning("failed to sync share",{sessionID:y,shareID:b.id,status:E.status}))}),w=Ee.fn("ShareNext.full")(function*(y){yield*Ee.logInfo("full sync",{sessionID:y});let v=yield*c.get(y),P=yield*c.diff(y),b=yield*c.messages({sessionID:y}),T=yield*Ee.forEach(Array.from(new Map(b.filter(E=>E.info.role==="user").map(E=>E.info.model).map(E=>[`${E.providerID}/${E.modelID}`,E])).values()),E=>a.getModel(co.ID.make(E.providerID),xn.ID.make(E.modelID)),{concurrency:8});yield*d(y,[{type:"session",data:v},...b.map(E=>({type:"message",data:E.info})),...b.flatMap(E=>E.parts.map(j=>({type:"part",data:j}))),{type:"session_diff",data:P},{type:"model",data:T}])}),k=Ee.fn("ShareNext.init")(function*(){Kr||(yield*B.get(u))}),p=Ee.fn("ShareNext.url")(function*(){return(yield*l()).baseUrl}),f=Ee.fn("ShareNext.create")(function*(y){if(Kr)return{id:"",url:"",secret:""};yield*Ee.logInfo("creating share",{sessionID:y});let v=yield*l(),P=yield*Xo.post(`${v.baseUrl}${v.api.create}`).pipe(Xo.setHeaders(v.headers),Xo.bodyJson({sessionID:y}),Ee.flatMap(T=>i.execute(T)),Ee.flatMap(cD.schemaBodyJson(lD)));yield*n.insert(Xn).values({session_id:y,id:P.id,secret:P.secret,url:P.url}).onConflictDoUpdate({target:Xn.session_id,set:{id:P.id,secret:P.secret,url:P.url}}).run().pipe(Ee.orDie);let b=yield*B.get(u);return b.shared.set(y,P),yield*w(y).pipe(Ee.catchCause(T=>Ee.logError("share full sync failed",{sessionID:y,cause:T})),Ee.forkIn(b.scope)),P}),S=Ee.fn("ShareNext.remove")(function*(y){if(Kr)return;yield*Ee.logInfo("removing share",{sessionID:y});let v=yield*B.get(u),P=yield*h(y);if(!P){v.shared.delete(y),v.queue.delete(y);return}let b=yield*l();yield*Xo.delete(`${b.baseUrl}${b.api.remove(P.id)}`).pipe(Xo.setHeaders(b.headers),Xo.bodyJson({secret:P.secret}),Ee.flatMap(T=>i.execute(T))),yield*n.delete(Xn).where(bm(Xn.session_id,y)).run().pipe(Ee.orDie),v.shared.delete(y),v.queue.delete(y)});return Qn.of({init:k,url:p,request:l,create:f,remove:S})})),mD=ge.make({service:Qn,layer:fD,deps:[Pa.node,we.node,De.node,Xe.node,Co,yt.node,ce.node]});var Jr={};ae(Jr,{AppNodeBuilderV1:()=>Jr,build:()=>bD});var Gs={};ae(Gs,{InstanceBootstrap:()=>Gs,Service:()=>ir,node:()=>yD});import{Effect as yn,Layer as hD}from"effect";var gD=hD.effect(ir,yn.gen(function*(){let e=yield*De.Service,t=yield*Xt.Service,o=yield*ut.Service,n=yield*dt.Service,r=yield*od,i=yield*Qo.Service,a=yield*lo.Service,c=yield*gn,d=yn.gen(function*(){let u=yield*B.context;yield*yn.logInfo("bootstrapping",{directory:u.directory}),yield*e.get(),yield*n.init(),yield*yn.forEach([o,i,t,c,a,r],l=>l.init().pipe(yn.catchCause(m=>yn.logWarning("init failed",{cause:m}))),{concurrency:"unbounded",discard:!0}).pipe(yn.withSpan("InstanceBootstrap.init"))}).pipe(yn.withSpan("InstanceBootstrap"));return ir.of({run:d})})),yD=ti({service:ir,layer:gD,deps:[De.node,Xt.node,ut.node,dt.node,nd,Qo.node,lo.node,tl]});var wD=[ar.bootstrapNode,Gs.node];function bD(e,t=[]){return Rn.build(e,t.concat([wD]))}s(bD,"build");var rl={};ae(rl,{ConnectionStatus:()=>RD,CreateInput:()=>AD,Event:()=>nl,Info:()=>fa,Service:()=>er,SessionEventsNotFoundError:()=>ha,SessionWarpHttpError:()=>Xs,SessionWarpInput:()=>CD,SyncAbortedError:()=>ya,SyncHttpError:()=>Js,SyncTimeoutError:()=>ga,Workspace:()=>rl,WorkspaceNotFoundError:()=>ma,node:()=>LD,use:()=>MD});import{Context as DD,Effect as V,FiberMap as Ys,Iterable as Im,Layer as ED,Schema as Be,Stream as Ks}from"effect";import{HttpBody as ua,HttpClient as TD,HttpClientRequest as Qr}from"effect/unstable/http";import{asc as PD}from"drizzle-orm";import{eq as Zo}from"drizzle-orm";import{inArray as km}from"drizzle-orm";import{Effect as Zn}from"effect";function ol(e){return e.signal?.aborted?Zn.fail(e.signal.reason??new Error("Request aborted")):Zn.callback(t=>{let o=s(()=>{r(),t(Zn.fail(e.signal?.reason??new Error("Request aborted")))},"abort"),n=s(a=>{try{if(!e.fn(a))return;r(),t(Zn.void)}catch(c){r(),t(Zn.fail(c))}},"handler"),r=s(()=>{clearTimeout(i),sr.off("event",n),e.signal?.removeEventListener("abort",o)},"cleanup"),i=setTimeout(()=>{r(),t(Zn.fail(new Error("Timed out waiting for global event")))},e.timeout);return sr.on("event",n),e.signal?.addEventListener("abort",o,{once:!0}),Zn.sync(r)})}s(ol,"waitEvent");var ao={};ae(ao,{WorkspaceAdapterRuntime:()=>ao,configure:()=>vD,create:()=>ID,list:()=>SD,remove:()=>kD,target:()=>xD});import{Effect as Xr}from"effect";var Hs=Xr.gen(function*(){return{instance:yield*Yl,workspaceID:yield*pi}}),xD=s(e=>Xr.gen(function*(){let t=cs(e.projectID,e.type),o=yield*Hs;return yield*Yt.fromPromise(()=>t.target(e,o))}),"target"),vD=s((e,t)=>Xr.gen(function*(){let o=yield*Hs;return yield*Yt.fromPromise(()=>e.configure(t,o))}),"configure"),ID=s((e,t,o,n)=>Xr.gen(function*(){let r=yield*Hs;return yield*Yt.fromPromise(()=>e.create(t,o,n,r))}),"create"),SD=s(e=>Xr.gen(function*(){let t=yield*Hs;return yield*Yt.fromPromise(()=>Promise.resolve(e.list?.(t)??[]))}),"list"),kD=s(e=>Xr.gen(function*(){let t=cs(e.projectID,e.type),o=yield*Hs;return yield*Yt.fromPromise(()=>t.remove(e,o))}),"remove");var fa=Be.Struct({...Ql.fields,timeUsed:Be.Number}).annotate({identifier:"Workspace"}),RD=Sa.ConnectionStatus,nl=Sa;function pa(e){return{id:e.id,type:e.type,branch:e.branch,name:e.name,directory:e.directory,extra:e.extra,projectID:e.project_id,timeUsed:e.time_used}}s(pa,"fromRow");var AD=Be.Struct({id:Be.optional(kn.ID),type:fa.fields.type,branch:fa.fields.branch,projectID:Tl.ID,extra:Be.optional(fa.fields.extra)}),CD=Be.Struct({workspaceID:Be.NullOr(kn.ID),sessionID:Et,copyChanges:Be.optional(Be.Boolean)}),Js=class extends Be.TaggedErrorClass()("WorkspaceSyncHttpError",{message:Be.String,status:Be.Number,body:Be.optional(Be.String)}){static{s(this,"SyncHttpError")}},ma=class extends Be.TaggedErrorClass()("WorkspaceNotFoundError",{message:Be.String,workspaceID:kn.ID}){static{s(this,"WorkspaceNotFoundError")}},ha=class extends Be.TaggedErrorClass()("WorkspaceSessionEventsNotFoundError",{message:Be.String,sessionID:Et}){static{s(this,"SessionEventsNotFoundError")}},Xs=class extends Be.TaggedErrorClass()("WorkspaceSessionWarpHttpError",{message:Be.String,workspaceID:kn.ID,sessionID:Et,status:Be.Number,body:Be.String}){static{s(this,"SessionWarpHttpError")}},ga=class extends Be.TaggedErrorClass()("WorkspaceSyncTimeoutError",{message:Be.String,state:Be.Record(Be.String,Be.Number)}){static{s(this,"SyncTimeoutError")}},ya=class extends Be.TaggedErrorClass()("WorkspaceSyncAbortedError",{message:Be.String,cause:Be.optional(Be.Defect())}){static{s(this,"SyncAbortedError")}},er=class extends DD.Service()("@opencode/Workspace"){static{s(this,"Service")}},MD=Gt(er),OD=ED.effect(er,V.gen(function*(){let e=yield*eo.Service,t=yield*ce.Service,o=yield*Yr.Service,n=yield*TD.HttpClient,r=yield*we.Service,i=yield*Jn.Service,a=yield*Me.Service,c=yield*Se.Service,{db:d}=yield*Xe.Service,u=new Map,l=yield*Ys.make(),m=s((M,$)=>{if(u.get(M)?.status===$)return;let R={workspaceID:M,status:$};u.set(M,R),sr.emit("event",{directory:"global",workspace:M,payload:{type:nl.Status.type,properties:R}})},"setStatus"),h=V.fn("Workspace.connectSSE")(function*(M,$){let x=yield*n.execute(Qr.get(Zr(M,"/global/event"),{headers:new Headers($),accept:"text/event-stream"}));return x.status<200||x.status>=300?yield*new Js({message:`Workspace sync HTTP failure: ${x.status}`,status:x.status}):x.stream}),g=V.fn("Workspace.parseSSE")(function*(M,$){yield*M.pipe(Ks.decodeText(),Ks.splitLines,Ks.mapAccum(()=>({data:[],id:void 0,retry:1e3}),(x,R)=>{if(R==="")return x.data.length?[{...x,data:[]},[{data:x.data.join(`
1454
- `),id:x.id,retry:x.retry}]]:[x,[]];let A=R.indexOf(":"),O=A===-1?R:R.slice(0,A),F=A===-1?"":R.slice(A+(R[A+1]===" "?2:1));if(O==="data")return[{...x,data:[...x.data,F]},[]];if(O==="id")return[{...x,id:F},[]];if(O==="retry"){let U=Number.parseInt(F,10);return[Number.isNaN(U)?x:{...x,retry:U},[]]}return[x,[]]},{onHalt:s(x=>x.data.length?[{data:x.data.join(`
1455
- `),id:x.id,retry:x.retry}]:[],"onHalt")}),Ks.map(x=>{try{return JSON.parse(x.data)}catch{return{type:"sse.message",properties:{data:x.data,id:x.id||void 0,retry:x.retry}}}}),Ks.runForEach($))}),w=s(M=>V.gen(function*(){if(!M.workspaceID)return yield*M.local();let $=yield*T(M.workspaceID);if(!$)return M.fallback;let x=yield*ao.target($);if(x.type==="local")return yield*(yield*ar.Service).provide({directory:x.directory},M.local());let R=yield*n.execute(M.remote({workspace:$,target:x})).pipe(V.catch(O=>V.logWarning("workspace target request failed",{workspaceID:$.id,error:sn(O)}).pipe(V.as(void 0))));if(!R)return M.fallback;if(R.status<200||R.status>=300){let O=yield*R.text.pipe(V.catch(()=>V.succeed("")));return yield*V.logWarning("workspace target request failed",{workspaceID:$.id,status:R.status,body:O}),M.fallback}return yield*(M.response==="text"?R.text:R.json).pipe(V.map(O=>O),V.catch(O=>V.logWarning("workspace target response decode failed",{workspaceID:$.id,error:sn(O)}).pipe(V.as(M.fallback))))}),"runInWorkspace"),k=V.fn("Workspace.syncHistory")(function*(M,$,x){let R=(yield*d.select({id:Dt.id}).from(Dt).where(Zo(Dt.workspace_id,M.id)).all().pipe(V.orDie)).map(U=>U.id),A=R.length?Object.fromEntries((yield*d.select().from(vn).where(km(vn.aggregate_id,R)).all().pipe(V.orDie)).map(U=>[U.aggregate_id,U.seq])):{},O=yield*n.execute(Qr.post(Zr($,"/sync/history"),{headers:new Headers(x),body:ua.jsonUnsafe(A)}));if(O.status<200||O.status>=300){let U=yield*O.text;return yield*new Js({message:`Workspace history HTTP failure: ${O.status} ${U}`,status:O.status,body:U})}let F=yield*O.json;yield*V.forEach(F,U=>r.replay({id:Al.ID.make(U.id),aggregateID:U.aggregate_id,seq:U.seq,type:U.type,data:U.data},{publish:!0,ownerID:M.id}).pipe(V.provideService(pi,M.id)),{discard:!0})}),p=V.fn("Workspace.syncWorkspaceLoop")(function*(M){let $=yield*ao.target(M);if($.type==="local")return;let x=0;for(;;){m(M.id,"connecting");let R=yield*h($.url,$.headers).pipe(V.tap(()=>k(M,$.url,$.headers)),V.catch(A=>V.gen(function*(){return m(M.id,"error"),yield*V.logWarning("failed to connect to global sync",{workspace:M.name,error:sn(A)}),null})));R&&(x=0,m(M.id,"connected"),yield*g(R,A=>V.gen(function*(){if(!A||typeof A!="object"||!("payload"in A))return;let O=A.payload;if(O.type!=="server.heartbeat"&&!(O.type==="sync"&&O.syncEvent&&(yield*r.replay(O.syncEvent,{publish:!0,ownerID:M.id}).pipe(V.as(!1),V.catchCause(U=>V.logWarning("failed to replay global event",U).pipe(V.annotateLogs({workspaceID:M.id}),V.as(!0)))))))try{let F=A;sr.emit("event",{directory:F.directory,project:F.project,workspace:M.id,payload:F.payload})}catch(F){yield*V.logWarning("failed to emit global event",{workspaceID:M.id,error:sn(F)})}})),m(M.id,"disconnected")),yield*V.sleep(`${Math.min(12e4,1e3*2**x)} millis`),x+=1}}),f=V.fn("Workspace.startSync")(function*(M){if(!a.experimentalWorkspaces)return;let $=yield*ao.target(M).pipe(V.catch(R=>V.gen(function*(){return m(M.id,"error"),yield*V.logWarning("workspace target failed",{workspaceID:M.id,error:sn(R)}),null})));if(!$)return;if($.type==="local"){m(M.id,(yield*c.existsSafe($.directory))?"connected":"error");return}(yield*Ys.has(l,M.id))&&u.get(M.id)?.status!=="error"||(m(M.id,"disconnected"),yield*Ys.run(l,M.id,p(M).pipe(V.catch(R=>V.gen(function*(){m(M.id,"error"),yield*V.logWarning("workspace listener failed",{workspaceID:M.id,error:sn(R)})})))))}),S=V.fn("Workspace.stopSync")(function*(M){yield*Ys.remove(l,M),u.delete(M)}),y=V.fn("Workspace.create")(function*(M){let $=kn.ID.ascending(M.id),x=cs(M.projectID,M.type),R=yield*ao.configure(x,{...M,id:$,name:Cl.create(),directory:null,extra:M.extra??null}),A={id:$,type:R.type,branch:R.branch??null,name:R.name??null,directory:R.directory??null,extra:R.extra??null,projectID:M.projectID,timeUsed:Date.now()};yield*d.insert(Ht).values({id:A.id,type:A.type,branch:A.branch,name:A.name,directory:A.directory,extra:A.extra,project_id:A.projectID,time_used:A.timeUsed}).run().pipe(V.orDie);let O={OPENCODE_AUTH_CONTENT:JSON.stringify(yield*e.all()),OPENCODE_WORKSPACE_ID:R.id,OPENCODE_EXPERIMENTAL_WORKSPACES:"true",OTEL_EXPORTER_OTLP_HEADERS:process.env.OTEL_EXPORTER_OTLP_HEADERS,OTEL_EXPORTER_OTLP_ENDPOINT:process.env.OTEL_EXPORTER_OTLP_ENDPOINT,OTEL_RESOURCE_ATTRIBUTES:process.env.OTEL_RESOURCE_ATTRIBUTES};return yield*ao.create(x,R,O),yield*V.all([ol({timeout:Sm,fn(F){if(F.workspace===A.id&&F.payload.type===nl.Status.type){let{status:U}=F.payload.properties;return U==="error"||U==="connected"}return!1}}),f(A)],{concurrency:2,discard:!0}),A}),v=V.fn("Workspace.sessionWarp")(function*(M){return yield*V.gen(function*(){let $=yield*d.select({workspaceID:Dt.workspace_id}).from(Dt).where(Zo(Dt.id,M.sessionID)).get().pipe(V.orDie);if($?.workspaceID){let Z=yield*T($.workspaceID);if(Z){let Q=yield*ao.target(Z);Q.type==="remote"?yield*k(Z,Q.url,Q.headers).pipe(V.catch(D=>V.logWarning("session warp final source sync failed",{workspaceID:Z.id,sessionID:M.sessionID,error:sn(D)}))):yield*o.cancel(M.sessionID),yield*r.claim(M.sessionID,M.workspaceID??Z.projectID)}}let x=M.copyChanges&&$?.workspaceID?yield*w({workspaceID:$?.workspaceID??void 0,local:s(()=>i.diffRaw(),"local"),remote:s(({target:Z})=>Qr.get(Zr(Z.url,"/vcs/diff/raw"),{headers:new Headers(Z.headers)}),"remote"),fallback:"",response:"text"}).pipe(V.provide(Jr.build(ar.node))):"";if(x&&(yield*w({workspaceID:M.workspaceID??void 0,local:s(()=>i.apply({patch:x}),"local"),remote:s(({target:Z})=>Qr.post(Zr(Z.url,"/vcs/apply"),{headers:new Headers(Z.headers),body:ua.jsonUnsafe({patch:x})}),"remote"),fallback:{applied:!1}}).pipe(V.provide(Jr.build(ar.node)))),M.workspaceID===null){yield*t.setWorkspace({sessionID:M.sessionID,workspaceID:void 0});return}let R=M.workspaceID,A=yield*T(R);if(!A)return yield*new ma({message:`Workspace not found: ${R}`,workspaceID:R});let O=yield*ao.target(A);if(O.type==="local"){yield*t.setWorkspace({sessionID:M.sessionID,workspaceID:M.workspaceID});return}let F=yield*d.select({id:Fo.id,aggregateID:Fo.aggregate_id,seq:Fo.seq,type:Fo.type,data:Fo.data}).from(Fo).where(Zo(Fo.aggregate_id,M.sessionID)).orderBy(PD(Fo.seq)).all().pipe(V.orDie);if(F.length===0)return yield*new ha({message:`No events found for session: ${M.sessionID}`,sessionID:M.sessionID});let U=Im.chunksOf(F,10),pe=Im.size(U);yield*V.forEach(U,(Z,Q)=>V.gen(function*(){let D=yield*n.execute(Qr.post(Zr(O.url,"/sync/replay"),{headers:new Headers(O.headers),body:ua.jsonUnsafe({directory:A.directory??"",events:Z})}));if(D.status<200||D.status>=300){let N=yield*D.text;return yield*new Xs({message:`Failed to warp session ${M.sessionID} into workspace ${R}: HTTP ${D.status} ${N}`,workspaceID:R,sessionID:M.sessionID,status:D.status,body:N})}}),{discard:!0});let re=yield*n.execute(Qr.post(Zr(O.url,"/sync/steal"),{headers:new Headers(O.headers),body:ua.jsonUnsafe({sessionID:M.sessionID})}));if(re.status<200||re.status>=300){let Z=yield*re.text;return yield*new Xs({message:`Failed to steal session ${M.sessionID} into workspace ${R}: HTTP ${re.status} ${Z}`,workspaceID:R,sessionID:M.sessionID,status:re.status,body:Z})}yield*t.setWorkspace({sessionID:M.sessionID,workspaceID:M.workspaceID})})}),P=V.fn("Workspace.list")(function*(M){return a.experimentalWorkspaces?(yield*d.select().from(Ht).where(Zo(Ht.project_id,M.id)).all().pipe(V.orDie)).map(pa).sort(($,x)=>$.id.localeCompare(x.id)):[]}),b=V.fn("Workspace.syncList")(function*(M){let $=new Set((yield*P(M)).map(R=>R.name)),x=yield*V.forEach(rd(M.id),([R,A])=>ao.list(A).pipe(V.catchCause(O=>V.logWarning("workspace adapter list failed",{type:R,error:O}).pipe(V.as([])))),{concurrency:"unbounded"}).pipe(V.map(R=>R.flat()));yield*V.forEach(x,R=>V.gen(function*(){if($.has(R.name))return;$.add(R.name);let A={id:kn.ID.ascending(),type:R.type,branch:R.branch,name:R.name,directory:R.directory,extra:R.extra,projectID:R.projectID,timeUsed:Date.now()};yield*d.insert(Ht).values({id:A.id,type:A.type,branch:A.branch,name:A.name,directory:A.directory,extra:A.extra,project_id:A.projectID,time_used:A.timeUsed}).run().pipe(V.orDie),yield*f(A)}),{concurrency:1})}),T=V.fn("Workspace.get")(function*(M){let $=yield*d.select().from(Ht).where(Zo(Ht.id,M)).get().pipe(V.orDie);if($)return pa($)}),E=V.fn("Workspace.remove")(function*(M){let $=yield*d.select({id:Dt.id,parentID:Dt.parent_id}).from(Dt).where(Zo(Dt.workspace_id,M)).all().pipe(V.orDie),x=new Set($.map(O=>O.id));yield*V.forEach($.filter(O=>!O.parentID||!x.has(O.parentID)),O=>t.remove(O.id).pipe(V.catchIf(mi.isInstance,()=>V.void)),{discard:!0});let R=yield*d.select().from(Ht).where(Zo(Ht.id,M)).get().pipe(V.orDie);if(!R)return;yield*S(M);let A=pa(R);return yield*V.catchCause(V.gen(function*(){yield*ao.remove(A)}),()=>V.logError("adapter not available when removing workspace",{type:R.type})),yield*d.delete(Ht).where(Zo(Ht.id,M)).run().pipe(V.orDie),A}),j=V.fn("Workspace.status")(function*(){return[...u.values()]}),_=V.fn("Workspace.isSyncing")(function*(M){return(yield*Ys.has(l,M))&&u.get(M)?.status!=="error"}),W=V.fn("Workspace.waitForSync")(function*(M,$,x,R=Sm){(yield*Em(d,$))||(yield*V.catch(Dm({db:d,workspaceID:M,state:$,signal:x,timeout:R}),()=>x?.aborted?V.fail(new ya({message:x.reason instanceof Error?x.reason.message:"Request aborted",cause:x.reason})):V.fail(new ga({message:`Timed out waiting for sync fence: ${JSON.stringify($)}`,state:$}))))}),ie=V.fn("Workspace.startWorkspaceSyncing")(function*(M){if(!a.experimentalWorkspaces)return;let $=yield*d.selectDistinct({workspace:Ht}).from(Ht).where(Zo(Ht.project_id,M)).all().pipe(V.orDie);for(let{workspace:x}of $)yield*f(pa(x)).pipe(V.catch(R=>V.sync(()=>{m(x.id,"error")})),V.forkDetach)});return er.of({create:y,sessionWarp:v,list:P,syncList:b,get:T,remove:E,status:j,isSyncing:_,waitForSync:W,startWorkspaceSyncing:ie})})),Sm=5e3;function Dm(e){return V.suspend(()=>ol({timeout:e.timeout,signal:e.signal,fn(t){return t.workspace===e.workspaceID||t.payload.type==="sync"}}).pipe(V.andThen(Em(e.db,e.state)),V.flatMap(t=>t?V.void:Dm(e))))}s(Dm,"waitUntilSynced");function Em(e,t){let o=Object.keys(t);return o.length===0?V.succeed(!0):e.select({id:vn.aggregate_id,seq:vn.seq}).from(vn).where(km(vn.aggregate_id,o)).all().pipe(V.orDie,V.map(n=>{let r=Object.fromEntries(n.map(i=>[i.id,i.seq]));return o.every(i=>(r[i]??-1)>=t[i])}))}s(Em,"synced");function Zr(e,t){let o=new URL(e);return o.pathname=`${o.pathname.replace(/\/$/,"")}${t}`,o.search="",o.hash="",o}s(Zr,"route");var LD=ge.make({service:er,layer:OD,deps:[eo.node,ce.node,Yr.node,Co,we.node,Jn.node,Me.node,Se.node,Xe.node]});var al={};ae(al,{Event:()=>FD,Info:()=>$D,Installation:()=>al,Service:()=>wn,USER_AGENT:()=>WD,UpgradeFailedError:()=>es,getReleaseType:()=>BD,isLocal:()=>VD,isPreview:()=>qD,latest:()=>QD,method:()=>ZD,node:()=>Lm,upgrade:()=>eE,use:()=>JD,userAgent:()=>Mm});import{Effect as Ct,Layer as UD,Schema as pt,Context as jD,Stream as ND}from"effect";import{HttpClient as Am,HttpClientRequest as Po,HttpClientResponse as Zs}from"effect/unstable/http";import{ChildProcess as sl}from"effect/unstable/process";import Cm from"path";import wa from"semver";var Qs={};ae(Qs,{Definitions:()=>_D,InstallationEvent:()=>Qs,UpdateAvailable:()=>Rm,Updated:()=>Pm});import{Schema as Tm}from"effect";var Pm=kt.define({type:"installation.updated",schema:{version:Tm.String}}),Rm=kt.define({type:"installation.update-available",schema:{version:Tm.String}}),_D=kt.inventory(Pm,Rm);var FD=Qs;function BD(e,t){let o=wa.major(e),n=wa.minor(e),r=wa.major(t),i=wa.minor(t);return r>o?"major":i>n?"minor":"patch"}s(BD,"getReleaseType");var $D=pt.Struct({version:pt.String,latest:pt.String}).annotate({identifier:"InstallationInfo"});function Mm(e="cli"){return`opencode/${is}/${ss}/${e}`}s(Mm,"userAgent");var WD=Mm();function qD(){return is!=="latest"}s(qD,"isPreview");function VD(){return is==="local"}s(VD,"isLocal");var es=class extends pt.TaggedErrorClass()("UpgradeFailedError",{stderr:pt.String}){static{s(this,"UpgradeFailedError")}get message(){return this.stderr}},zD=pt.Struct({tag_name:pt.String}),Om=pt.Struct({version:pt.String}),GD=pt.Struct({versions:pt.Struct({stable:pt.String})}),HD=pt.Struct({formulae:pt.Array(pt.Struct({versions:pt.Struct({stable:pt.String})}))}),YD=pt.Struct({d:pt.Struct({results:pt.Array(pt.Struct({Version:pt.String}))})}),KD=Om,wn=class extends jD.Service()("@opencode/Installation"){static{s(this,"Service")}},JD=Gt(wn),XD=UD.effect(wn,Ct.gen(function*(){let e=yield*Am.HttpClient,t=Am.filterStatusOk(ui(e)),o=yield*nr.Service,n=Ct.fnUntraced(function*(l,m){return(yield*o.run(sl.make(l[0],l.slice(1),{cwd:m?.cwd,env:m?.env,extendEnv:!0}))).stdout.toString("utf8")},Ct.catch(()=>Ct.succeed(""))),r=Ct.fnUntraced(function*(l,m){let h=yield*o.run(sl.make(l[0],l.slice(1),{cwd:m?.cwd,env:m?.env,extendEnv:!0}));return{code:h.exitCode,stdout:h.stdout.toString("utf8"),stderr:h.stderr.toString("utf8")}},Ct.catch(l=>Ct.succeed({code:1,stdout:"",stderr:vo(l)}))),i=Ct.fnUntraced(function*(){return(yield*n(["brew","list","--formula","anomalyco/tap/opencode"])).includes("opencode")?"anomalyco/tap/opencode":((yield*n(["brew","list","--formula","opencode"])).includes("opencode"),"opencode")}),a=s((l,m)=>l==="choco"?"not running from an elevated command shell":m?`Upgrade failed for ${l} (exit code ${m.code}).`:`Upgrade failed for ${l}.`,"upgradeFailure"),c=Ct.fnUntraced(function*(){return(yield*n(["bash","--version"]))?"bash":"sh"}),d=Ct.fnUntraced(function*(l){let h=yield*(yield*t.execute(Po.get("https://opencode.ai/install"))).text,g=new TextEncoder().encode(h),w=yield*c(),k=yield*o.run(sl.make(w,[],{stdin:ND.make(g),env:{VERSION:l},extendEnv:!0}));return{code:k.exitCode,stdout:k.stdout.toString("utf8"),stderr:k.stderr.toString("utf8")}},Ct.mapError(()=>new es({stderr:a("curl")}))),u={info:Ct.fn("Installation.info")(function*(){return{version:ss,latest:yield*u.latest()}}),method:Ct.fn("Installation.method")(function*(){if(process.execPath.includes(Cm.join(".opencode","bin"))||process.execPath.includes(Cm.join(".local","bin")))return"curl";let l=process.execPath.toLowerCase(),m=[{name:"npm",command:s(()=>n(["npm","list","-g","--depth=0"]),"command")},{name:"yarn",command:s(()=>n(["yarn","global","list"]),"command")},{name:"pnpm",command:s(()=>n(["pnpm","list","-g","--depth=0"]),"command")},{name:"bun",command:s(()=>n(["bun","pm","ls","-g"]),"command")},{name:"brew",command:s(()=>n(["brew","list","--formula","opencode"]),"command")},{name:"scoop",command:s(()=>n(["scoop","list","opencode"]),"command")},{name:"choco",command:s(()=>n(["choco","list","--limit-output","opencode"]),"command")}];m.sort((h,g)=>{let w=l.includes(h.name),k=l.includes(g.name);return w&&!k?-1:!w&&k?1:0});for(let h of m){let g=yield*h.command(),w=h.name==="brew"||h.name==="choco"||h.name==="scoop"?"opencode":"opencode-ai";if(g.includes(w))return h.name}return"unknown"}),latest:Ct.fn("Installation.latest")(function*(l){let m=l||(yield*u.method());if(m==="brew"){let w=yield*i();if(w.includes("/")){let f=yield*n(["brew","info","--json=v2",w]);return(yield*pt.decodeUnknownEffect(pt.fromJsonString(HD))(f)).formulae[0].versions.stable}let k=yield*t.execute(Po.get("https://formulae.brew.sh/api/formula/opencode.json").pipe(Po.acceptJson));return(yield*Zs.schemaBodyJson(GD)(k)).versions.stable}if(m==="npm"||m==="bun"||m==="pnpm"){let w=yield*t.execute(Po.get(`${yield*Wl.registry(process.cwd())}/opencode-ai/${is}`).pipe(Po.acceptJson));return(yield*Zs.schemaBodyJson(Om)(w)).version}if(m==="choco"){let w=yield*t.execute(Po.get("https://community.chocolatey.org/api/v2/Packages?$filter=Id%20eq%20%27opencode%27%20and%20IsLatestVersion&$select=Version").pipe(Po.setHeaders({Accept:"application/json;odata=verbose"})));return(yield*Zs.schemaBodyJson(YD)(w)).d.results[0].Version}if(m==="scoop"){let w=yield*t.execute(Po.get("https://raw.githubusercontent.com/ScoopInstaller/Main/master/bucket/opencode.json").pipe(Po.setHeaders({Accept:"application/json"})));return(yield*Zs.schemaBodyJson(KD)(w)).version}let h=yield*t.execute(Po.get("https://api.github.com/repos/anomalyco/opencode/releases/latest").pipe(Po.acceptJson));return(yield*Zs.schemaBodyJson(zD)(h)).tag_name.replace(/^v/,"")},Ct.orDie),upgrade:Ct.fn("Installation.upgrade")(function*(l,m){let h;switch(l){case"curl":h=yield*d(m);break;case"npm":h=yield*r(["npm","install","-g",`opencode-ai@${m}`]);break;case"pnpm":h=yield*r(["pnpm","install","-g",`opencode-ai@${m}`]);break;case"bun":h=yield*r(["bun","install","-g",`opencode-ai@${m}`]);break;case"brew":{let g=yield*i(),w={HOMEBREW_NO_AUTO_UPDATE:"1"};if(g.includes("/")){let k=yield*r(["brew","tap","anomalyco/tap"],{env:w});if(k.code!==0){h=k;break}let f=(yield*n(["brew","--repo","anomalyco/tap"])).trim();if(f){let S=yield*r(["git","pull","--ff-only"],{cwd:f,env:w});if(S.code!==0){h=S;break}}}h=yield*r(["brew","upgrade",g],{env:w});break}case"choco":h=yield*r(["choco","upgrade","opencode",`--version=${m}`,"-y"]);break;case"scoop":h=yield*r(["scoop","install",`opencode@${m}`]);break;default:return yield*new es({stderr:`Unknown installation method: ${l}`})}if(!h||h.code!==0)return yield*new es({stderr:a(l,h)});yield*Ct.logInfo("upgraded",{method:l,target:m,stdout:h.stdout,stderr:h.stderr}),yield*n([process.execPath,"--version"])})};return wn.of(u)})),Lm=ge.make({service:wn,layer:XD,deps:[Co,nr.node]}),{runPromise:il}=$l(wn,Rn.build(Lm)),QD=s((...e)=>il(t=>t.latest(...e)),"latest"),ZD=s(()=>il(e=>e.method()),"method"),eE=s((...e)=>il(t=>t.upgrade(...e)),"upgrade");var cl={};ae(cl,{Service:()=>os,SessionShare:()=>cl,node:()=>sE});import{Effect as ts,Layer as tE,Scope as oE,Context as nE}from"effect";var os=class extends nE.Service()("@opencode/SessionShare"){static{s(this,"Service")}},rE=tE.effect(os,ts.gen(function*(){let e=yield*De.Service,t=yield*ce.Service,o=yield*Qo.Service,n=yield*oE.Scope,r=yield*Me.Service,i=ts.fn("SessionShare.share")(function*(d){if((yield*e.get()).share==="disabled")throw new Error("Sharing is disabled in configuration");let l=yield*o.create(d);return yield*t.setShare({sessionID:d,share:{url:l.url}}),l}),a=ts.fn("SessionShare.unshare")(function*(d){yield*o.remove(d),yield*t.setShare({sessionID:d,share:void 0})}),c=ts.fn("SessionShare.create")(function*(d){let u=yield*t.create(d);if(u.parentID)return u;let l=yield*e.get();return(r.autoShare||l.share==="auto")&&(yield*i(u.id).pipe(ts.ignore,ts.forkIn(n))),u});return os.of({create:c,share:i,unshare:a})})),sE=ge.make({service:os,layer:rE,deps:[De.node,ce.node,Qo.node,Me.node]});export{Rn as a,ja as b,Lt as c,Fa as d,to as e,cn as f,ur as g,po as h,qo as i,mo as j,ho as k,zo as l,Es as m,Pr as n,Ar as o,Lo as p,Ps as q,ut as r,Xt as s,Wn as t,xf as u,Ko as v,Kn as w,Yr as x,qs as y,Jn as z,ao as A,Qo as B,Jr as C,rl as D,Qs as E,al as F,cl as G};