alchemylab-opencode 2.0.1 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NODE_COMPAT.md +8 -1
- package/dist/20260127222353_familiar_lady_ursula-YYOFSQD5.js +18 -0
- package/dist/20260211171708_add_project_commands-3GKQTPBZ.js +18 -0
- package/dist/20260213144116_wakeful_the_professor-ROO7OAVL.js +18 -0
- package/dist/20260225215848_workspace-V2OZTNFF.js +18 -0
- package/dist/20260227213759_add_session_workspace_id-GVDWAXKM.js +18 -0
- package/dist/20260228203230_blue_harpoon-Z5QP2II5.js +18 -0
- package/dist/20260303231226_add_workspace_fields-QOVAFN7W.js +18 -0
- package/dist/20260309230000_move_org_to_state-RQURSDZD.js +18 -0
- package/dist/20260312043431_session_message_cursor-VBISKDXL.js +18 -0
- package/dist/20260323234822_events-PILJHLNA.js +18 -0
- package/dist/20260410174513_workspace-name-63YCZ5NS.js +18 -0
- package/dist/20260413175956_chief_energizer-NMAZYGDO.js +18 -0
- package/dist/20260423070820_add_icon_url_override-RAJCVNEP.js +18 -0
- package/dist/20260427172553_slow_nightmare-ULYYZLR4.js +18 -0
- package/dist/20260428004200_add_session_path-U4WO2TGE.js +18 -0
- package/dist/20260501142318_next_venus-6BCYATSC.js +18 -0
- package/dist/20260504145000_add_sync_owner-RGVHV6LN.js +18 -0
- package/dist/20260507164347_add_workspace_time-GE6UHNPM.js +18 -0
- package/dist/{20260510033149_session_usage-UGBVOXZB.js → 20260510033149_session_usage-7XHCFVKY.js} +5 -1
- package/dist/20260511000411_data_migration_state-2EGZKFLB.js +18 -0
- package/dist/20260511173437_session-metadata-K322YY33.js +18 -0
- package/dist/20260601010001_normalize_storage_paths-VZDTY366.js +18 -0
- package/dist/{20260225215848_workspace-ZMSOZSPA.js → 20260601202201_amazing_prowler-YT6PLK3L.js} +5 -1
- package/dist/{20260228203230_blue_harpoon-IW3Z4TQZ.js → 20260602002951_lowly_union_jack-6VLQTBVB.js} +5 -1
- package/dist/20260602182828_add_project_directories-TVSRD25A.js +18 -0
- package/dist/20260603001617_session_message_projection_indexes-PHKTF6HK.js +18 -0
- package/dist/{20260622170816_reset_v2_session_state-5JPHJTZG.js → 20260603040000_session_message_projection_order-7RTV2POG.js} +5 -1
- package/dist/20260603141458_session_input_inbox-RSBWABG7.js +18 -0
- package/dist/20260603160727_jittery_ezekiel_stane-DXBLLRVV.js +18 -0
- package/dist/20260604172448_event_sourced_session_input-H6Z3JEBD.js +18 -0
- package/dist/20260605003541_add_session_context_snapshot-6FDPM2TK.js +18 -0
- package/dist/20260605042240_add_context_epoch_agent-C2OF2UKR.js +18 -0
- package/dist/20260611035744_credential-YNZ47FSH.js +18 -0
- package/dist/20260611192811_lush_chimera-E357VI6P.js +18 -0
- package/dist/20260612174303_project_dir_strategy-VUGGK42O.js +18 -0
- package/dist/20260622142730_simplify_session_context_epoch-UYGXZ5BX.js +18 -0
- package/dist/20260622170816_reset_v2_session_state-EILLPCJQ.js +18 -0
- package/dist/20260622202450_simplify_session_input-Y65GDGBO.js +18 -0
- package/dist/NodeSdk-AGMQWBHH.js +18 -0
- package/dist/anthropic-45OFTLAW.js +18 -0
- package/dist/anthropic-FVULF7C3.js +18 -0
- package/dist/app-runtime-LDQWNGWP.js +18 -0
- package/dist/chunk-2JE3QYG6.js +18 -0
- package/dist/chunk-2MRHL4B2.js +18 -0
- package/dist/chunk-4GJE6OMN.js +190 -0
- package/dist/chunk-4MBUHJHY.js +22 -0
- package/dist/chunk-5BLZCAU6.js +55 -0
- package/dist/chunk-7XX6TY62.js +259 -0
- package/dist/chunk-ANF3QA3Z.js +48 -0
- package/dist/chunk-AZUMH3TO.js +18 -0
- package/dist/chunk-B74WSFN4.js +878 -0
- package/dist/chunk-BQ4IEPN3.js +19 -0
- package/dist/chunk-CYRZU5QM.js +33 -0
- package/dist/chunk-DADVNQTM.js +1490 -0
- package/dist/chunk-DO2UZ6NY.js +18 -0
- package/dist/chunk-DWEYXIQI.js +780 -0
- package/dist/chunk-EK6FQQHY.js +20 -0
- package/dist/chunk-ELPXQ32J.js +90 -0
- package/dist/chunk-FGLPSSRK.js +19 -0
- package/dist/chunk-FOHYZ7MJ.js +55 -0
- package/dist/chunk-FV7U6PVP.js +18 -0
- package/dist/chunk-FYYAOZPU.js +18 -0
- package/dist/chunk-G7PFO5HG.js +920 -0
- package/dist/chunk-GDWO6EXN.js +22 -0
- package/dist/chunk-GW3ZRKAI.js +20 -0
- package/dist/chunk-IYUSBBGY.js +35 -0
- package/dist/chunk-JPOFLMNH.js +18 -0
- package/dist/{chunk-VURLSDCB.js → chunk-K5LKDIVU.js} +4 -0
- package/dist/chunk-KS4WLVK5.js +19 -0
- package/dist/chunk-LIXP4TPL.js +18 -0
- package/dist/chunk-LSC4RT5V.js +36 -0
- package/dist/chunk-M5A6NFHQ.js +28 -0
- package/dist/chunk-M6E6KNLV.js +30 -0
- package/dist/chunk-MLFZXUGQ.js +18 -0
- package/dist/chunk-NDI67DRG.js +31 -0
- package/dist/chunk-NGT6LCW6.js +18 -0
- package/dist/chunk-OCWGUTZJ.js +36 -0
- package/dist/chunk-OGDRUXMJ.js +18 -0
- package/dist/chunk-OGJKLJC7.js +29 -0
- package/dist/chunk-OT2YNR56.js +19 -0
- package/dist/chunk-OUVSKG2H.js +19 -0
- package/dist/chunk-P5RLCJUV.js +18 -0
- package/dist/chunk-Q3WIUQXB.js +18 -0
- package/dist/{20260227213759_add_session_workspace_id-ROENWPKA.js → chunk-QCRIXKIC.js} +5 -1
- package/dist/chunk-QD24DLUD.js +18 -0
- package/dist/chunk-R2GWBJEP.js +18 -0
- package/dist/chunk-RPAXSOGH.js +18 -0
- package/dist/chunk-TK5R7QUN.js +18 -0
- package/dist/chunk-TNQWZFIZ.js +28 -0
- package/dist/chunk-UCLPBO4I.js +18 -0
- package/dist/chunk-UPEPL4I2.js +18 -0
- package/dist/chunk-V6FDDNGV.js +117 -0
- package/dist/chunk-V6HERYFV.js +18 -0
- package/dist/chunk-V7XKKJ7X.js +24 -0
- package/dist/chunk-VHDYUBBS.js +23 -0
- package/dist/chunk-VWLJXTZ5.js +18 -0
- package/dist/chunk-VXAPFOIL.js +22 -0
- package/dist/chunk-WKZYINC7.js +29 -0
- package/dist/chunk-WPMP2ZFE.js +40 -0
- package/dist/chunk-WRTNIOI3.js +18 -0
- package/dist/chunk-X5F46HR5.js +18 -0
- package/dist/chunk-XPS7TQZG.js +22 -0
- package/dist/chunk-YJPP6IQ3.js +23 -0
- package/dist/chunk-ZYQWFC55.js +22 -0
- package/dist/code-mode-YYOGD36U.js +502 -0
- package/dist/copilot-provider-QVMLQZZC.js +18 -0
- package/dist/dist-5NQOHNPL.js +18 -0
- package/dist/dist-7CT3XCNN.js +32 -0
- package/dist/dist-CL46WFZG.js +18 -0
- package/dist/{20260605042240_add_context_epoch_agent-W6IQYZXE.js → dist-CYBRID2F.js} +5 -1
- package/dist/dist-HXJTF22W.js +32 -0
- package/dist/dist-JFXI53ZF.js +22 -0
- package/dist/dist-KBYKWVT5.js +22 -0
- package/dist/dist-KM5HCPZX.js +35 -0
- package/dist/dist-KTNLTEHB.js +18 -0
- package/dist/dist-KZ5R5QM5.js +24 -0
- package/dist/dist-NLXUYBW7.js +32 -0
- package/dist/dist-O4DF72J2.js +22 -0
- package/dist/dist-PH4MEGVR.js +22 -0
- package/dist/{20260511000411_data_migration_state-FB4LBFSE.js → dist-QJPOJCLB.js} +5 -1
- package/dist/dist-QYH62TCJ.js +22 -0
- package/dist/{20260303231226_add_workspace_fields-OUVZMNAG.js → dist-RIC4WKHC.js} +5 -1
- package/dist/dist-T776XKTM.js +22 -0
- package/dist/dist-TCE5MKZQ.js +23 -0
- package/dist/dist-TH2Q44RX.js +50 -0
- package/dist/dist-VV5FV5RT.js +101 -0
- package/dist/dist-XAFENVUS.js +22 -0
- package/dist/dist-XPFB35TX.js +32 -0
- package/dist/dist-YUH4RKR5.js +28 -0
- package/dist/dist-es-43ZM44MP.js +18 -0
- package/dist/dist-es-6PLFRCS4.js +18 -0
- package/dist/dist-es-G5UIJOU7.js +26 -0
- package/dist/{20260428004200_add_session_path-LGW75WYA.js → dist-es-HYIIGUNX.js} +5 -1
- package/dist/dist-es-L2GU465G.js +18 -0
- package/dist/dist-es-LSR2QCFZ.js +18 -0
- package/dist/dist-es-RGEIM2BP.js +18 -0
- package/dist/dist-es-SITTNOGV.js +18 -0
- package/dist/dist-es-W5GYOX6F.js +18 -0
- package/dist/esm-NN5W7YCL.js +18 -0
- package/dist/esm-XWJSHYHG.js +18 -0
- package/dist/getMachineId-bsd-L5I5TZ5I.js +18 -0
- package/dist/getMachineId-darwin-YB7KG37W.js +19 -0
- package/dist/getMachineId-linux-EL47KXX7.js +18 -0
- package/dist/getMachineId-unsupported-QOWPEBPN.js +18 -0
- package/dist/getMachineId-win-HCRYRDFJ.js +18 -0
- package/dist/lib-ZP7Q6A3E.js +199 -0
- package/dist/loadCognitoIdentity-EWT55EI7.js +18 -0
- package/dist/loadSso-AGOUE6RL.js +18 -0
- package/dist/{20260213144116_wakeful_the_professor-ZVDD54AK.js → loadSts-RH5L3PIX.js} +5 -1
- package/dist/mantle-IJXDXT4M.js +25 -0
- package/dist/mime-types-46EO4HOZ.js +18 -0
- package/dist/multipart-parser-KZWMKXA4.js +19 -0
- package/dist/{20260211171708_add_project_commands-GDOHPDPF.js → open-7KXTRM37.js} +5 -1
- package/dist/openai-ZOJI6I5R.js +18 -0
- package/dist/p-map-CYL6ILJW.js +18 -0
- package/dist/photon-W56QZY4L.js +18 -0
- package/dist/{20260423070820_add_icon_url_override-X5SHFGTI.js → pkce-VT4ITJTB.js} +5 -1
- package/dist/{pty.node-Y3N2XKYG.js → pty.node-IWULXXG6.js} +5 -1
- package/dist/run.js +5 -1
- package/dist/serve.js +143 -1
- package/dist/server-LVIHYOCY.js +21 -0
- package/dist/session-6OPJNJMK.js +18 -0
- package/dist/signin-OCIW23YM.js +18 -0
- package/dist/src-3NCXEROI.js +18 -0
- package/dist/src-LXWGIUZH.js +18 -0
- package/dist/src-WDYKISPD.js +20 -0
- package/dist/src-YAAFIGTW.js +18 -0
- package/dist/sso-oidc-OMMKINFE.js +18 -0
- package/dist/sts-MWK22JIX.js +18 -0
- package/dist/token-QPO3OAGS.js +18 -0
- package/dist/token-util-YGPCEEPO.js +18 -0
- package/dist/unified-W3ZKZ4HG.js +18 -0
- package/dist/worktree-32M5MTFE.js +18 -0
- package/package.json +40 -40
- package/postinstall.cjs +4 -2
- package/dist/20260127222353_familiar_lady_ursula-KV747FJX.js +0 -14
- package/dist/20260309230000_move_org_to_state-NOXAPU5V.js +0 -14
- package/dist/20260312043431_session_message_cursor-DJ4T3T4R.js +0 -14
- package/dist/20260323234822_events-72GIKJ2A.js +0 -14
- package/dist/20260410174513_workspace-name-JXSWFBJN.js +0 -14
- package/dist/20260413175956_chief_energizer-4HEWZ6U3.js +0 -14
- package/dist/20260427172553_slow_nightmare-PS5T2AH2.js +0 -14
- package/dist/20260501142318_next_venus-J3TLVXZ6.js +0 -14
- package/dist/20260504145000_add_sync_owner-3R52GB4C.js +0 -14
- package/dist/20260507164347_add_workspace_time-JHDRCZAR.js +0 -14
- package/dist/20260511173437_session-metadata-T2XHGWHS.js +0 -14
- package/dist/20260601010001_normalize_storage_paths-5MAY5GT3.js +0 -14
- package/dist/20260601202201_amazing_prowler-PET224YG.js +0 -14
- package/dist/20260602002951_lowly_union_jack-PG6XDMGL.js +0 -14
- package/dist/20260602182828_add_project_directories-ZCH2ACGG.js +0 -14
- package/dist/20260603001617_session_message_projection_indexes-XVLJTUF2.js +0 -14
- package/dist/20260603040000_session_message_projection_order-XG6RACZQ.js +0 -14
- package/dist/20260603141458_session_input_inbox-K2VQ7V6E.js +0 -14
- package/dist/20260603160727_jittery_ezekiel_stane-WKJLRDO7.js +0 -14
- package/dist/20260604172448_event_sourced_session_input-NTXOECR7.js +0 -14
- package/dist/20260605003541_add_session_context_snapshot-DXMQEXMT.js +0 -14
- package/dist/20260611035744_credential-XTMSYTJD.js +0 -14
- package/dist/20260611192811_lush_chimera-XPLIQMJD.js +0 -14
- package/dist/20260612174303_project_dir_strategy-FR2NGQKK.js +0 -14
- package/dist/20260622142730_simplify_session_context_epoch-NTQZR3RE.js +0 -14
- package/dist/20260622202450_simplify_session_input-2EXF2HMV.js +0 -14
- package/dist/app-runtime-HQBOCDV5.js +0 -14
- package/dist/chunk-4FEBIOI5.js +0 -865
- package/dist/chunk-4K2RXRZL.js +0 -14
- package/dist/chunk-4RFMKEKM.js +0 -1455
- package/dist/chunk-BM2C7NHL.js +0 -41
- package/dist/chunk-MKEMZFJI.js +0 -393
- package/dist/chunk-OMDJ6ZZ2.js +0 -684
- package/dist/chunk-OWMG4NNF.js +0 -186
- package/dist/chunk-QRABYJKL.js +0 -14
- package/dist/chunk-RHIWAYN5.js +0 -14
- package/dist/chunk-Z5TLIUAI.js +0 -28
- package/dist/code-mode-7BQJUARW.js +0 -40
- package/dist/copilot-provider-TX4YFKJZ.js +0 -14
- package/dist/photon-VQS5F5BI.js +0 -14
- package/dist/server-BFUQR7MX.js +0 -17
- package/dist/session-6RNXZNG6.js +0 -14
- package/dist/worktree-QHQHX3SG.js +0 -14
- package/patches/@ai-sdk%2Famazon-bedrock@4.0.166.patch +0 -164
- package/patches/@ai-sdk%2Fanthropic@3.0.111.patch +0 -528
- package/patches/@ai-sdk%2Fgoogle@3.0.73.patch +0 -69
- package/patches/@ai-sdk%2Fgroq@3.0.31.patch +0 -79
- package/patches/@ai-sdk%2Fmistral@3.0.51.patch +0 -714
- package/patches/@ai-sdk%2Fopenai-compatible@2.0.41.patch +0 -39
- package/patches/@ai-sdk%2Fopenai@3.0.88.patch +0 -280
- package/patches/@ai-sdk%2Fxai@3.0.139.patch +0 -296
- package/patches/@modelcontextprotocol%2Fsdk@1.29.0.patch +0 -647
- package/patches/@npmcli%2Fagent@4.0.2.patch +0 -13
- package/patches/effect@4.0.0-beta.83.patch +0 -57
- package/patches/gcp-metadata@8.1.2.patch +0 -14
- package/patches/pacote@21.5.0.patch +0 -18
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Built by esbuild from opencode-server source
|
|
2
|
+
if (typeof globalThis.Bun === 'undefined') {
|
|
3
|
+
globalThis.Bun = {
|
|
4
|
+
version: '0.0.0-node-compat',
|
|
5
|
+
stdin: { async text() { const chunks = []; for await (const c of process.stdin) chunks.push(c); return Buffer.concat(chunks).toString(); } },
|
|
6
|
+
which(cmd) { try { return require('child_process').execFileSync('which', [cmd], { encoding: 'utf8' }).trim(); } catch { return null; } },
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
if (typeof globalThis.__name === 'undefined') { globalThis.__name = (t, n) => { Object.defineProperty(t, 'name', { value: n, configurable: true }); return t; }; }
|
|
10
|
+
if (typeof globalThis.__export === 'undefined') { globalThis.__export = (t, a) => { for (const k in a) Object.defineProperty(t, k, { get: a[k], enumerable: true }); }; }
|
|
11
|
+
import { createRequire as __alchemyCreateRequire } from 'node:module';
|
|
12
|
+
const require = __alchemyCreateRequire(import.meta.url);
|
|
13
|
+
import { fileURLToPath as __alchemyFileURLToPath } from 'node:url';
|
|
14
|
+
import { dirname as __alchemyDirname } from 'node:path';
|
|
15
|
+
const __alchemy_filename = __alchemyFileURLToPath(import.meta.url);
|
|
16
|
+
const __alchemy_dirname = __alchemyDirname(__alchemy_filename);
|
|
17
|
+
|
|
18
|
+
import{A as Hm,B as Pm,C as ha,D as fe,E as bm,F as Es,G as Sa,a as am,b as Xe,c as hm,d as Nc,e as $t,f as vo,g as Sm,h as Kr,i as ma,j as la,k as Eo,l as Am,m as Im,n as fa,o as Ao,p as wm,q as Rm,r as Xr,s as Io,t as Cm,u as _c,v as ya,w as ga,x as Vt,y as km,z as at}from"./chunk-DADVNQTM.js";import{D as qm,F as wo,G as Me,H as zt,a as Gu,c as om,d as oa,e as Pt,f as yo,g as Ke,h as sm,i as he,j as Qr,k as sa,p as Mc,r as im,s as Ss,t as Ne,v as ym,z as Dm}from"./chunk-G7PFO5HG.js";import{a as xm,b as Jr,f as it,g as It,h as Tm,w as lr}from"./chunk-4GJE6OMN.js";import{L as ho,N as Cn,O as gm,P as So,S as vm,T as ie,W as Em,X as qe,b as Bu,c as Fu,d as qc,e as hs,f as fo,g as Xu,h as ta,i as Ju,j as Zu,k as ra,m as nm,n as na}from"./chunk-B74WSFN4.js";import"./chunk-GW3ZRKAI.js";import{R as X,g as pa,h as lm,i as fm,j as Y,k as Yr,l as Uc,p as da,q as ua}from"./chunk-FOHYZ7MJ.js";import{$ as lo,B as Yu,Ba as pe,C as gs,Ca as Lc,Da as Ue,Ea as um,Ia as go,X as Ku,_ as mo,_a as At,a as wn,aa as Et,b as Ru,c as Ge,d as K,da as em,e as Wu,ea as tm,f as $u,g as Vu,h as $r,ha as rm,i as zu,j as Qu,ja as cm,jb as mr,k as ea,ka as pm,kb as Wt,la as ia,lb as mm,mb as vs,r as Vr,t as bc,ta as dm,u as zr,v as ys,va as Gt,wa as aa,xa as ca,ya as Oc}from"./chunk-DWEYXIQI.js";import"./chunk-QD24DLUD.js";import"./chunk-OUVSKG2H.js";import"./chunk-V6FDDNGV.js";import"./chunk-QCRIXKIC.js";import"./chunk-P5RLCJUV.js";import"./chunk-LIXP4TPL.js";import"./chunk-M6E6KNLV.js";import{d as Ch}from"./chunk-NDI67DRG.js";import"./chunk-WKZYINC7.js";import"./chunk-Q3WIUQXB.js";import"./chunk-WPMP2ZFE.js";import"./chunk-K5LKDIVU.js";import"./chunk-TK5R7QUN.js";import{b as Rn,d as Zi,f as Wr}from"./chunk-R2GWBJEP.js";import{$ as Su,$a as bu,A as nu,Aa as st,B as ji,Ba as Pc,C as Gi,Ca as Ye,D as ou,Da as Qi,E as Rc,Ea as ds,F as su,G as iu,H as q,I as Qe,J as Cc,Ja as be,K as au,L as Le,La as kt,M as xc,Ma as us,N as pu,Na as Cu,O as du,P as kc,Pa as Yi,Q as Wi,R as uu,Ra as xu,S as mu,Sa as ku,Sb as Mu,Sc as jr,T as lu,Ta as Hu,Tc as Uu,U as fu,Ub as po,V as ge,Vb as Ou,Vc as uo,W as yu,Wc as Ht,X as gu,Xa as Pu,Y as _r,Ya as Tu,Z as $i,_ as hu,aa as vu,ba as Eu,bd as Fe,ca as Ce,cd as ce,de as Tc,ed as Dn,fe as Ji,ga as Au,ge as le,ha as zi,ia as Br,j as ru,je as _u,ke as je,la as In,lb as ms,le as fs,m as An,ma as Ae,mb as Ki,mc as Lu,n as ao,na as vt,nb as qu,oa as Ie,pc as ur,q as _i,qa as Du,qb as Fr,rb as Xi,sb as ls,sd as Nu,we as ju,x as Bi,xa as z,xe as Gr,y as Fi,z as Be}from"./chunk-7XX6TY62.js";import"./chunk-LSC4RT5V.js";import"./chunk-V7XKKJ7X.js";import"./chunk-FV7U6PVP.js";import"./chunk-UCLPBO4I.js";import"./chunk-V6HERYFV.js";import"./chunk-DO2UZ6NY.js";import"./chunk-AZUMH3TO.js";import{d as jt,h as cu,p as Vi,u as Iu,v as wu}from"./chunk-VWLJXTZ5.js";import{$f as Nd,$i as Mi,Bc as xt,Bd as Ei,Be as lc,Bf as s,Bh as Ci,Ca as yi,Cf as ns,Ch as is,Ci as Kd,Df as Pd,Dh as $d,Di as Xd,Ee as Hd,Ef as Lr,Eh as Vd,Ei as Jd,Ej as co,Ff as Td,Fg as Ee,Gd as re,Gf as oo,Gi as bi,Hc as Id,Hf as dr,Ia as Ed,Ih as zd,Ii as as,Jh as xi,Kd as Dd,Kf as yc,Ki as cs,Lc as vi,Lf as bd,Lh as ki,Li as Ic,Md as es,Mi as Sn,Nd as no,Oa as Te,Oh as Ur,Oi as Zd,P as fi,Pa as gi,Pd as dc,Pf as gc,Pi as qi,Qf as qd,Ra as Mr,Rf as Md,Rh as Hi,S as yd,Sa as Or,Sd as uc,Sf as Od,Sh as Pi,Si as Nr,Ta as hi,Tc as P,Td as pr,Tf as Ld,Uf as Ii,Ui as wc,Va as Xo,Vf as Ud,Vi as vn,Wa as ac,Wf as wi,Xd as Rd,Xf as hc,Ya as cc,Yf as Sc,Yi as eu,Z as gd,Za as Ct,Zd as ts,Zf as so,_ as hd,_a as Jo,_f as vc,a as br,aa as Re,ab as Ad,ae as Ai,ag as _d,bb as oe,bg as hn,bi as se,bj as tu,c as gn,cg as Ec,cj as Dc,dc as cr,dg as os,dj as Oi,eg as Bd,eh as ss,f as ld,fa as Sd,fj as nt,ge as Cd,gh as jd,h as fd,he as Bt,hj as Li,ih as Di,ij as Ui,ja as sc,jd as _t,jh as Ri,kd as wd,kj as ps,lc as ro,lj as ot,me as xd,mh as io,nb as Si,nd as pc,nj as En,of as fc,oj as Ni,pg as Fd,pj as o,qa as vd,qj as Hc,r as St,rc as Zo,rg as Ac,rh as Gd,ta as qr,ti as ze,ue as mc,ui as Ti,wh as Ft,wi as Qd,ye as rs,yh as Wd,yi as Yd,za as ic,ze as kd}from"./chunk-ELPXQ32J.js";import{a as i,b as yn,d as ve,e as me,g as oc}from"./chunk-2MRHL4B2.js";var Ca=ve(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});tp.default=Av;var al=/[A-Z]/g;function cl(t){return t.toLowerCase()}i(cl,"toLowerCase");function Av(t,e){let r=t.replace(al,cl),n=e.replace(al,cl);return r===n}i(Av,"dnsEqual")});var rp=ve(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.DnsTxt=void 0;var xa=class{static{i(this,"DnsTxt")}constructor(e={}){this.binary=e?e.binary:!1}encode(e={}){return Object.entries(e).map(([r,n])=>{let a=`${r}=${n}`;return Buffer.from(a)})}decode(e){var r={};try{let a=e.toString().split(/=(.+)/),c=a[0],p=a[1];r[c]=p}catch{}return r}decodeAll(e){return e.filter(r=>r.length>1).map(r=>this.decode(r)).reduce((r,n)=>{var a=r;let[c]=Object.keys(n),[p]=Object.values(n);return a[c]=p,a},{})}};Ws.DnsTxt=xa;Ws.default=xa});var np=ve(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.toType=Co.toString=void 0;var pl=i(t=>"_"+t,"Prefix"),Iv=i(t=>["name","protocol","subtype"].includes(t),"AllowedProp"),wv=i(t=>{let e={name:t.name,protocol:t.protocol,subtype:t.subtype};return Object.entries(e).filter(([n,a])=>Iv(n)&&a!==void 0).reduce((n,[a,c])=>(typeof c==="object"?c.map(p=>n.push(pl(p))):n.push(pl(c)),n),[]).join(".")},"toString");Co.toString=wv;var Dv=i(t=>{let e=t.split("."),r;for(let n in e)e[n][0]==="_"&&(e[n]=e[n].slice(1));return e.includes("sub")&&(r=e.shift(),e.shift()),{name:e.shift(),protocol:e.shift()||null,subtype:r}},"toType");Co.toType=Dv});var op=ve(On=>{"use strict";var ul=On&&On.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(On,"__esModule",{value:!0});On.Service=void 0;var dl=ul(yn("os")),Rv=ul(rp()),Cv=yn("events"),xv=np(),ka=".local",Ha=class extends Cv.EventEmitter{static{i(this,"Service")}constructor(e){if(super(),this.probe=!0,this.published=!1,this.activated=!1,this.destroyed=!1,this.txtService=new Rv.default,!e.name)throw new Error("ServiceConfig requires `name` property to be set");if(!e.type)throw new Error("ServiceConfig requires `type` property to be set");if(!e.port)throw new Error("ServiceConfig requires `port` property to be set");this.name=e.name.split(".").join("-"),this.protocol=e.protocol||"tcp",this.type=(0,xv.toString)({name:e.type,protocol:this.protocol}),this.port=e.port,this.host=e.host||dl.default.hostname(),this.fqdn=`${this.name}.${this.type}${ka}`,this.txt=e.txt,this.subtypes=e.subtypes,this.disableIPv6=!!e.disableIPv6}records(){var e=[this.RecordPTR(this),this.RecordSRV(this),this.RecordTXT(this)];for(let n of this.subtypes||[])e.push(this.RecordSubtypePTR(this,n));let r=Object.values(dl.default.networkInterfaces());for(let n of r){let a=n;for(let c of a)if(!(c.internal||c.mac==="00:00:00:00:00:00"))switch(c.family){case"IPv4":e.push(this.RecordA(this,c.address));break;case"IPv6":if(this.disableIPv6)break;e.push(this.RecordAAAA(this,c.address));break}}return e}RecordPTR(e){return{name:`${e.type}${ka}`,type:"PTR",ttl:28800,data:e.fqdn}}RecordSubtypePTR(e,r){return{name:`_${r}._sub.${e.type}${ka}`,type:"PTR",ttl:28800,data:`${e.name}.${e.type}${ka}`}}RecordSRV(e){return{name:e.fqdn,type:"SRV",ttl:120,data:{port:e.port,target:e.host}}}RecordTXT(e){return{name:e.fqdn,type:"TXT",ttl:4500,data:this.txtService.encode(e.txt)}}RecordA(e,r){return{name:e.host,type:"A",ttl:120,data:r}}RecordAAAA(e,r){return{name:e.host,type:"AAAA",ttl:120,data:r}}};On.Service=Ha;On.default=Ha});var ll=ve(Ln=>{"use strict";var ml=Ln&&Ln.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ln,"__esModule",{value:!0});Ln.Registry=void 0;var kv=ml(Ca()),sp=ml(op()),Hv=3600*1e3,Pv=3,Tv=i(function(){},"noop"),Pa=class{static{i(this,"Registry")}constructor(e){this.services=[],this.server=e}publish(e){function r(c,p,f){c.activated||(c.activated=!0,p.services.push(c),c instanceof sp.default&&(f?.probe?p.probe(p.server.mdns,c,l=>{if(l){c.stop!==void 0&&c.stop(),console.log(new Error("Service name is already in use on the network"));return}p.announce(p.server,c)}):p.announce(p.server,c)))}i(r,"start");function n(c,p,f){if(f||(f=Tv),!c.activated||!(c instanceof sp.default))return process.nextTick(f);p.teardown(p.server,c,f);let l=p.services.indexOf(c);l!==-1&&p.services.splice(l,1)}i(n,"stop");let a=new sp.default(e);return a.start=r.bind(null,a,this),a.stop=n.bind(null,a,this),a.start({probe:e.probe!==!1}),a}unpublishAll(e){this.teardown(this.server,this.services,e),this.services=[]}destroy(){this.services.map(e=>e.destroyed=!0)}probe(e,r,n){var a=!1,c=0,p;let f=i(()=>{!r.activated||r.destroyed||e.query(r.fqdn,"ANY",function(){a=!0,p=setTimeout(++c<3?f:y,250),p.unref()})},"send"),l=i(g=>{a&&(g.answers.some(m)||g.additionals.some(m))&&y(!0)},"onresponse"),m=i(g=>(0,kv.default)(g.name,r.fqdn),"matchRR"),y=i(g=>{e.removeListener("response",l),clearTimeout(p),n(!!g)},"done");e.on("response",l),setTimeout(f,Math.random()*250)}announce(e,r){var n=1e3,a=r.records();e.register(a);let c=i(()=>{!r.activated||r.destroyed||e.mdns.respond(a,function(){r.published||(r.activated=!0,r.published=!0,r.emit("up")),n=n*Pv,n<Hv&&!r.destroyed&&setTimeout(c,n).unref()})},"broadcast");c()}teardown(e,r,n){Array.isArray(r)||(r=[r]),r=r.filter(c=>c.activated);var a=r.flatMap(function(c){c.activated=!1;var p=c.records();return p.forEach(f=>{f.ttl=0}),p});if(a.length===0)return n&&process.nextTick(n);e.unregister(a),e.mdns.respond(a,function(){r.forEach(function(c){c.published=!1}),typeof n=="function"&&n.apply(null,arguments)})}};Ln.Registry=Pa;Ln.default=Pa});var fl=ve(ip=>{"use strict";ip.toString=function(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t};ip.toType=function(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}});var yl=ve(ap=>{"use strict";ap.toString=function(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t};ap.toRcode=function(t){switch(t.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var gl=ve(cp=>{"use strict";cp.toString=function(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t};cp.toOpcode=function(t){switch(t.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var hl=ve(pp=>{"use strict";pp.toString=function(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t};pp.toClass=function(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var Sl=ve(dp=>{"use strict";dp.toString=function(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`};dp.toCode=function(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var Al=ve((El,up)=>{var vl=(function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decode=g,t.encode=y,t.familyOf=m,t.name=void 0,t.sizeOf=l,t.v6=t.v4=void 0;let e=/^(\d{1,3}\.){3,3}\d{1,3}$/,r=4,n=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,a=16,c={name:"v4",size:r,isFormat:i(E=>e.test(E),"isFormat"),encode(E,v,h){h=~~h,v=v||new Uint8Array(h+r);let w=E.length,C=0;for(let R=0;R<w;){let b=E.charCodeAt(R++);b===46?(v[h++]=C,C=0):C=C*10+(b-48)}return v[h]=C,v},decode(E,v){return v=~~v,`${E[v++]}.${E[v++]}.${E[v++]}.${E[v]}`}};t.v4=c;let p={name:"v6",size:a,isFormat:i(E=>E.length>0&&n.test(E),"isFormat"),encode(E,v,h){h=~~h;let w=h+a,C=-1,R=0,b=0,M=!0,Z=!1;v=v||new Uint8Array(h+a);for(let Se=0;Se<E.length;Se++){let De=E.charCodeAt(Se);De===58?(M?C!==-1?(h<w&&(v[h]=0),h<w-1&&(v[h+1]=0),h+=2):h<w&&(C=h):(Z===!0?(h<w&&(v[h]=b),h++):(h<w&&(v[h]=R>>8),h<w-1&&(v[h+1]=R&255),h+=2),R=0,b=0),M=!0,Z=!1):De===46?(h<w&&(v[h]=b),h++,b=0,R=0,M=!1,Z=!0):(M=!1,De>=97?De-=87:De>=65?De-=55:(De-=48,b=b*10+De),R=(R<<4)+De)}if(M===!1)Z===!0?(h<w&&(v[h]=b),h++):(h<w&&(v[h]=R>>8),h<w-1&&(v[h+1]=R&255),h+=2);else if(C===0)h<w&&(v[h]=0),h<w-1&&(v[h+1]=0),h+=2;else if(C!==-1){h+=2;for(let Se=Math.min(h-1,w-1);Se>=C+2;Se--)v[Se]=v[Se-2];v[C]=0,v[C+1]=0,C=h}if(C!==h&&C!==-1)for(h>w-2&&(h=w-2);w>C;)v[--w]=h<w&&h>C?v[--h]:0;else for(;h<w;)v[h++]=0;return v},decode(E,v){v=~~v;let h="";for(let w=0;w<a;w+=2)w!==0&&(h+=":"),h+=(E[v+w]<<8|E[v+w+1]).toString(16);return h.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};t.v6=p;let f="ip";t.name=f;function l(E){if(c.isFormat(E))return c.size;if(p.isFormat(E))return p.size;throw Error(`Invalid ip address: ${E}`)}i(l,"sizeOf");function m(E){return l(E)===c.size?1:2}i(m,"familyOf");function y(E,v,h){h=~~h;let w=l(E);return typeof v=="function"&&(v=v(h+w)),w===c.size?c.encode(E,v,h):p.encode(E,v,h)}i(y,"encode");function g(E,v,h){if(v=~~v,h=h||E.length-v,h===c.size)return c.decode(E,v,h);if(h===p.size)return p.decode(E,v,h);throw Error(`Invalid buffer size needs to be ${c.size} for v4 or ${p.size} for v6.`)}return i(g,"decode"),"default"in t?t.default:t})({});typeof define=="function"&&define.amd?define([],function(){return vl}):typeof up=="object"&&typeof El=="object"&&(up.exports=vl)});var Dl=ve(O=>{"use strict";var L=yn("buffer").Buffer,Dr=fl(),bv=yl(),qv=gl(),ba=hl(),mp=Sl(),Un=Al(),Mv=0,Il=32768,lp=32768,Ov=~lp,wl=32768,Lv=~wl,T=O.name={};T.encode=function(t,e,r,{mail:n=!1}={}){e||(e=L.alloc(T.encodingLength(t))),r||(r=0);let a=r,c=t.replace(/^\.|\.$/gm,"");if(c.length){let p=[];if(n){let f="";c.split(".").forEach(l=>{l.endsWith("\\")?f+=(f.length?".":"")+l.slice(0,-1):p.length===0&&f.length?p.push(f+"."+l):p.push(l)})}else p=c.split(".");for(let f=0;f<p.length;f++){let l=e.write(p[f],r+1);e[r]=l,r+=l+1}}return e[r++]=0,T.encode.bytes=r-a,e};T.encode.bytes=0;T.decode=function(t,e,{mail:r=!1}={}){e||(e=0);let n=[],a=e,c=0,p=0,f=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let l=t[e++];if(p+=f?0:1,l===0)break;if((l&192)===0){if(e+l>t.length)throw new Error("Cannot decode name (buffer overflow)");if(c+=l+1,c>254)throw new Error("Cannot decode name (name too long)");let m=t.toString("utf-8",e,e+l);r&&(m=m.replace(/\./g,"\\.")),n.push(m),e+=l,p+=f?0:l}else if((l&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let m=t.readUInt16BE(e-1)-49152;if(m>=a)throw new Error("Cannot decode name (bad pointer)");e=m,a=m,p+=f?0:1,f=!0}else throw new Error("Cannot decode name (bad label)")}return T.decode.bytes=p,n.length===0?".":n.join(".")};T.decode.bytes=0;T.encodingLength=function(t){return t==="."||t===".."?1:L.byteLength(t.replace(/^\.|\.$/gm,""))+2};var G={};G.encode=function(t,e,r){e||(e=L.alloc(G.encodingLength(t))),r||(r=0);let n=e.write(t,r+1);return e[r]=n,G.encode.bytes=n+1,e};G.encode.bytes=0;G.decode=function(t,e){e||(e=0);let r=t[e],n=t.toString("utf-8",e+1,e+1+r);return G.decode.bytes=r+1,n};G.decode.bytes=0;G.encodingLength=function(t){return L.byteLength(t)+1};var qt={};qt.encode=function(t,e,r){e||(e=qt.encodingLength(t)),r||(r=0);let n=(t.flags||0)&32767,a=t.type==="response"?Il:Mv;return e.writeUInt16BE(t.id||0,r),e.writeUInt16BE(n|a,r+2),e.writeUInt16BE(t.questions.length,r+4),e.writeUInt16BE(t.answers.length,r+6),e.writeUInt16BE(t.authorities.length,r+8),e.writeUInt16BE(t.additionals.length,r+10),e};qt.encode.bytes=12;qt.decode=function(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=t.readUInt16BE(e+2);return{id:t.readUInt16BE(e),type:r&Il?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:qv.toString(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:bv.toString(r&15),questions:new Array(t.readUInt16BE(e+4)),answers:new Array(t.readUInt16BE(e+6)),authorities:new Array(t.readUInt16BE(e+8)),additionals:new Array(t.readUInt16BE(e+10))}};qt.decode.bytes=12;qt.encodingLength=function(){return 12};var yr=O.unknown={};yr.encode=function(t,e,r){return e||(e=L.alloc(yr.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.length,r),t.copy(e,r+2),yr.encode.bytes=t.length+2,e};yr.encode.bytes=0;yr.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=t.slice(e+2,e+2+r);return yr.decode.bytes=r+2,n};yr.decode.bytes=0;yr.encodingLength=function(t){return t.length+2};var gr=O.ns={};gr.encode=function(t,e,r){return e||(e=L.alloc(gr.encodingLength(t))),r||(r=0),T.encode(t,e,r+2),e.writeUInt16BE(T.encode.bytes,r),gr.encode.bytes=T.encode.bytes+2,e};gr.encode.bytes=0;gr.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=T.decode(t,e+2);return gr.decode.bytes=r+2,n};gr.decode.bytes=0;gr.encodingLength=function(t){return T.encodingLength(t)+2};var hr=O.soa={};hr.encode=function(t,e,r){e||(e=L.alloc(hr.encodingLength(t))),r||(r=0);let n=r;return r+=2,T.encode(t.mname,e,r),r+=T.encode.bytes,T.encode(t.rname,e,r,{mail:!0}),r+=T.encode.bytes,e.writeUInt32BE(t.serial||0,r),r+=4,e.writeUInt32BE(t.refresh||0,r),r+=4,e.writeUInt32BE(t.retry||0,r),r+=4,e.writeUInt32BE(t.expire||0,r),r+=4,e.writeUInt32BE(t.minimum||0,r),r+=4,e.writeUInt16BE(r-n-2,n),hr.encode.bytes=r-n,e};hr.encode.bytes=0;hr.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=T.decode(t,e),e+=T.decode.bytes,n.rname=T.decode(t,e,{mail:!0}),e+=T.decode.bytes,n.serial=t.readUInt32BE(e),e+=4,n.refresh=t.readUInt32BE(e),e+=4,n.retry=t.readUInt32BE(e),e+=4,n.expire=t.readUInt32BE(e),e+=4,n.minimum=t.readUInt32BE(e),e+=4,hr.decode.bytes=e-r,n};hr.decode.bytes=0;hr.encodingLength=function(t){return 22+T.encodingLength(t.mname)+T.encodingLength(t.rname)};var Sr=O.txt={};Sr.encode=function(t,e,r){Array.isArray(t)||(t=[t]);for(let a=0;a<t.length;a++)if(typeof t[a]=="string"&&(t[a]=L.from(t[a])),!L.isBuffer(t[a]))throw new Error("Must be a Buffer");e||(e=L.alloc(Sr.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(a){e[r++]=a.length,a.copy(e,r,0,a.length),r+=a.length}),e.writeUInt16BE(r-n-2,n),Sr.encode.bytes=r-n,e};Sr.encode.bytes=0;Sr.decode=function(t,e){e||(e=0);let r=e,n=t.readUInt16BE(e);e+=2;let a=[];for(;n>0;){let c=t[e++];if(--n,n<c)throw new Error("Buffer overflow");a.push(t.slice(e,e+c)),e+=c,n-=c}return Sr.decode.bytes=e-r,a};Sr.decode.bytes=0;Sr.encodingLength=function(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=L.byteLength(r)+1:e+=r.length+1}),e};var vr=O.null={};vr.encode=function(t,e,r){e||(e=L.alloc(vr.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=L.from(t)),t||(t=L.alloc(0));let n=r;r+=2;let a=t.length;return t.copy(e,r,0,a),r+=a,e.writeUInt16BE(r-n-2,n),vr.encode.bytes=r-n,e};vr.encode.bytes=0;vr.decode=function(t,e){e||(e=0);let r=e,n=t.readUInt16BE(e);e+=2;let a=t.slice(e,e+n);return e+=n,vr.decode.bytes=e-r,a};vr.decode.bytes=0;vr.encodingLength=function(t){return t?(L.isBuffer(t)?t.length:L.byteLength(t))+2:2};var Er=O.hinfo={};Er.encode=function(t,e,r){e||(e=L.alloc(Er.encodingLength(t))),r||(r=0);let n=r;return r+=2,G.encode(t.cpu,e,r),r+=G.encode.bytes,G.encode(t.os,e,r),r+=G.encode.bytes,e.writeUInt16BE(r-n-2,n),Er.encode.bytes=r-n,e};Er.encode.bytes=0;Er.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=G.decode(t,e),e+=G.decode.bytes,n.os=G.decode(t,e),e+=G.decode.bytes,Er.decode.bytes=e-r,n};Er.decode.bytes=0;Er.encodingLength=function(t){return G.encodingLength(t.cpu)+G.encodingLength(t.os)+2};var Tt=O.ptr={},Uv=O.cname=Tt,Nv=O.dname=Tt;Tt.encode=function(t,e,r){return e||(e=L.alloc(Tt.encodingLength(t))),r||(r=0),T.encode(t,e,r+2),e.writeUInt16BE(T.encode.bytes,r),Tt.encode.bytes=T.encode.bytes+2,e};Tt.encode.bytes=0;Tt.decode=function(t,e){e||(e=0);let r=T.decode(t,e+2);return Tt.decode.bytes=T.decode.bytes+2,r};Tt.decode.bytes=0;Tt.encodingLength=function(t){return T.encodingLength(t)+2};var Ar=O.srv={};Ar.encode=function(t,e,r){e||(e=L.alloc(Ar.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.priority||0,r+2),e.writeUInt16BE(t.weight||0,r+4),e.writeUInt16BE(t.port||0,r+6),T.encode(t.target,e,r+8);let n=T.encode.bytes+6;return e.writeUInt16BE(n,r),Ar.encode.bytes=n+2,e};Ar.encode.bytes=0;Ar.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n={};return n.priority=t.readUInt16BE(e+2),n.weight=t.readUInt16BE(e+4),n.port=t.readUInt16BE(e+6),n.target=T.decode(t,e+8),Ar.decode.bytes=r+2,n};Ar.decode.bytes=0;Ar.encodingLength=function(t){return 8+T.encodingLength(t.target)};var pt=O.caa={};pt.ISSUER_CRITICAL=128;pt.encode=function(t,e,r){let n=pt.encodingLength(t);return e||(e=L.alloc(pt.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=pt.ISSUER_CRITICAL),e.writeUInt16BE(n-2,r),r+=2,e.writeUInt8(t.flags||0,r),r+=1,G.encode(t.tag,e,r),r+=G.encode.bytes,e.write(t.value,r),r+=L.byteLength(t.value),pt.encode.bytes=n,e};pt.encode.bytes=0;pt.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e);e+=2;let n=e,a={};return a.flags=t.readUInt8(e),e+=1,a.tag=G.decode(t,e),e+=G.decode.bytes,a.value=t.toString("utf-8",e,n+r),a.issuerCritical=!!(a.flags&pt.ISSUER_CRITICAL),pt.decode.bytes=r+2,a};pt.decode.bytes=0;pt.encodingLength=function(t){return G.encodingLength(t.tag)+G.encodingLength(t.value)+2};var nn=O.mx={};nn.encode=function(t,e,r){e||(e=L.alloc(nn.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,T.encode(t.exchange,e,r),r+=T.encode.bytes,e.writeUInt16BE(r-n-2,n),nn.encode.bytes=r-n,e};nn.encode.bytes=0;nn.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=t.readUInt16BE(e),e+=2,n.exchange=T.decode(t,e),e+=T.decode.bytes,nn.decode.bytes=e-r,n};nn.encodingLength=function(t){return 4+T.encodingLength(t.exchange)};var Ir=O.a={};Ir.encode=function(t,e,r){return e||(e=L.alloc(Ir.encodingLength(t))),r||(r=0),e.writeUInt16BE(4,r),r+=2,Un.v4.encode(t,e,r),Ir.encode.bytes=6,e};Ir.encode.bytes=0;Ir.decode=function(t,e){e||(e=0),e+=2;let r=Un.v4.decode(t,e);return Ir.decode.bytes=6,r};Ir.decode.bytes=0;Ir.encodingLength=function(){return 6};var wr=O.aaaa={};wr.encode=function(t,e,r){return e||(e=L.alloc(wr.encodingLength(t))),r||(r=0),e.writeUInt16BE(16,r),r+=2,Un.v6.encode(t,e,r),wr.encode.bytes=18,e};wr.encode.bytes=0;wr.decode=function(t,e){e||(e=0),e+=2;let r=Un.v6.decode(t,e);return wr.decode.bytes=18,r};wr.decode.bytes=0;wr.encodingLength=function(){return 18};var et=O.option={};et.encode=function(t,e,r){e||(e=L.alloc(et.encodingLength(t))),r||(r=0);let n=r,a=mp.toCode(t.code);if(e.writeUInt16BE(a,r),r+=2,t.data)e.writeUInt16BE(t.data.length,r),r+=2,t.data.copy(e,r),r+=t.data.length;else switch(a){case 8:let c=t.sourcePrefixLength||0,p=t.family||Un.familyOf(t.ip),f=Un.encode(t.ip,L.alloc),l=Math.ceil(c/8);e.writeUInt16BE(l+4,r),r+=2,e.writeUInt16BE(p,r),r+=2,e.writeUInt8(c,r++),e.writeUInt8(t.scopePrefixLength||0,r++),f.copy(e,r,0,l),r+=l;break;case 11:t.timeout?(e.writeUInt16BE(2,r),r+=2,e.writeUInt16BE(t.timeout,r),r+=2):(e.writeUInt16BE(0,r),r+=2);break;case 12:let m=t.length||0;e.writeUInt16BE(m,r),r+=2,e.fill(0,r,r+m),r+=m;break;case 14:let y=t.tags.length*2;e.writeUInt16BE(y,r),r+=2;for(let g of t.tags)e.writeUInt16BE(g,r),r+=2;break;default:throw new Error(`Unknown roption code: ${t.code}`)}return et.encode.bytes=r-n,e};et.encode.bytes=0;et.decode=function(t,e){e||(e=0);let r={};r.code=t.readUInt16BE(e),r.type=mp.toString(r.code),e+=2;let n=t.readUInt16BE(e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=t.readUInt16BE(e),e+=2,r.sourcePrefixLength=t.readUInt8(e++),r.scopePrefixLength=t.readUInt8(e++);let a=L.alloc(r.family===1?4:16);t.copy(a,0,e,e+n-4),r.ip=Un.decode(a);break;case 11:n>0&&(r.timeout=t.readUInt16BE(e),e+=2);break;case 14:r.tags=[];for(let c=0;c<n;c+=2)r.tags.push(t.readUInt16BE(e)),e+=2}return et.decode.bytes=n+4,r};et.decode.bytes=0;et.encodingLength=function(t){if(t.data)return t.data.length+4;switch(mp.toCode(t.code)){case 8:let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8;case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)};var ut=O.opt={};ut.encode=function(t,e,r){e||(e=L.alloc(ut.encodingLength(t))),r||(r=0);let n=r,a=xo(t,et);return e.writeUInt16BE(a,r),r=$s(t,et,e,r+2),ut.encode.bytes=r-n,e};ut.encode.bytes=0;ut.decode=function(t,e){e||(e=0);let r=e,n=[],a=t.readUInt16BE(e);e+=2;let c=0;for(;a>0;)n[c++]=et.decode(t,e),e+=et.decode.bytes,a-=et.decode.bytes;return ut.decode.bytes=e-r,n};ut.decode.bytes=0;ut.encodingLength=function(t){return 2+xo(t||[],et)};var We=O.dnskey={};We.PROTOCOL_DNSSEC=3;We.ZONE_KEY=128;We.SECURE_ENTRYPOINT=32768;We.encode=function(t,e,r){e||(e=L.alloc(We.encodingLength(t))),r||(r=0);let n=r,a=t.key;if(!L.isBuffer(a))throw new Error("Key must be a Buffer");return r+=2,e.writeUInt16BE(t.flags,r),r+=2,e.writeUInt8(We.PROTOCOL_DNSSEC,r),r+=1,e.writeUInt8(t.algorithm,r),r+=1,a.copy(e,r,0,a.length),r+=a.length,We.encode.bytes=r-n,e.writeUInt16BE(We.encode.bytes-2,n),e};We.encode.bytes=0;We.decode=function(t,e){e||(e=0);let r=e;var n={},a=t.readUInt16BE(e);if(e+=2,n.flags=t.readUInt16BE(e),e+=2,t.readUInt8(e)!==We.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t.readUInt8(e),e+=1,n.key=t.slice(e,r+a+2),e+=n.key.length,We.decode.bytes=e-r,n};We.decode.bytes=0;We.encodingLength=function(t){return 6+L.byteLength(t.key)};var Yt=O.rrsig={};Yt.encode=function(t,e,r){e||(e=L.alloc(Yt.encodingLength(t))),r||(r=0);let n=r,a=t.signature;if(!L.isBuffer(a))throw new Error("Signature must be a Buffer");return r+=2,e.writeUInt16BE(Dr.toType(t.typeCovered),r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.labels,r),r+=1,e.writeUInt32BE(t.originalTTL,r),r+=4,e.writeUInt32BE(t.expiration,r),r+=4,e.writeUInt32BE(t.inception,r),r+=4,e.writeUInt16BE(t.keyTag,r),r+=2,T.encode(t.signersName,e,r),r+=T.encode.bytes,a.copy(e,r,0,a.length),r+=a.length,Yt.encode.bytes=r-n,e.writeUInt16BE(Yt.encode.bytes-2,n),e};Yt.encode.bytes=0;Yt.decode=function(t,e){e||(e=0);let r=e;var n={},a=t.readUInt16BE(e);return e+=2,n.typeCovered=Dr.toString(t.readUInt16BE(e)),e+=2,n.algorithm=t.readUInt8(e),e+=1,n.labels=t.readUInt8(e),e+=1,n.originalTTL=t.readUInt32BE(e),e+=4,n.expiration=t.readUInt32BE(e),e+=4,n.inception=t.readUInt32BE(e),e+=4,n.keyTag=t.readUInt16BE(e),e+=2,n.signersName=T.decode(t,e),e+=T.decode.bytes,n.signature=t.slice(e,r+a+2),e+=n.signature.length,Yt.decode.bytes=e-r,n};Yt.decode.bytes=0;Yt.encodingLength=function(t){return 20+T.encodingLength(t.signersName)+L.byteLength(t.signature)};var Kt=O.rp={};Kt.encode=function(t,e,r){e||(e=L.alloc(Kt.encodingLength(t))),r||(r=0);let n=r;return r+=2,T.encode(t.mbox||".",e,r,{mail:!0}),r+=T.encode.bytes,T.encode(t.txt||".",e,r),r+=T.encode.bytes,Kt.encode.bytes=r-n,e.writeUInt16BE(Kt.encode.bytes-2,n),e};Kt.encode.bytes=0;Kt.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=T.decode(t,e,{mail:!0})||".",e+=T.decode.bytes,n.txt=T.decode(t,e)||".",e+=T.decode.bytes,Kt.decode.bytes=e-r,n};Kt.decode.bytes=0;Kt.encodingLength=function(t){return 2+T.encodingLength(t.mbox||".")+T.encodingLength(t.txt||".")};var He={};He.encode=function(t,e,r){e||(e=L.alloc(He.encodingLength(t))),r||(r=0);let n=r;for(var a=[],c=0;c<t.length;c++){var p=Dr.toType(t[c]);a[p>>8]===void 0&&(a[p>>8]=[]),a[p>>8][p>>3&31]|=1<<7-(p&7)}for(c=0;c<a.length;c++)if(a[c]!==void 0){var f=L.from(a[c]);e.writeUInt8(c,r),r+=1,e.writeUInt8(f.length,r),r+=1,f.copy(e,r),r+=f.length}return He.encode.bytes=r-n,e};He.encode.bytes=0;He.decode=function(t,e,r){e||(e=0);let n=e;for(var a=[];e-n<r;){var c=t.readUInt8(e);e+=1;var p=t.readUInt8(e);e+=1;for(var f=0;f<p;f++)for(var l=t.readUInt8(e+f),m=0;m<8;m++)if(l&1<<7-m){var y=Dr.toString(c<<8|f<<3|m);a.push(y)}e+=p}return He.decode.bytes=e-n,a};He.decode.bytes=0;He.encodingLength=function(t){for(var e=[],r=0;r<t.length;r++){var n=Dr.toType(t[r]);e[n>>8]=Math.max(e[n>>8]||0,n&255)}var a=0;for(r=0;r<e.length;r++)e[r]!==void 0&&(a+=2+Math.ceil((e[r]+1)/8));return a};var Xt=O.nsec={};Xt.encode=function(t,e,r){e||(e=L.alloc(Xt.encodingLength(t))),r||(r=0);let n=r;return r+=2,T.encode(t.nextDomain,e,r),r+=T.encode.bytes,He.encode(t.rrtypes,e,r),r+=He.encode.bytes,Xt.encode.bytes=r-n,e.writeUInt16BE(Xt.encode.bytes-2,n),e};Xt.encode.bytes=0;Xt.decode=function(t,e){e||(e=0);let r=e;var n={},a=t.readUInt16BE(e);return e+=2,n.nextDomain=T.decode(t,e),e+=T.decode.bytes,n.rrtypes=He.decode(t,e,a-(e-r)),e+=He.decode.bytes,Xt.decode.bytes=e-r,n};Xt.decode.bytes=0;Xt.encodingLength=function(t){return 2+T.encodingLength(t.nextDomain)+He.encodingLength(t.rrtypes)};var Jt=O.nsec3={};Jt.encode=function(t,e,r){e||(e=L.alloc(Jt.encodingLength(t))),r||(r=0);let n=r,a=t.salt;if(!L.isBuffer(a))throw new Error("salt must be a Buffer");let c=t.nextDomain;if(!L.isBuffer(c))throw new Error("nextDomain must be a Buffer");return r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.flags,r),r+=1,e.writeUInt16BE(t.iterations,r),r+=2,e.writeUInt8(a.length,r),r+=1,a.copy(e,r,0,a.length),r+=a.length,e.writeUInt8(c.length,r),r+=1,c.copy(e,r,0,c.length),r+=c.length,He.encode(t.rrtypes,e,r),r+=He.encode.bytes,Jt.encode.bytes=r-n,e.writeUInt16BE(Jt.encode.bytes-2,n),e};Jt.encode.bytes=0;Jt.decode=function(t,e){e||(e=0);let r=e;var n={},a=t.readUInt16BE(e);e+=2,n.algorithm=t.readUInt8(e),e+=1,n.flags=t.readUInt8(e),e+=1,n.iterations=t.readUInt16BE(e),e+=2;let c=t.readUInt8(e);e+=1,n.salt=t.slice(e,e+c),e+=c;let p=t.readUInt8(e);return e+=1,n.nextDomain=t.slice(e,e+p),e+=p,n.rrtypes=He.decode(t,e,a-(e-r)),e+=He.decode.bytes,Jt.decode.bytes=e-r,n};Jt.decode.bytes=0;Jt.encodingLength=function(t){return 8+t.salt.length+t.nextDomain.length+He.encodingLength(t.rrtypes)};var Zt=O.ds={};Zt.encode=function(t,e,r){e||(e=L.alloc(Zt.encodingLength(t))),r||(r=0);let n=r,a=t.digest;if(!L.isBuffer(a))throw new Error("Digest must be a Buffer");return r+=2,e.writeUInt16BE(t.keyTag,r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.digestType,r),r+=1,a.copy(e,r,0,a.length),r+=a.length,Zt.encode.bytes=r-n,e.writeUInt16BE(Zt.encode.bytes-2,n),e};Zt.encode.bytes=0;Zt.decode=function(t,e){e||(e=0);let r=e;var n={},a=t.readUInt16BE(e);return e+=2,n.keyTag=t.readUInt16BE(e),e+=2,n.algorithm=t.readUInt8(e),e+=1,n.digestType=t.readUInt8(e),e+=1,n.digest=t.slice(e,r+a+2),e+=n.digest.length,Zt.decode.bytes=e-r,n};Zt.decode.bytes=0;Zt.encodingLength=function(t){return 6+L.byteLength(t.digest)};var dt=O.sshfp={};dt.getFingerprintLengthForHashType=i(function(e){switch(e){case 1:return 20;case 2:return 32}},"getFingerprintLengthForHashType");dt.encode=i(function(e,r,n){r||(r=L.alloc(dt.encodingLength(e))),n||(n=0);let a=n;n+=2,r[n]=e.algorithm,n+=1,r[n]=e.hash,n+=1;let c=L.from(e.fingerprint.toUpperCase(),"hex");if(c.length!==dt.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return c.copy(r,n),n+=c.byteLength,dt.encode.bytes=n-a,r.writeUInt16BE(dt.encode.bytes-2,a),r},"encode");dt.encode.bytes=0;dt.decode=i(function(e,r){r||(r=0);let n=r,a={};r+=2,a.algorithm=e[r],r+=1,a.hash=e[r],r+=1;let c=dt.getFingerprintLengthForHashType(a.hash);return a.fingerprint=e.slice(r,r+c).toString("hex").toUpperCase(),r+=c,dt.decode.bytes=r-n,a},"decode");dt.decode.bytes=0;dt.encodingLength=function(t){return 4+L.from(t.fingerprint,"hex").byteLength};var er=O.naptr={};er.encode=function(t,e,r){e||(e=L.alloc(er.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.order||0,r),r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,G.encode(t.flags,e,r),r+=G.encode.bytes,G.encode(t.services,e,r),r+=G.encode.bytes,G.encode(t.regexp,e,r),r+=G.encode.bytes,T.encode(t.replacement,e,r),r+=T.encode.bytes,er.encode.bytes=r-n,e.writeUInt16BE(er.encode.bytes-2,n),e};er.encode.bytes=0;er.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.order=t.readUInt16BE(e),e+=2,n.preference=t.readUInt16BE(e),e+=2,n.flags=G.decode(t,e),e+=G.decode.bytes,n.services=G.decode(t,e),e+=G.decode.bytes,n.regexp=G.decode(t,e),e+=G.decode.bytes,n.replacement=T.decode(t,e),e+=T.decode.bytes,er.decode.bytes=e-r,n};er.decode.bytes=0;er.encodingLength=function(t){return G.encodingLength(t.flags)+G.encodingLength(t.services)+G.encodingLength(t.regexp)+T.encodingLength(t.replacement)+6};var tr=O.tlsa={};tr.encode=function(t,e,r){e||(e=L.alloc(tr.encodingLength(t))),r||(r=0);let n=r,a=t.certificate;if(!L.isBuffer(a))throw new Error("Certificate must be a Buffer");return r+=2,e.writeUInt8(t.usage,r),r+=1,e.writeUInt8(t.selector,r),r+=1,e.writeUInt8(t.matchingType,r),r+=1,a.copy(e,r,0,a.length),r+=a.length,tr.encode.bytes=r-n,e.writeUInt16BE(tr.encode.bytes-2,n),e};tr.encode.bytes=0;tr.decode=function(t,e){e||(e=0);let r=e,n={},a=t.readUInt16BE(e);return e+=2,n.usage=t.readUInt8(e),e+=1,n.selector=t.readUInt8(e),e+=1,n.matchingType=t.readUInt8(e),e+=1,n.certificate=t.slice(e,r+a+2),e+=n.certificate.length,tr.decode.bytes=e-r,n};tr.decode.bytes=0;tr.encodingLength=function(t){return 5+L.byteLength(t.certificate)};var fp=O.record=function(t){switch(t.toUpperCase()){case"A":return Ir;case"PTR":return Tt;case"CNAME":return Uv;case"DNAME":return Nv;case"TXT":return Sr;case"NULL":return vr;case"AAAA":return wr;case"SRV":return Ar;case"HINFO":return Er;case"CAA":return pt;case"NS":return gr;case"SOA":return hr;case"MX":return nn;case"OPT":return ut;case"DNSKEY":return We;case"RRSIG":return Yt;case"RP":return Kt;case"NSEC":return Xt;case"NSEC3":return Jt;case"SSHFP":return dt;case"DS":return Zt;case"NAPTR":return er;case"TLSA":return tr}return yr},Oe=O.answer={};Oe.encode=function(t,e,r){e||(e=L.alloc(Oe.encodingLength(t))),r||(r=0);let n=r;if(T.encode(t.name,e,r),r+=T.encode.bytes,e.writeUInt16BE(Dr.toType(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(t.udpPayloadSize||4096,r+2),e.writeUInt8(t.extendedRcode||0,r+4),e.writeUInt8(t.ednsVersion||0,r+5),e.writeUInt16BE(t.flags||0,r+6),r+=8,ut.encode(t.options||[],e,r),r+=ut.encode.bytes}else{let a=ba.toClass(t.class===void 0?"IN":t.class);t.flush&&(a|=lp),e.writeUInt16BE(a,r+2),e.writeUInt32BE(t.ttl||0,r+4),r+=8;let c=fp(t.type);c.encode(t.data,e,r),r+=c.encode.bytes}return Oe.encode.bytes=r-n,e};Oe.encode.bytes=0;Oe.decode=function(t,e){e||(e=0);let r={},n=e;if(r.name=T.decode(t,e),e+=T.decode.bytes,r.type=Dr.toString(t.readUInt16BE(e)),r.type==="OPT")r.udpPayloadSize=t.readUInt16BE(e+2),r.extendedRcode=t.readUInt8(e+4),r.ednsVersion=t.readUInt8(e+5),r.flags=t.readUInt16BE(e+6),r.flag_do=(r.flags>>15&1)===1,r.options=ut.decode(t,e+8),e+=8+ut.decode.bytes;else{let a=t.readUInt16BE(e+2);r.ttl=t.readUInt32BE(e+4),r.class=ba.toString(a&Ov),r.flush=!!(a&lp);let c=fp(r.type);r.data=c.decode(t,e+8),e+=8+c.decode.bytes}return Oe.decode.bytes=e-n,r};Oe.decode.bytes=0;Oe.encodingLength=function(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return T.encodingLength(t.name)+8+fp(t.type).encodingLength(e)};var bt=O.question={};bt.encode=function(t,e,r){e||(e=L.alloc(bt.encodingLength(t))),r||(r=0);let n=r;return T.encode(t.name,e,r),r+=T.encode.bytes,e.writeUInt16BE(Dr.toType(t.type),r),r+=2,e.writeUInt16BE(ba.toClass(t.class===void 0?"IN":t.class),r),r+=2,bt.encode.bytes=r-n,t};bt.encode.bytes=0;bt.decode=function(t,e){e||(e=0);let r=e,n={};return n.name=T.decode(t,e),e+=T.decode.bytes,n.type=Dr.toString(t.readUInt16BE(e)),e+=2,n.class=ba.toString(t.readUInt16BE(e)),e+=2,n.class&wl&&(n.class&=Lv),bt.decode.bytes=e-r,n};bt.decode.bytes=0;bt.encodingLength=function(t){return T.encodingLength(t.name)+4};O.AUTHORITATIVE_ANSWER=1024;O.TRUNCATED_RESPONSE=512;O.RECURSION_DESIRED=256;O.RECURSION_AVAILABLE=128;O.AUTHENTIC_DATA=32;O.CHECKING_DISABLED=16;O.DNSSEC_OK=32768;O.encode=function(t,e,r){let n=!e;n&&(e=L.alloc(O.encodingLength(t))),r||(r=0);let a=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),qt.encode(t,e,r),r+=qt.encode.bytes,r=$s(t.questions,bt,e,r),r=$s(t.answers,Oe,e,r),r=$s(t.authorities,Oe,e,r),r=$s(t.additionals,Oe,e,r),O.encode.bytes=r-a,n&&O.encode.bytes!==e.length?e.slice(0,O.encode.bytes):e};O.encode.bytes=0;O.decode=function(t,e){e||(e=0);let r=e,n=qt.decode(t,e);return e+=qt.decode.bytes,e=Ta(n.questions,bt,t,e),e=Ta(n.answers,Oe,t,e),e=Ta(n.authorities,Oe,t,e),e=Ta(n.additionals,Oe,t,e),O.decode.bytes=e-r,n};O.decode.bytes=0;O.encodingLength=function(t){return qt.encodingLength(t)+xo(t.questions||[],bt)+xo(t.answers||[],Oe)+xo(t.authorities||[],Oe)+xo(t.additionals||[],Oe)};O.streamEncode=function(t){let e=O.encode(t),r=L.alloc(2);r.writeUInt16BE(e.byteLength);let n=L.concat([r,e]);return O.streamEncode.bytes=n.byteLength,n};O.streamEncode.bytes=0;O.streamDecode=function(t){let e=t.readUInt16BE(0);if(t.byteLength<e+2)return null;let r=O.decode(t.slice(2));return O.streamDecode.bytes=O.decode.bytes,r};O.streamDecode.bytes=0;function xo(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}i(xo,"encodingLengthList");function $s(t,e,r,n){for(let a=0;a<t.length;a++)e.encode(t[a],r,n),n+=e.encode.bytes;return n}i($s,"encodeList");function Ta(t,e,r,n){for(let a=0;a<t.length;a++)t[a]=e.decode(r,n),n+=e.decode.bytes;return n}i(Ta,"decodeList")});var xl=ve((gC,Cl)=>{"use strict";var Rl=Wv;process.nextTick(Gv,42);Cl.exports=_v;function _v(t){var e=n;return r;function r(a){e(a||Fv)}function n(a){var c=[a];e=p,t(f);function p(l){c.push(l)}i(p,"wait");function f(l){var m=arguments;for(e=Bv(l)?n:y;c.length;)y(c.shift());function y(g){Rl(jv,g,m)}i(y,"finished")}i(f,"done")}}i(_v,"thunky");function Bv(t){return Object.prototype.toString.call(t)==="[object Error]"}i(Bv,"isError");function Fv(){}i(Fv,"noop");function jv(t,e){t.apply(null,e)}i(jv,"apply");function Gv(t){t===42&&(Rl=process.nextTick)}i(Gv,"upgrade");function Wv(t,e,r){process.nextTick(function(){t(e,r)})}i(Wv,"nextTickArgs")});var Pl=ve((SC,Hl)=>{var yp=Dl(),$v=yn("dgram"),Vv=xl(),zv=yn("events"),hp=yn("os"),gp=i(function(){},"noop");Hl.exports=function(t){t||(t={});var e=new zv.EventEmitter,r=typeof t.port=="number"?t.port:5353,n=t.type||"udp4",a=t.ip||t.host||(n==="udp4"?"224.0.0.251":null),c={address:a,port:r},p={},f=!1,l=null;if(n==="udp6"&&(!a||!t.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var m=t.socket||$v.createSocket({type:n,reuseAddr:t.reuseAddr!==!1,toString:i(function(){return n},"toString")});m.on("error",function(g){g.code==="EACCES"||g.code==="EADDRINUSE"?e.emit("error",g):e.emit("warning",g)}),m.on("message",function(g,E){try{g=yp.decode(g)}catch(v){e.emit("warning",v);return}e.emit("packet",g,E),g.type==="query"&&e.emit("query",g,E),g.type==="response"&&e.emit("response",g,E)}),m.on("listening",function(){r||(r=c.port=m.address().port),t.multicast!==!1&&(e.update(),l=setInterval(e.update,5e3),m.setMulticastTTL(t.ttl||255),m.setMulticastLoopback(t.loopback!==!1))});var y=Vv(function(g){if(!r||t.bind===!1)return g(null);m.once("error",g),m.bind(r,t.bind||t.interface,function(){m.removeListener("error",g),g(null)})});return y(function(g){if(g)return e.emit("error",g);e.emit("ready")}),e.send=function(g,E,v){if(typeof E=="function")return e.send(g,null,E);v||(v=gp),E?!E.host&&!E.address&&(E.address=c.address):E=c,y(h);function h(w){if(f)return v();if(w)return v(w);var C=yp.encode(g);m.send(C,0,C.length,E.port,E.address||E.host,v)}i(h,"onbind")},e.response=e.respond=function(g,E,v){Array.isArray(g)&&(g={answers:g}),g.type="response",g.flags=(g.flags||0)|yp.AUTHORITATIVE_ANSWER,e.send(g,E,v)},e.query=function(g,E,v,h){if(typeof E=="function")return e.query(g,null,null,E);if(typeof E=="object"&&E&&E.port)return e.query(g,null,E,v);if(typeof v=="function")return e.query(g,E,null,v);h||(h=gp),typeof g=="string"&&(g=[{name:g,type:E||"ANY"}]),Array.isArray(g)&&(g={type:"query",questions:g}),g.type="query",e.send(g,v,h)},e.destroy=function(g){if(g||(g=gp),f)return process.nextTick(g);f=!0,clearInterval(l);for(var E in p)try{m.dropMembership(a,E)}catch{}p={},m.close(g)},e.update=function(){for(var g=t.interface?[].concat(t.interface):Yv(),E=!1,v=0;v<g.length;v++){var h=g[v];if(!p[h])try{m.addMembership(a,h),p[h]=!0,E=!0}catch(w){e.emit("warning",w)}}if(E){if(m.setMulticastInterface)try{m.setMulticastInterface(t.interface||Qv())}catch(w){e.emit("warning",w)}e.emit("networkInterface")}},e};function Qv(){for(var t=hp.networkInterfaces(),e=Object.keys(t),r=0;r<e.length;r++)for(var n=t[e[r]],a=0;a<n.length;a++){var c=n[a];if(kl(c.family)&&!c.internal)return hp.platform()==="darwin"&&e[r]==="en0"?c.address:"0.0.0.0"}return"127.0.0.1"}i(Qv,"defaultInterface");function Yv(){for(var t=hp.networkInterfaces(),e=Object.keys(t),r=[],n=0;n<e.length;n++)for(var a=t[e[n]],c=0;c<a.length;c++){var p=a[c];if(kl(p.family)){r.push(p.address);break}}return r}i(Yv,"allInterfaces");function kl(t){return t===4||t==="IPv4"}i(kl,"isIPv4")});var bl=ve((EC,Tl)=>{"use strict";Tl.exports=i(function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,a,c;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!t(e[a],r[a]))return!1;return!0}if(e instanceof Map&&r instanceof Map){if(e.size!==r.size)return!1;for(a of e.entries())if(!r.has(a[0]))return!1;for(a of e.entries())if(!t(a[1],r.get(a[0])))return!1;return!0}if(e instanceof Set&&r instanceof Set){if(e.size!==r.size)return!1;for(a of e.entries())if(!r.has(a[0]))return!1;return!0}if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(r)){if(n=e.length,n!=r.length)return!1;for(a=n;a--!==0;)if(e[a]!==r[a])return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(c=Object.keys(e),n=c.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,c[a]))return!1;for(a=n;a--!==0;){var p=c[a];if(!t(e[p],r[p]))return!1}return!0}return e!==e&&r!==r},"equal")});var ql=ve(Nn=>{"use strict";var Sp=Nn&&Nn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nn,"__esModule",{value:!0});Nn.Server=void 0;var Kv=Sp(Pl()),Xv=Sp(bl()),Jv=Sp(Ca()),qa=class{static{i(this,"Server")}constructor(e,r){this.registry={},this.mdns=(0,Kv.default)(e),this.mdns.setMaxListeners(0),this.mdns.on("query",this.respondToQuery.bind(this)),this.errorCallback=r??function(n){throw n}}register(e){let r=i(n=>{var a=this.registry[n.type];if(!a)a=this.registry[n.type]=[];else if(a.some(this.isDuplicateRecord(n)))return;a.push(n)},"shouldRegister");Array.isArray(e)?e.forEach(r):r(e)}unregister(e){let r=i(n=>{let a=n.type;a in this.registry&&(this.registry[a]=this.registry[a].filter(c=>c.name!==n.name))},"shouldUnregister");Array.isArray(e)?e.forEach(r):r(e)}respondToQuery(e){let r=this;e.questions.forEach(n=>{var a=n.type,c=n.name,p=a==="ANY"?Object.keys(r.registry).map(r.recordsFor.bind(r,c)).flat(1):r.recordsFor(c,a);if(p.length!==0){var f=[];a!=="ANY"&&(p.forEach(l=>{l.type==="PTR"&&(f=f.concat(r.recordsFor(l.data,"SRV")).concat(r.recordsFor(l.data,"TXT")))}),f.filter(function(l){return l.type==="SRV"}).map(function(l){return l.data.target}).filter(this.unique()).forEach(function(l){f=f.concat(r.recordsFor(l,"A")).concat(r.recordsFor(l,"AAAA"))})),r.mdns.respond({answers:p,additionals:f},l=>{l&&this.errorCallback(l)})}})}recordsFor(e,r){return r in this.registry?this.registry[r].filter(n=>{var a=~e.indexOf(".")?n.name:n.name.split(".")[0];return(0,Jv.default)(a,e)}):[]}isDuplicateRecord(e){return r=>e.type===r.type&&e.name===r.name&&(0,Xv.default)(e.data,r.data)}unique(){var e=[];return r=>~e.indexOf(r)?!1:(e.push(r),!0)}};Nn.Server=qa;Nn.default=qa});var Ml=ve(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});vp.default=(t,e)=>{if(e===void 0)return!0;let r=t.txt,n=Object.entries(e).map(([a,c])=>{let p=r[a];return!(p===void 0||c!=p)});return n.length==0?!0:!n.includes(!1)}});var Ol=ve(Ep=>{"use strict";Object.defineProperty(Ep,"__esModule",{value:!0});Ep.default=t=>Object.keys(t).filter(e=>!e.includes("binary")).reduce((e,r)=>Object.assign(e,{[r]:t[r]}),{})});var Ll=ve(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});Ap.default=Zv;function Zv(t,e){if(t===void 0||e===void 0)return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!=n.length)return!1;for(let a of r)if(t[a]!=e[a])return!1;return!0}i(Zv,"equalTxt")});var _l=ve(_n=>{"use strict";var Vs=_n&&_n.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_n,"__esModule",{value:!0});_n.Browser=void 0;var eE=Vs(rp()),on=Vs(Ca()),tE=yn("events"),Ip=np(),Ul=Vs(Ml()),rE=Vs(Ol()),nE=Vs(Ll()),Nl=".local",oE="_services._dns-sd._udp"+Nl,Ma=class t extends tE.EventEmitter{static{i(this,"Browser")}constructor(e,r,n){if(super(),this.onresponse=void 0,this.serviceMap={},this.wildcard=!1,this._services=[],typeof r=="function")return new t(e,null,r);this.mdns=e,this.txt=new eE.default(r!==null&&r.txt!=null?r.txt:void 0),r===null||r.type===void 0?(this.name=oE,this.wildcard=!0):(this.name=(0,Ip.toString)({name:r.type,protocol:r.protocol||"tcp"})+Nl,r.name&&(this.name=r.name+"."+this.name),this.wildcard=!1),r!=null&&r.txt!==void 0&&(this.txtQuery=(0,rE.default)(r.txt)),n&&this.on("up",n),this.start()}start(){if(!(this.onresponse||this.name===void 0)){var e=this,r={};this.wildcard||(r[this.name]=!0),this.onresponse=(n,a)=>{e.wildcard&&n.answers.forEach(c=>{c.type!=="PTR"||c.name!==e.name||c.name in r||(r[c.data]=!0,e.mdns.query(c.data,"PTR"))}),Object.keys(r).forEach(function(c){e.goodbyes(c,n).forEach(e.removeService.bind(e));var p=e.buildServicesFor(c,n,e.txt,a);p.length!==0&&p.forEach(f=>{if(e.serviceMap[f.fqdn]){e.updateService(f);return}e.addService(f)})})},this.mdns.on("response",this.onresponse),this.update()}}stop(){this.onresponse&&(this.mdns.removeListener("response",this.onresponse),this.onresponse=void 0)}update(){this.mdns.query(this.name,"PTR")}get services(){return this._services}addService(e){(0,Ul.default)(e,this.txtQuery)!==!1&&(this._services.push(e),this.serviceMap[e.fqdn]=!0,this.emit("up",e))}updateService(e){var r;if(!(0,nE.default)(e.txt,((r=this._services.find(n=>(0,on.default)(n.fqdn,e.fqdn)))===null||r===void 0?void 0:r.txt)||{})){if(!(0,Ul.default)(e,this.txtQuery)){this.removeService(e.fqdn);return}this._services=this._services.map(function(n){return(0,on.default)(n.fqdn,e.fqdn)?e:n}),this.emit("txt-update",e)}}removeService(e){var r,n;this._services.some(function(a,c){if((0,on.default)(a.fqdn,e))return r=a,n=c,!0}),!(!r||n===void 0)&&(this._services.splice(n,1),delete this.serviceMap[e],this.emit("down",r))}goodbyes(e,r){return r.answers.concat(r.additionals).filter(n=>n.type==="PTR"&&n.ttl===0&&(0,on.default)(n.name,e)).map(n=>n.data)}buildServicesFor(e,r,n,a){var c=r.answers.concat(r.additionals).filter(p=>p.ttl>0);return c.filter(p=>p.type==="PTR"&&(0,on.default)(p.name,e)).map(p=>{let f={addresses:[],subtypes:[]};if(c.filter(l=>l.type==="PTR"&&(0,on.default)(l.data,p.data)&&l.name.includes("._sub")).forEach(l=>{let m=(0,Ip.toType)(l.name);f.subtypes.push(m.subtype)}),c.filter(l=>(l.type==="SRV"||l.type==="TXT")&&(0,on.default)(l.name,p.data)).forEach(l=>{if(l.type==="SRV"){var m=l.name.split("."),y=m[0],g=(0,Ip.toType)(m.slice(1,-1).join("."));f.name=y,f.fqdn=l.name,f.host=l.data.target,f.referer=a,f.port=l.data.port,f.type=g.name,f.protocol=g.protocol}else l.type==="TXT"&&(f.rawTxt=l.data,f.txt=this.txt.decodeAll(l.data))}),!!f.name)return c.filter(l=>(l.type==="A"||l.type==="AAAA")&&(0,on.default)(l.name,f.host)).forEach(l=>f.addresses.push(l.data)),f}).filter(p=>!!p)}};_n.Browser=Ma;_n.default=Ma});var Bl=ve(Mt=>{"use strict";var La=Mt&&Mt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Mt,"__esModule",{value:!0});Mt.Browser=Mt.Service=Mt.Bonjour=void 0;var sE=La(ll()),iE=La(ql()),wp=La(_l());Mt.Browser=wp.default;var aE=La(op());Mt.Service=aE.default;var Oa=class{static{i(this,"Bonjour")}constructor(e={},r){this.server=new iE.default(e,r),this.registry=new sE.default(this.server)}publish(e){return this.registry.publish(e)}unpublishAll(e){return this.registry.unpublishAll(e)}find(e=null,r){return new wp.default(this.server.mdns,e,r)}findOne(e=null,r=1e4,n){let a=new wp.default(this.server.mdns,e);var c;return a.once("up",p=>{c!==void 0&&clearTimeout(c),a.stop(),n&&n(p)}),c=setTimeout(()=>{a.stop(),n&&n(null)},r),a}destroy(e){this.registry.destroy(),this.server.mdns.destroy(e)}};Mt.Bonjour=Oa;Mt.default=Oa});var yg=ve((WN,tc)=>{function pg(t){return Array.isArray(t)?t:[t]}i(pg,"makeArray");var zw=void 0,Xp="",ag=" ",Kp="\\",Qw=/^\s+$/,Yw=/(?:[^\\]|^)\\$/,Kw=/^\\!/,Xw=/^\\#/,Jw=/\r?\n/g,Zw=/^\.{0,2}\/|^\.{1,2}$/,eD=/\/$/,Qo="/",dg="node-ignore";typeof Symbol<"u"&&(dg=Symbol.for("node-ignore"));var ug=dg,Yo=i((t,e,r)=>(Object.defineProperty(t,e,{value:r}),r),"define"),tD=/([0-z])-([0-z])/g,mg=i(()=>!1,"RETURN_FALSE"),rD=i(t=>t.replace(tD,(e,r,n)=>r.charCodeAt(0)<=n.charCodeAt(0)?e:Xp),"sanitizeRange"),nD=i(t=>{let{length:e}=t;return t.slice(0,e-e%2)},"cleanRangeBackSlash"),oD=[[/^\uFEFF/,()=>Xp],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,r)=>e+(r.indexOf("\\")===0?ag:Xp)],[/(\\+?)\s/g,(t,e)=>{let{length:r}=e;return e.slice(0,r-r%2)+ag}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,i(function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"},"startingReplacer")],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,r)=>e+6<r.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,r)=>{let n=r.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Kp],[/\\\\/g,()=>Kp],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,r,n,a)=>e===Kp?`\\[${r}${nD(n)}${a}`:a==="]"&&n.length%2===0?`[${rD(r)}${n}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],sD=/(^|\\\/)?\\\*$/,ui="regex",Za="checkRegex",cg="_",iD={[ui](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Za](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},aD=i(t=>oD.reduce((e,[r,n])=>e.replace(r,n.bind(t)),t),"makeRegexPrefix"),ec=i(t=>typeof t=="string","isString"),cD=i(t=>t&&ec(t)&&!Qw.test(t)&&!Yw.test(t)&&t.indexOf("#")!==0,"checkPattern"),pD=i(t=>t.split(Jw).filter(Boolean),"splitPattern"),Jp=class{static{i(this,"IgnoreRule")}constructor(e,r,n,a,c,p){this.pattern=e,this.mark=r,this.negative=c,Yo(this,"body",n),Yo(this,"ignoreCase",a),Yo(this,"regexPrefix",p)}get regex(){let e=cg+ui;return this[e]?this[e]:this._make(ui,e)}get checkRegex(){let e=cg+Za;return this[e]?this[e]:this._make(Za,e)}_make(e,r){let n=this.regexPrefix.replace(sD,iD[e]),a=this.ignoreCase?new RegExp(n,"i"):new RegExp(n);return Yo(this,r,a)}},dD=i(({pattern:t,mark:e},r)=>{let n=!1,a=t;a.indexOf("!")===0&&(n=!0,a=a.substr(1)),a=a.replace(Kw,"!").replace(Xw,"#");let c=aD(a);return new Jp(t,e,a,r,n,c)},"createRule"),Zp=class{static{i(this,"RuleManager")}constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[ug]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(ec(e)&&(e={pattern:e}),cD(e.pattern)){let r=dD(e,this._ignoreCase);this._added=!0,this._rules.push(r)}}add(e){return this._added=!1,pg(ec(e)?pD(e):e).forEach(this._add,this),this._added}test(e,r,n){let a=!1,c=!1,p;this._rules.forEach(l=>{let{negative:m}=l;c===m&&a!==c||m&&!a&&!c&&!r||!l[n].test(e)||(a=!m,c=m,p=m?zw:l)});let f={ignored:a,unignored:c};return p&&(f.rule=p),f}},uD=i((t,e)=>{throw new e(t)},"throwError"),Pr=i((t,e,r)=>ec(t)?t?Pr.isNotRelative(t)?r(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:r("path must not be empty",TypeError):r(`path must be a string, but got \`${e}\``,TypeError),"checkPath"),lg=i(t=>Zw.test(t),"isNotRelative");Pr.isNotRelative=lg;Pr.convert=t=>t;var ed=class{static{i(this,"Ignore")}constructor({ignorecase:e=!0,ignoreCase:r=e,allowRelativePaths:n=!1}={}){Yo(this,ug,!0),this._rules=new Zp(r),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,r,n,a){let c=e&&Pr.convert(e);return Pr(c,e,this._strictPathCheck?uD:mg),this._t(c,r,n,a)}checkIgnore(e){if(!eD.test(e))return this.test(e);let r=e.split(Qo).filter(Boolean);if(r.pop(),r.length){let n=this._t(r.join(Qo)+Qo,this._testCache,!0,r);if(n.ignored)return n}return this._rules.test(e,!1,Za)}_t(e,r,n,a){if(e in r)return r[e];if(a||(a=e.split(Qo).filter(Boolean)),a.pop(),!a.length)return r[e]=this._rules.test(e,n,ui);let c=this._t(a.join(Qo)+Qo,r,n,a);return r[e]=c.ignored?c:this._rules.test(e,n,ui)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return pg(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},td=i(t=>new ed(t),"factory"),mD=i(t=>Pr(t&&Pr.convert(t),t,mg),"isPathValid"),fg=i(()=>{let t=i(r=>/^\\\\\?\\/.test(r)||/["<>|\u0000-\u001F]+/u.test(r)?r:r.replace(/\\/g,"/"),"makePosix");Pr.convert=t;let e=/^[a-z]:\//i;Pr.isNotRelative=r=>e.test(r)||lg(r)},"setupWindows");typeof process<"u"&&process.platform==="win32"&&fg();tc.exports=td;td.default=td;tc.exports.isPathValid=mD;Yo(tc.exports,Symbol.for("setupWindows"),fg)});var md={};me(md,{Default:()=>XD,Server:()=>md,listen:()=>ZD,openapi:()=>JD,url:()=>rc});var U={};me(U,{AdditionalSchemas:()=>Ds,isHttpApi:()=>aS,make:()=>pS,reflect:()=>Kc});var u={};me(u,{delete:()=>nS,get:()=>Zh,getErrorSchemas:()=>Pn,getPayloadSchemas:()=>Wh,getSuccessSchemas:()=>Hn,head:()=>oS,isHttpApiEndpoint:()=>Gh,make:()=>en,options:()=>sS,patch:()=>rS,post:()=>eS,put:()=>tS});var k={};me(k,{Accepted:()=>Ph,Created:()=>Hh,Empty:()=>va,MultipartStreamTypeId:()=>Nm,MultipartTypeId:()=>Um,NoContent:()=>jc,StreamSse:()=>Th,StreamUint8Array:()=>qh,asFormUrlEncoded:()=>$c,asJson:()=>Uh,asMultipart:()=>Oh,asMultipartStream:()=>Lh,asNoContent:()=>Je,asText:()=>Nh,asUint8Array:()=>_h,getPayloadEncoding:()=>Aa,getResponseEncoding:()=>fr,getStatusError:()=>kn,getStatusStream:()=>xn,getStatusSuccess:()=>Qt,getStreamMetadata:()=>Mh,isNoContent:()=>Zr,isStreamSchema:()=>Ze,isStreamSse:()=>Is,isStreamUint8Array:()=>Gc,status:()=>Mm});var kh={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511},As="~effect/httpapi/HttpApiSchema/Stream";function Mm(t){let e=typeof t=="string"?kh[t]:t;return r=>r.annotate({httpApiStatus:e})}i(Mm,"status");var va=i(t=>wc.pipe(Mm(t)),"Empty"),jc=va(204),Hh=va(201),Ph=va(202);function Je(t){return e=>wc.pipe(Oi(Zd(e),Md({decode:t.decode,encode:fd})))}i(Je,"asNoContent");var Om=bi(ss),Th=i(t=>{let e=t.events??(t.data===void 0?void 0:vn({id:tu(Nr),event:Nr,data:bh(t.data)}));if(e===void 0)throw new Error("StreamSse requires either an events schema or a data schema");return Ic(Om.ast,{[As]:As,_tag:"StreamSse",mode:"sse",sseMode:t.events===void 0?"data":"events",contentType:t.contentType??Lm("sse"),events:e,error:t.error??qi})},"StreamSse"),bh=i(t=>{let e=os(t.ast);return e===void 0?ps(t):ps(t).annotate({identifier:`${e}Stream`})},"sseDataJsonSchema"),qh=i(t=>Ic(Om.ast,{[As]:As,_tag:"StreamUint8Array",mode:"uint8array",contentType:t?.contentType??Lm("uint8array")}),"StreamUint8Array"),Ze=i(t=>Sn(t)&&St(t,As),"isStreamSchema"),Is=i(t=>Ze(t)&&t._tag==="StreamSse","isStreamSse"),Gc=i(t=>Ze(t)&&t._tag==="StreamUint8Array","isStreamUint8Array");function Mh(t){return t._tag==="StreamSse"?{mode:t.mode,sseMode:t.sseMode,contentType:t.contentType,events:t.events,error:t.error}:{mode:t.mode,contentType:t.contentType}}i(Mh,"getStreamMetadata");function Lm(t){switch(t){case"sse":return"text/event-stream";case"uint8array":return"application/octet-stream"}}i(Lm,"defaultStreamContentType");var Um="~effect/httpapi/HttpApiSchema/Multipart";function Oh(t){return e=>e.pipe(Dc(Um)).annotate({"~httpApiEncoding":{_tag:"Multipart",mode:"buffered",contentType:Wc("Multipart"),limits:t}})}i(Oh,"asMultipart");var Nm="~effect/httpapi/HttpApiSchema/MultipartStream";function Lh(t){return e=>e.pipe(Dc(Nm)).annotate({"~httpApiEncoding":{_tag:"Multipart",mode:"stream",contentType:Wc("Multipart"),limits:t}})}i(Lh,"asMultipartStream");function Ea(t,e){return t.annotate({"~httpApiEncoding":{_tag:e._tag,contentType:e.contentType??Wc(e._tag)}})}i(Ea,"asNonMultipartEncoding");function Wc(t){switch(t){case"Multipart":return"multipart/form-data";case"Json":return"application/json";case"FormUrlEncoded":return"application/x-www-form-urlencoded";case"Uint8Array":return"application/octet-stream";case"Text":return"text/plain"}}i(Wc,"defaultContentType");function Uh(t){return e=>Ea(e,{_tag:"Json",...t})}i(Uh,"asJson");function $c(t){return e=>Ea(e,{_tag:"FormUrlEncoded",...t})}i($c,"asFormUrlEncoded");function Nh(t){return e=>Ea(e,{_tag:"Text",...t})}i(Nh,"asText");function _h(t){return e=>Ea(e,{_tag:"Uint8Array",...t})}i(_h,"asUint8Array");var Zr=i(t=>{if(Ii(t))return!0;let e=hn(t);if(Ii(e))return!0;let r=t.encoding?.[0].to;return r===void 0?!1:Ii(r)},"isNoContent"),_m=Ec("~httpApiEncoding"),Bm=Ec("httpApiStatus"),Fm={_tag:"Json",contentType:"application/json"},Bh={_tag:"FormUrlEncoded",contentType:"application/x-www-form-urlencoded"};function Fh(t){return _m(t)??Fm}i(Fh,"getEncoding");function Aa(t,e){let r=_m(t);return r||(ao(e)?Fm:Bh)}i(Aa,"getPayloadEncoding");function fr(t){let e=Fh(t);if(e._tag==="Multipart")throw new Error("Multipart is not supported in response");return e}i(fr,"getResponseEncoding");function Qt(t){return Bm(t)??200}i(Qt,"getStatusSuccess");function xn(t){return Qt(t.ast)}i(xn,"getStatusStream");function kn(t){return Bm(t)??500}i(kn,"getStatusError");var zc="~effect/httpapi/HttpApiEndpoint",Gh=i(t=>St(t,zc),"isHttpApiEndpoint");function Wh(t){let e=[];for(let{schemas:r}of t.payload.values())e.push(...r);return e}i(Wh,"getPayloadSchemas");function Hn(t){let e=Array.from(t.success);return yi(e)?e:[jc]}i(Hn,"getSuccessSchemas");function Pn(t){let e=new Set(t.error);for(let r of t.middlewares){let n=r;for(let a of n.error)e.add(a)}return Array.from(e)}i(Pn,"getErrorSchemas");var $h={[zc]:zc,pipe(){return br(this,arguments)},prefix(t){return ws({...this,path:Eu(this.path,t)})},middleware(t){return ws({...this,middlewares:new Set([...this.middlewares,t])})},annotate(t,e){return ws({...this,annotations:Or(this.annotations,t,e)})},annotateMerge(t){return ws({...this,annotations:Ct(this.annotations,t)})}};function ws(t){return Object.assign(Object.create($h),t)}i(ws,"makeProto");var en=i(t=>(e,r,n)=>{let a=n?.disableCodecs??!1,c=a?gn:Ni;return ws({name:e,path:r,method:t,params:Vc(n?.params,c),query:Vc(n?.query,c),headers:Vc(n?.headers,c),payload:Vh(n?.payload,t,a),success:zh(n?.success,t,a),error:Qh(n?.error,a),annotations:Mr(),middlewares:new Set})},"make");function Vc(t,e){if(t!==void 0)return Sn(t)?e(t):e(vn(t))}i(Vc,"ensureStruct");function Vh(t,e,r){let n=new Map;if(t===void 0)return n;let a=Array.isArray(t)?t:Sn(t)?[t]:[vn(t).pipe($c())],c=r?gn:Jh;for(let p of a){let f=Aa(p.ast,e),l=n.get(f.contentType);if(l){if(l.encoding._tag!==f._tag)throw new Error(`Multiple payload encodings for content-type: ${f.contentType}`);if(l.encoding._tag==="Multipart")throw new Error(`Multiple multipart payloads for content-type: ${f.contentType}`);l.schemas.push(c(p,e))}else n.set(f.contentType,{encoding:f,schemas:[c(p,e)]})}return n}i(Vh,"getPayload");var Gm="effect/httpapi/stream/failure";function zh(t,e,r){if(t===void 0)return new Set;let n=ic(t);return Yh(n,e),new Set(r?n:n.map(a=>Ze(a)?a:Wm(a)))}i(zh,"getSuccessResponse");function Qh(t,e){if(t===void 0)return new Set;let r=ic(t);for(let n of r)if(Ze(n))throw new Error("Streaming schemas are not supported in error responses");return new Set(e?r:r.map(Wm))}i(Qh,"getErrorResponse");function Yh(t,e){let r=new Map;for(let n of t)if(Ze(n)){Kh(n,e);let a=xn(n),c=jm(r,a);if(c.stream!==void 0)throw new Error(`Multiple streaming success responses for status: ${a}`);if(c.noContent)throw new Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(c.bufferedContentTypes.has(Ia(n.contentType)))throw new Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${n.contentType}`);r.set(a,{...c,stream:n})}else{let a=Qt(n.ast),c=jm(r,a),p=Zr(n.ast);if(c.stream!==void 0){if(p)throw new Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let f=fr(n.ast);if(Ia(f.contentType)===Ia(c.stream.contentType))throw new Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${f.contentType}`)}p||c.bufferedContentTypes.add(Ia(fr(n.ast).contentType)),c.noContent=c.noContent||p}}i(Yh,"validateSuccessResponse");function Ia(t){let e=t.toLowerCase().trim(),r=e.indexOf(";");return r===-1?e:e.slice(0,r).trim()}i(Ia,"normalizeResponseContentType");function jm(t,e){let r=t.get(e);return r===void 0&&(r={bufferedContentTypes:new Set,noContent:!1},t.set(e,r)),r}i(jm,"getStatusEntry");function Kh(t,e){if(e==="HEAD")throw new Error("HEAD endpoints cannot declare streaming success responses");if(Is(t)&&Xh(t.events.ast))throw new Error(`SSE event name is reserved: ${Gm}`)}i(Kh,"validateStreamSuccess");function Xh(t){return Qc(hn(t),new Set)}i(Xh,"hasReservedSseEventName");function Qc(t,e){if(e.has(t))return!1;if(e.add(t),hc(t))return t.types.some(n=>Qc(n,e));if(Sc(t))return Qc(t.thunk(),e);if(!wi(t))return!1;let r=t.propertySignatures.find(n=>n.name==="event");return r!==void 0&&wa(r.type,e)}i(Qc,"hasReservedEventName");function wa(t,e){if(e.has(t))return!1;e.add(t);let r=hn(t);return r!==t?wa(r,e):Ud(t)?t.literal===Gm:hc(t)?t.types.some(n=>wa(n,e)):Sc(t)?wa(t.thunk(),e):!1}i(wa,"hasReservedEventLiteral");function Wm(t){switch(fr(t.ast)._tag){case"Json":return En(t);case"FormUrlEncoded":return Ni(t);case"Text":case"Uint8Array":return t}}i(Wm,"transformResponse");function Jh(t,e){switch(Aa(t.ast,e)._tag){case"Json":return En(t);case"FormUrlEncoded":return Ni(t);case"Text":case"Uint8Array":case"Multipart":return t}}i(Jh,"transformPayload");var Zh=en("GET"),eS=en("POST"),tS=en("PUT"),rS=en("PATCH"),nS=en("DELETE");var oS=en("HEAD"),sS=en("OPTIONS");var Yc="~effect/httpapi/HttpApi",aS=i(t=>St(t,Yc),"isHttpApi"),cS={[Yc]:Yc,pipe(){return br(this,arguments)},add(...t){let e={...this.groups};for(let r of t)e[r.identifier]=r;return Tn({identifier:this.identifier,groups:e,annotations:this.annotations})},addHttpApi(t){let e={...this.groups};for(let r in t.groups){let n=t.groups[r];n.annotations=Ct(t.annotations,n.annotations),e[r]=n}return Tn({identifier:this.identifier,groups:e,annotations:this.annotations})},prefix(t){return Tn({identifier:this.identifier,groups:qr(this.groups,e=>e.prefix(t)),annotations:this.annotations})},middleware(t){return Tn({identifier:this.identifier,groups:qr(this.groups,e=>e.middleware(t)),annotations:this.annotations})},annotate(t,e){return Tn({identifier:this.identifier,groups:this.groups,annotations:Or(this.annotations,t,e)})},annotateMerge(t){return Tn({identifier:this.identifier,groups:this.groups,annotations:Ct(this.annotations,t)})}},Tn=i(t=>{function e(){}return i(e,"HttpApi"),Object.setPrototypeOf(e,cS),e.groups=t.groups,e.annotations=t.annotations,e},"makeProto"),pS=i(t=>Tn({identifier:t,groups:new Map,annotations:Mr()}),"make"),Kc=i((t,e)=>{let r=Object.values(t.groups);for(let n of r){let a=Ct(t.annotations,n.annotations);e.onGroup({group:n,mergedAnnotations:a});let c=Object.values(n.endpoints);for(let p of c)e.predicate&&!e.predicate({endpoint:p,group:n})||e.onEndpoint({group:n,endpoint:p,middleware:p.middlewares,mergedAnnotations:Ct(a,p.annotations),successes:$m(Hn(p),Qt),errors:$m(Pn(p),kn)})}},"reflect"),$m=i((t,e)=>{let r=new Map;return t.forEach(n),r;function n(a){if(Ze(a))return;let c=a.ast,p=e(c),f=r.get(p);f===void 0?r.set(p,[a]):f.push(a)}i(n,"add")},"extractResponseContent"),Ds=class extends Te()("effect/httpapi/HttpApi/AdditionalSchemas"){static{i(this,"AdditionalSchemas")}};var x={};me(x,{HandlersTypeId:()=>rl,endpoint:()=>$S,group:()=>WS,handlerToRoute:()=>sl,layer:()=>GS,securityDecode:()=>nl,securitySetCookie:()=>VS});var D={};me(D,{BadRequest:()=>Rs,BadRequestNoContent:()=>AS,Conflict:()=>bs,ConflictNoContent:()=>kS,Forbidden:()=>xs,ForbiddenNoContent:()=>wS,Gone:()=>qs,GoneNoContent:()=>HS,HttpApiSchemaError:()=>ct,HttpApiSchemaErrorTypeId:()=>Da,InternalServerError:()=>Ms,InternalServerErrorNoContent:()=>PS,MethodNotAllowed:()=>Hs,MethodNotAllowedNoContent:()=>RS,NotAcceptable:()=>Ps,NotAcceptableNoContent:()=>CS,NotFound:()=>ks,NotFoundNoContent:()=>DS,NotImplemented:()=>Os,NotImplementedNoContent:()=>TS,RequestTimeout:()=>Ts,RequestTimeoutNoContent:()=>xS,ServiceUnavailable:()=>Ls,ServiceUnavailableNoContent:()=>bS,Unauthorized:()=>Cs,UnauthorizedNoContent:()=>IS});var Vm=Be({status:400}),dS=Be({status:401}),uS=Be({status:403}),mS=Be({status:404}),lS=Be({status:405}),fS=Be({status:406}),yS=Be({status:408}),gS=Be({status:409}),hS=Be({status:410}),SS=Be({status:500}),vS=Be({status:501}),ES=Be({status:503}),Rs=class t extends ot("effect/HttpApiError/BadRequest")({_tag:nt("BadRequest")},{description:"BadRequest",httpApiStatus:400}){static{i(this,"BadRequest")}[jt]=!0;[Qe](){return re(Vm)}static singleton=new t},AS=Rs.pipe(Je({decode:i(()=>new Rs({}),"decode")})),Cs=class extends ot("effect/HttpApiError/Unauthorized")({_tag:nt("Unauthorized")},{description:"Unauthorized",httpApiStatus:401}){static{i(this,"Unauthorized")}[jt]=!0;[Qe](){return re(dS)}},IS=Cs.pipe(Je({decode:i(()=>new Cs({}),"decode")})),xs=class extends ot("effect/HttpApiError/Forbidden")({_tag:nt("Forbidden")},{description:"Forbidden",httpApiStatus:403}){static{i(this,"Forbidden")}[jt]=!0;[Qe](){return re(uS)}},wS=xs.pipe(Je({decode:i(()=>new xs({}),"decode")})),ks=class extends ot("effect/HttpApiError/NotFound")({_tag:nt("NotFound")},{description:"NotFound",httpApiStatus:404}){static{i(this,"NotFound")}[jt]=!0;[Qe](){return re(mS)}},DS=ks.pipe(Je({decode:i(()=>new ks({}),"decode")})),Hs=class extends ot("effect/HttpApiError/MethodNotAllowed")({_tag:nt("MethodNotAllowed")},{description:"MethodNotAllowed",httpApiStatus:405}){static{i(this,"MethodNotAllowed")}[jt]=!0;[Qe](){return re(lS)}},RS=Hs.pipe(Je({decode:i(()=>new Hs({}),"decode")})),Ps=class extends ot("effect/HttpApiError/NotAcceptable")({_tag:nt("NotAcceptable")},{description:"NotAcceptable",httpApiStatus:406}){static{i(this,"NotAcceptable")}[jt]=!0;[Qe](){return re(fS)}},CS=Ps.pipe(Je({decode:i(()=>new Ps({}),"decode")})),Ts=class extends ot("effect/HttpApiError/RequestTimeout")({_tag:nt("RequestTimeout")},{description:"RequestTimeout",httpApiStatus:408}){static{i(this,"RequestTimeout")}[jt]=!0;[Qe](){return re(yS)}},xS=Ts.pipe(Je({decode:i(()=>new Ts({}),"decode")})),bs=class extends ot("effect/HttpApiError/Conflict")({_tag:nt("Conflict")},{description:"Conflict",httpApiStatus:409}){static{i(this,"Conflict")}[jt]=!0;[Qe](){return re(gS)}},kS=bs.pipe(Je({decode:i(()=>new bs({}),"decode")})),qs=class extends ot("effect/HttpApiError/Gone")({_tag:nt("Gone")},{description:"Gone",httpApiStatus:410}){static{i(this,"Gone")}[jt]=!0;[Qe](){return re(hS)}},HS=qs.pipe(Je({decode:i(()=>new qs({}),"decode")})),Ms=class extends ot("effect/HttpApiError/InternalServerError")({_tag:nt("InternalServerError")},{description:"InternalServerError",httpApiStatus:500}){static{i(this,"InternalServerError")}[Qe](){return re(SS)}},PS=Ms.pipe(Je({decode:i(()=>new Ms({}),"decode")})),Os=class extends ot("effect/HttpApiError/NotImplemented")({_tag:nt("NotImplemented")},{description:"NotImplemented",httpApiStatus:501}){static{i(this,"NotImplemented")}[Qe](){return re(vS)}},TS=Os.pipe(Je({decode:i(()=>new Os({}),"decode")})),Ls=class extends ot("effect/HttpApiError/ServiceUnavailable")({_tag:nt("ServiceUnavailable")},{description:"ServiceUnavailable",httpApiStatus:503}){static{i(this,"ServiceUnavailable")}[Qe](){return re(ES)}},bS=Ls.pipe(Je({decode:i(()=>new Ls({}),"decode")})),Da="~effect/httpapi/HttpApiError/HttpApiSchemaError",ct=class t extends wd("HttpApiSchemaError"){static{i(this,"HttpApiSchemaError")}[Da]=Da;static is(e){return St(e,Da)}static wrap(e,r){return Cd(r,n=>new t({kind:e,cause:n}))}name="HttpApiSchemaError";message=this.kind;[Qe](){return re(Vm)}};var ye={};me(ye,{Service:()=>qS,isSecurity:()=>Us,layerClient:()=>LS,layerSchemaErrorTransform:()=>OS});var zm="~effect/httpapi/HttpApiMiddleware",Xc="~effect/httpapi/HttpApiMiddleware/Security",Us=i(t=>St(t,Xc),"isSecurity"),qS=i(()=>(t,e)=>{let r=globalThis.Error,n=r.stackTraceLimit;r.stackTraceLimit=2;let a=new r;r.stackTraceLimit=n;class c extends Te()(t){static{i(this,"Service")}}let p=c;if(Object.defineProperty(c,"stack",{get(){return a.stack}}),p[zm]=zm,p.error=MS(e?.error),p.requiredForClient=e?.requiredForClient??!1,e?.security!==void 0){if(Object.keys(e.security).length===0)throw new Error("HttpApiMiddleware.Service: security object must not be empty");p[Xc]=Xc,p.security=e.security}return p},"Service");function MS(t){return t===void 0?new Set:new Set(Array.isArray(t)?t:[t])}i(MS,"getError");var OS=i((t,e)=>Id(t,(r,n)=>Ai(r,a=>ct.is(a)?e(a,n):no(a))),"layerSchemaErrorTransform"),LS=i((t,e)=>vi(es(function*(){let r=(yield*rs()).pipe(Jo(Zo)),n=Ei(e)?yield*e:e;return gi(new Map([[`${t.key}/Client`,a=>Hd(n(a),c=>Ct(r,c))]]))})),"layerClient");var d={};me(d,{Deprecated:()=>Gs,Description:()=>tn,Exclude:()=>Ra,ExternalDocs:()=>Do,Format:()=>js,Identifier:()=>Ns,License:()=>Bs,Override:()=>qn,Servers:()=>Fs,Summary:()=>Ro,Title:()=>bn,Transform:()=>Mn,Version:()=>_s,annotations:()=>_S,fromApi:()=>Jc});var Ns=class extends Te()("effect/httpapi/OpenApi/Identifier"){static{i(this,"Identifier")}},bn=class extends Te()("effect/httpapi/OpenApi/Title"){static{i(this,"Title")}},_s=class extends Te()("effect/httpapi/OpenApi/Version"){static{i(this,"Version")}},tn=class extends Te()("effect/httpapi/OpenApi/Description"){static{i(this,"Description")}},Bs=class extends Te()("effect/httpapi/OpenApi/License"){static{i(this,"License")}},Do=class extends Te()("effect/httpapi/OpenApi/ExternalDocs"){static{i(this,"ExternalDocs")}},Fs=class extends Te()("effect/httpapi/OpenApi/Servers"){static{i(this,"Servers")}},js=class extends Te()("effect/httpapi/OpenApi/Format"){static{i(this,"Format")}},Ro=class extends Te()("effect/httpapi/OpenApi/Summary"){static{i(this,"Summary")}},Gs=class extends Te()("effect/httpapi/OpenApi/Deprecated"){static{i(this,"Deprecated")}},qn=class extends Te()("effect/httpapi/OpenApi/Override"){static{i(this,"Override")}},Ra=Ad("effect/httpapi/OpenApi/Exclude",{defaultValue:ld}),Mn=class extends Te()("effect/httpapi/OpenApi/Transform"){static{i(this,"Transform")}},NS=i(t=>{let e=Object.entries(t);return r=>{let n=Mr();for(let[a,c]of e)r[a]!==void 0&&(n=Or(n,c,r[a]));return n}},"servicesPartial"),_S=NS({identifier:Ns,title:bn,version:_s,description:tn,license:Bs,summary:Ro,deprecated:Gs,externalDocs:Do,servers:Fs,format:js,override:qn,exclude:Ra,transform:Mn}),Qm=new WeakMap;function we(t,e,r){let n=cc(t,e);yd(n)&&r(n.value)}i(we,"processAnnotation");function Jc(t){let e=Qm.get(t);if(e!==void 0)return e;let r={openapi:"3.1.0",info:{title:"Api",version:"0.0.1"},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]},n=[];we(t.annotations,bn,c=>{r.info.title=c}),we(t.annotations,_s,c=>{r.info.version=c}),we(t.annotations,tn,c=>{r.info.description=c}),we(t.annotations,Bs,c=>{r.info.license=c}),we(t.annotations,Ro,c=>{r.info.summary=c}),we(t.annotations,Fs,c=>{r.servers=[...c]}),Kc(t,{onGroup({group:c}){if(ac(c.annotations,Ra))return;let p={name:hi(c.annotations,bn,()=>c.identifier)};we(c.annotations,tn,f=>{p.description=f}),we(c.annotations,Do,f=>{p.externalDocs=f}),we(c.annotations,qn,f=>{Object.assign(p,f)}),we(c.annotations,Mn,f=>{p=f(p)}),r.tags.push(p)},onEndpoint({endpoint:c,group:p,mergedAnnotations:f,middleware:l}){if(ac(f,Ra))return;let m={tags:[hi(p.annotations,bn,()=>p.identifier)],operationId:hi(c.annotations,Ns,()=>p.topLevel?c.name:`${p.identifier}.${c.name}`),parameters:[],security:[],responses:{}},y=c.path.replace(/:(\w+)\??/g,"{$1}"),g=c.method.toLowerCase();function E(R){if(R.size>0){let b={},M=!1;R.forEach(({encoding:Z,schemas:Se},De)=>{let ar=Se.filter(ke=>!Zr(ke.ast));if(ar.length===0)return;M=!0;let F=ar.map(so),ue=F.length===1?F[0]:new vc(F,"anyOf");n.push({_tag:"schema",ast:Ym(ue,Z._tag),path:["paths",y,g,"requestBody","content",De,"schema"]}),b[De]={schema:{}}}),M&&(m.requestBody={content:b,required:!0})}}i(E,"processRequestBodies");function v(R,b){for(let[M,{content:Z,descriptions:Se,streamContent:De}]of R){let ar=Se.size>0?Array.from(Se).join(" | "):b();m.responses[M]={description:ar},Z!==void 0&&Z.forEach((F,ue)=>{F.forEach((ke,ne)=>{let Ve=Array.from(ke,so),nc=Ve.length===1?Ve[0]:new vc(Ve,"anyOf");n.push({_tag:"schema",ast:Ym(nc,ue),path:["paths",y,g,"responses",String(M),"content",ne,"schema"]}),m.responses[M].content??={},m.responses[M].content[ne]={schema:{}}})}),De!==void 0&&De.forEach((F,ue)=>{m.responses[M].content??={},Is(F)?(n.push({_tag:"schema",ast:so(F.events),path:["paths",y,g,"responses",String(M),"content",ue,"schema"]}),n.push({_tag:"schema",ast:so(En(Li(F.error,Ui()))),path:["paths",y,g,"responses",String(M),"content",ue,"x-effect-stream","causeSchema"]}),n.push({_tag:"schema",ast:so(F.error),path:["paths",y,g,"responses",String(M),"content",ue,"x-effect-stream","errorSchema"]}),m.responses[M].content[ue]={schema:{},"x-effect-stream":{encoding:"sse",causeSchema:{},errorSchema:{},failureEvent:BS}}):m.responses[M].content[ue]={schema:{type:"string",format:"binary"},"x-effect-stream":{encoding:"uint8array"}}})}}i(v,"processResponseBodies");function h(R,b){if(R){let M=Nd(R.ast);if(wi(M))for(let Z of M.propertySignatures)m.parameters.push({name:String(Z.name),in:b,schema:{},required:b==="path"||!_d(Z.type)}),n.push({_tag:"parameter",ast:Z.type,path:["paths",y,g,"parameters",String(m.parameters.length-1),"schema"]})}}i(h,"processParameters"),we(c.annotations,tn,R=>{m.description=R}),we(c.annotations,Ro,R=>{m.summary=R}),we(c.annotations,Gs,R=>{m.deprecated=R}),we(c.annotations,Do,R=>{m.externalDocs=R}),l.forEach(R=>{if(Us(R))for(let[b,M]of Object.entries(R.security))w(b,M),m.security.push({[b]:[]})});function w(R,b){r.components.securitySchemes[R]===void 0&&(r.components.securitySchemes[R]=jS(b))}i(w,"processHttpApiSecurity");let C=ao(c.method);if(C&&E(c.payload),h(c.params,"path"),!C&&c.payload.size===1){let R=c.payload.values().next().value;h(R.schemas[0],"query")}h(c.headers,"header"),h(c.query,"query"),v(FS(c),()=>"Success"),v(Km(Pn(c),kn,Xm),()=>"Error"),r.paths[y]||(r.paths[y]={}),we(c.annotations,qn,R=>{Object.assign(m,R)}),we(c.annotations,Mn,R=>{m=R(m)}),r.paths[y][g]=m}}),we(t.annotations,Ds,c=>{c.forEach(p=>{let f=os(p.ast);if(f!==void 0){if(f in r.components.schemas)throw new globalThis.Error(`Duplicate component schema identifier: ${f}`);r.components.schemas[f]={},n.push({_tag:"schema",ast:p.ast,path:["components","schemas",f]})}})});function a(c){return"/"+c.map(Qd).join("/")}if(i(a,"escapePath"),yi(n)){let c=Iu(Ed(n,l=>l.ast)),p=Xd(wu(c)),f=n.map((l,m)=>{let y=a(l.path),g=p.schemas[m];return{op:"replace",path:y,value:g}});Object.entries(p.definitions).forEach(([l,m])=>{f.push({op:"add",path:a(["components","schemas",l]),value:m})}),r=Kd(f,r)}return Object.keys(r.components.schemas).forEach(c=>{if(!Jd.test(c))throw new globalThis.Error(`Invalid component schema key: ${c}`)}),we(t.annotations,qn,c=>{Object.assign(r,c)}),we(t.annotations,Mn,c=>{r=c(r)}),Qm.set(t,r),r}i(Jc,"fromApi");var BS="effect/httpapi/stream/failure";function FS(t){return Km(Hn(t),Qt,Xm)}i(FS,"extractSuccessResponseBodies");function Km(t,e,r){let n=new Map;return t.forEach(a),n;function a(l){if(Ze(l)){f(l);return}let m=l.ast,y=e(m);Zr(m)?c(y,r(l.ast)??"<No Content>"):p(l,y,fr(m))}i(a,"process");function c(l,m){let y=n.get(l);y===void 0?n.set(l,{descriptions:new Set([m]),content:void 0,streamContent:void 0}):m!==void 0&&y.descriptions.add(m)}i(c,"addNoContent");function p(l,m,y){let g=r(l.ast),E=n.get(m),{_tag:v,contentType:h}=y;if(E===void 0)n.set(m,{descriptions:new Set(g!==void 0?[g]:[]),content:new Map([[v,new Map([[h,new Set([l])]])]]),streamContent:void 0});else if(g!==void 0&&E.descriptions.add(g),E.content===void 0)E.content=new Map([[v,new Map([[h,new Set([l])]])]]);else{let w=E.content.get(v);if(w===void 0)E.content.set(v,new Map([[h,new Set([l])]]));else{let C=w.get(h);C===void 0?w.set(h,new Set([l])):C.add(l)}}}i(p,"addContent");function f(l){let m=xn(l),y=n.get(m);y===void 0?n.set(m,{descriptions:new Set,content:void 0,streamContent:new Map([[l.contentType,l]])}):y.streamContent===void 0?y.streamContent=new Map([[l.contentType,l]]):y.streamContent.set(l.contentType,l)}i(f,"addStreamContent")}i(Km,"extractResponseBodies");function Xm(t){return Bd(t)??os(t)}i(Xm,"resolveDescriptionOrIdentifier");var Jm=Nr.annotate({format:"binary"});function Ym(t,e){switch(e){case"Uint8Array":return Jm.ast;case"Text":return Nr.ast;case"FormUrlEncoded":case"Json":return t;case"Multipart":return Zm(t)}}i(Ym,"toEncodingAST");function Zm(t){return Od(t)&&t.annotations?.typeConstructor?._tag==="effect/http/PersistedFile"?Jm.ast:typeof t?.recur=="function"?t.recur(Zm):t}i(Zm,"persistedFileToBinaryEncoding");var jS=i(t=>{let e={};switch(we(t.annotations,tn,r=>{e.description=r}),t._tag){case"Basic":return{...e,type:"http",scheme:"basic"};case"Http":{let r=cc(t.annotations,js).pipe(hd(n=>({bearerFormat:n})),gd);return{...e,type:"http",scheme:t.scheme,...r}}case"ApiKey":return{...e,type:"apiKey",name:t.key,in:t.in}}},"makeSecurityScheme");var GS=i((t,e)=>Su(fc(function*(r){let n=yield*rs(),a=[],c=Array.from(n.mapUnsafe.keys()).filter(p=>p.startsWith("effect/httpapi/HttpApiGroup/"));for(let p of Object.values(t.groups)){let f=n.mapUnsafe.get(p.key)?.routes;if(f===void 0){let l=c.length===0?"none":c.join(", ");return yield*dc(`HttpApiGroup "${p.identifier}" not found (key: "${p.key}"). Did you forget to provide HttpApiBuilder.group(api, "${p.identifier}", ...)? Available groups: ${l}`)}a.push(...f)}if(yield*r.addAll(a),e?.openapiPath){let p=Jc(t);yield*r.add("GET",e.openapiPath,re(Gi(p)))}})),"layer"),WS=i((t,e,r)=>vi(es(function*(){let n=(yield*rs()).pipe(Jo(Zo)),a=t.groups[e],c=r(YS(a)),p=Ei(c)?yield*c:c,f=[];for(let l of p.handlers.values())f.push(sl(a,l,n));return gi(new Map([[a.key,{routes:f,handlers:p.handlers}]]))})),"group"),rl=Symbol.for("@effect/platform/HttpApiBuilder/Handlers"),$S=i((t,e,r,n)=>kd(a=>{let c=t.groups[e],p=c.endpoints[r];return re(ol(c,p,Jo(Zo)(a),n,!1))}),"endpoint"),nl=i(t=>{switch(t._tag){case"Http":return ts(Wi,e=>oo((e.headers.authorization??"").slice(t.schemeLength+1)));case"ApiKey":{let e=t.in==="header"?t.key.toLowerCase():t.key,r=vn({[e]:Nr}),n=t.in==="query"?fu(r):t.in==="cookie"?mu(r):lu(r);return mc(n,{onFailure:i(()=>oo(""),"onFailure"),onSuccess:i(a=>oo(a[e]),"onSuccess")})}case"Basic":{let e={username:"",password:oo("")};return Wi.pipe(pr(r=>uc(Pd((r.headers.authorization??"").slice(zS)))),mc({onFailure:i(()=>e,"onFailure"),onSuccess:i(r=>{let n=r.split(":");return n.length!==2?e:{username:n[0],password:oo(n[1])}},"onSuccess")}))}}},"securityDecode"),VS=i((t,e,r)=>gu((n,a)=>Bt(iu(a,t.key,Td(e),{secure:!0,httpOnly:!0,...r}))),"securitySetCookie"),zS=6,QS={[rl]:{_Endpoints:gn},pipe(){return br(this,arguments)},handle(t,e,r){let n=this.group.endpoints[t];return this.handlers.set(t,{endpoint:n,handler:e,isRaw:!1,uninterruptible:r?.uninterruptible??!1}),this},handleRaw(t,e,r){let n=this.group.endpoints[t];return this.handlers.set(t,{endpoint:n,handler:e,isRaw:!0,uninterruptible:r?.uninterruptible??!1}),this}},YS=i(t=>{let e=Object.create(QS);return e.group=t,e.handlers=new Map,e},"makeHandlers");function KS(t){let e=new Map;return t.forEach(({encoding:r,schemas:n},a)=>{let c=as(Mi(n));r._tag==="Multipart"?e.set(a,{_tag:"Multipart",mode:r.mode,limits:r.limits,decode:c}):e.set(a,{_tag:r._tag,decode:c,nullOnEmpty:n.some(p=>Ld(hn(p.ast)))})}),e}i(KS,"buildPayloadDecoders");function XS(t,e,r){let n=ao(e.method),a=n?ZS(e):"application/x-www-form-urlencoded",c=t.get(a);if(!c)return ji(`Unsupported content-type: ${a}`,{status:415});let{_tag:p,decode:f}=c;switch(p){case"Multipart":{if(c.mode==="buffered"){let m=Bt(e.multipart);return c.limits&&(m=lc(m,kc(c.limits))),pr(m,f)}return re(c.limits?Pi(e.multipartStream,kc(c.limits)):e.multipartStream)}case"Json":let l=Bt(pr(e.text,m=>m===""?c.nullOnEmpty?re(null):Dd:re(JSON.parse(m))));return pr(l,f);case"Text":return pr(Bt(e.text),f);case"FormUrlEncoded":{let m=n?ts(Bt(e.urlParamsBody),ru):re(r);return pr(m,f)}case"Uint8Array":return pr(ts(Bt(e.arrayBuffer),m=>new Uint8Array(m)),f)}}i(XS,"decodePayload");function ol(t,e,r,n,a){let c=cs(fv(e)),p=cs(yv(e)),f=Ti(e.params,as),l=Ti(e.headers,as),m=Ti(e.query,as),y=nv(e),E=e.payload.size>0&&!a?KS(e.payload):void 0;return ev(t,e,r,es(function*(){let h=Fd().context,w=Xo(h,Wi),C=Xo(h,hu),R=Xo(h,uu),b={request:w,endpoint:e,group:t};if(f&&(b.params=yield*ct.wrap("Params",f(C.params))),l&&(b.headers=yield*ct.wrap("Headers",l(w.headers))),m&&(b.query=yield*ct.wrap("Query",m(R))),E){let Se=XS(E,w,R);if(Fi(Se))return Se;Se!==void 0&&(b.payload=yield*ct.wrap("Payload",Se))}let M=yield*n(b);if(Fi(M))return M;let Z=y?.(M,h);return Z!==void 0?yield*ct.wrap("Body",Z):yield*ct.wrap("Body",c(M))})).pipe(xd,Ai(v=>ct.is(v)?dc(v):Bt(p(v))),lc(r))}i(ol,"handlerToHttpEffect");function sl(t,e,r){let n=e.endpoint;return vu(n.method,n.path,ol(t,n,r,e.handler,e.isRaw),{uninterruptible:e.uninterruptible})}i(sl,"handlerToRoute");var JS=i(t=>t.headers["content-type"]?t.headers["content-type"].toLowerCase().trim():"application/json","getRequestContentType"),ZS=i(t=>{let e=JS(t),r=e.indexOf(";");return r===-1?e:e.slice(0,r).trim()},"getRequestMediaType"),ev=i((t,e,r,n)=>{let a={group:t,endpoint:e};for(let c of e.middlewares){let p=c,f=Xo(r,p);n=(Us(p)?tv(p,f):f)(n,a)}return n},"applyMiddleware"),el=new WeakMap,tv=i((t,e)=>{let r=el.get(e);if(r!==void 0)return r;let n=Object.entries(t.security).map(([c,p])=>({decode:nl(p),middleware:e[c]}));if(n.length===0)return gn;let a=fc(function*(c,p){let f;for(let l=0;l<n.length;l++){let{decode:m,middleware:y}=n[l],g=yield*Rd(pr(m,E=>y(c,{credential:E,endpoint:p.endpoint,group:p.group})));if(Sd(g)){f=g;continue}return g.success}return yield*uc(f)});return el.set(e,a),a},"makeSecurityMiddleware"),rv=bi(Fi);function nv(t){let e=ov(t);if(e===void 0)return;let r=sv(t),n=xn(e),a=e.contentType;if(Gc(e))return(p,f)=>ss(p)?re(Rc(Pi(p,f),{status:n,contentType:a})):r?void 0:tl(p);let c=iv(e);return(p,f)=>ss(p)?re(Rc(Pi(av(p,c),f),{status:n,contentType:a})):r?void 0:tl(p)}i(nv,"makeStreamEncoder");function ov(t){for(let e of t.success)if(Ze(e))return e}i(ov,"getStreamSuccessSchema");function sv(t){for(let e of t.success)if(Sn(e)&&!Ze(e))return!0;return t.success.size===0}i(sv,"hasBufferedSuccess");function tl(t){return no(uv(new yc(fi(t),{message:"Expected a streaming response"})))}i(tl,"expectedStreamResponse");function iv(t){let e=En(Li(t.error,Ui()));return{sseMode:t.sseMode,encodeEvents:cs(eu(t.events)),encodeCause:cs(ps(e))}}i(iv,"makeSseEncoder");function av(t,e){return t.pipe(e.sseMode==="data"?Ft(r=>({id:void 0,event:"message",data:r})):gn,Wd(r=>Bt(e.encodeEvents(r))),Vd(r=>jd(cv(r,e))),Ft(dv),Ur)}i(av,"encodeSseStream");function cv(t,e){return e.encodeCause(t).pipe(Bt,ts(r=>({id:void 0,event:pv,data:r})))}i(cv,"encodeFailureEvent");var pv="effect/httpapi/stream/failure";function dv(t){return Ou.write({_tag:"Event",event:t.event,id:t.id,data:t.data})}i(dv,"renderSseEvent");function uv(t){return new Yd(t)}i(uv,"makeSchemaError");var mv=il(Qt),lv=il(kn);function fv(t){let e=Hn(t).map(mv);return e.length===1?e[0]:Mi(e)}i(fv,"makeSuccessSchema");function yv(t){let e=Pn(t).map(lv);return e.length===0?qi:e.length===1?e[0]:Mi(e)}i(yv,"makeErrorSchema");function il(t){let e=new WeakMap;return r=>{let n=e.get(r.ast);if(n!==void 0)return n;let a=rv.pipe(Oi(r,gv(t,r)));return e.set(a.ast,a),a}}i(il,"toResponseSchema");function gv(t,e){let r=e.ast,n=hv(t(r),fr(r),Zr(r));return qd({decode:i(a=>no(new bd(fi(a),{message:"Encode only schema"})),"decode"),encode:n})}i(gv,"getResponseTransformation");function hv(t,e,r){switch(e._tag){case"Json":return n=>{if(n===void 0||r)return re(Be({status:t}));try{let a=JSON.stringify(n);return re(ji(a,{status:t,contentType:e.contentType}))}catch(a){return no(new yc(fi(n),{message:globalThis.String(a)}))}};case"Text":return n=>re(ji(n,{status:t,contentType:e.contentType}));case"Uint8Array":return n=>re(nu(n,{status:t,contentType:e.contentType}));case"FormUrlEncoded":return n=>re(ou(n,{status:t}).pipe(su("content-type",e.contentType)))}}i(hv,"getResponseEncode");var H={};me(H,{isHttpApiGroup:()=>Sv,make:()=>Ev});var ep="~effect/httpapi/HttpApiGroup",Sv=i(t=>St(t,ep),"isHttpApiGroup"),vv={[ep]:ep,add(...t){let e={...this.endpoints};for(let r of t)e[r.name]=r;return rn({identifier:this.identifier,topLevel:this.topLevel,endpoints:e,annotations:this.annotations})},prefix(t){return rn({identifier:this.identifier,topLevel:this.topLevel,endpoints:qr(this.endpoints,e=>e.prefix(t)),annotations:this.annotations})},middleware(t){return rn({identifier:this.identifier,topLevel:this.topLevel,endpoints:qr(this.endpoints,e=>e.middleware(t)),annotations:this.annotations})},annotateMerge(t){return rn({identifier:this.identifier,topLevel:this.topLevel,endpoints:this.endpoints,annotations:Ct(this.annotations,t)})},annotate(t,e){return rn({identifier:this.identifier,topLevel:this.topLevel,endpoints:this.endpoints,annotations:Or(this.annotations,t,e)})},annotateEndpointsMerge(t){return rn({identifier:this.identifier,topLevel:this.topLevel,endpoints:qr(this.endpoints,e=>e.annotateMerge(t)),annotations:this.annotations})},annotateEndpoints(t,e){return rn({identifier:this.identifier,topLevel:this.topLevel,endpoints:qr(this.endpoints,r=>r.annotate(t,e)),annotations:this.annotations})},pipe(){return br(this,arguments)}},rn=i(t=>{function e(){}return i(e,"HttpApiGroup"),Object.setPrototypeOf(e,vv),e.key=`effect/httpapi/HttpApiGroup/${t.identifier}`,Object.assign(e,t)},"makeProto"),Ev=i((t,e)=>rn({identifier:t,topLevel:e?.topLevel??!1,endpoints:vd(),annotations:Mr()}),"make");import{createServer as KD}from"node:http";var ko={};me(ko,{MDNS:()=>ko,publish:()=>cE,unpublish:()=>jl});var Fl=oc(Bl(),1);var rr,Ua;function cE(t,e){if(Ua!==t){rr&&jl();try{let r=e??"opencode.local",n=`opencode-${t}`;rr=new Fl.Bonjour,rr.publish({name:n,type:"http",host:r,port:t,txt:{path:"/"}}).on("error",()=>{}),Ua=t}catch{if(rr)try{rr.destroy()}catch{}rr=void 0,Ua=void 0}}}i(cE,"publish");function jl(){if(rr){try{rr.unpublishAll(),rr.destroy()}catch{}rr=void 0,Ua=void 0}}i(jl,"unpublish");var fn={};me(fn,{HttpApiApp:()=>fn,context:()=>OD,createRoutes:()=>dh,routes:()=>uh,webHandler:()=>YD});var zs={};me(zs,{PluginPtyEnvironment:()=>zs,layer:()=>dE});var nr={};me(nr,{PtyEnvironment:()=>nr,Service:()=>Ho,layer:()=>Gl,node:()=>pE});var Ho=class extends oe.Service()("@opencode/ServerPtyEnvironment"){static{i(this,"Service")}},Gl=P.succeed(Ho,Ho.of({get:i(()=>s.succeed({}),"get")})),pE=Br({service:Ho,layer:Gl,deps:[]});var dE=P.effect(nr.Service,s.gen(function*(){let t=yield*wo.Service,e=yield*It.Service;return nr.Service.of({get:s.fn("PtyEnvironment.get")(function*(r){return yield*e.provide({directory:r.directory},t.trigger("shell.env",{cwd:r.cwd},{env:{}}).pipe(s.map(n=>n.env)))})})}));var Ot={};me(Ot,{ApplyChangesError:()=>Qs,CaptureChangesError:()=>Ys,Destination:()=>Wl,DestinationProjectMismatchError:()=>Na,Input:()=>mE,MoveSession:()=>Ot,ResetSourceChangesError:()=>Ks,Service:()=>Po,node:()=>fE});import uE from"path";var Wl=o.Struct({directory:Ie}).annotate({identifier:"MoveSession.Destination"}),mE=o.Struct({sessionID:Wu.ID,destination:Wl,moveChanges:o.optional(o.Boolean)}).annotate({identifier:"MoveSession.Input"}),Na=class extends o.TaggedErrorClass()("MoveSession.DestinationProjectMismatchError",{expected:Fe.ID,actual:Fe.ID}){static{i(this,"DestinationProjectMismatchError")}},Qs=class extends o.TaggedErrorClass()("MoveSession.ApplyChangesError",{message:o.String}){static{i(this,"ApplyChangesError")}},Ys=class extends o.TaggedErrorClass()("MoveSession.CaptureChangesError",{message:o.String}){static{i(this,"CaptureChangesError")}},Ks=class extends o.TaggedErrorClass()("MoveSession.ResetSourceChangesError",{directory:Ie,message:o.String,cause:o.optional(o.Defect())}){static{i(this,"ResetSourceChangesError")}},Po=class extends oe.Service()("@opencode/ControlPlaneMoveSession"){static{i(this,"Service")}},lE=P.effect(Po,s.gen(function*(){let t=yield*uo.Service,e=yield*le.Service,r=yield*Fe.Service,n=yield*mo.Service,a=s.fn("MoveSession.moveSession")(function*(c){let p=yield*n.get(c.sessionID);if(!p)return yield*new Et.NotFoundError({sessionID:c.sessionID});let f=Ie.make(c.destination.directory);if(p.location.directory===f)return;let l=yield*r.resolve(p.location.directory),m=yield*r.resolve(f);if(p.projectID!==m.id)return yield*new Na({expected:p.projectID,actual:m.id});let y=c.moveChanges&&l.directory!==m.directory,g=y?yield*t.repo.discover(p.location.directory):void 0;if(y&&!g)return yield*new Ys({message:"Source is not a Git repository"});let E=g?yield*t.change.capture({repository:g,path:p.location.directory}).pipe(s.mapError(v=>new Ys({message:v.message}))):uo.ChangeSet.make("");if(E){let v=yield*t.repo.discover(f);if(!v)return yield*new Qs({message:"Destination is not a Git repository"});yield*t.change.apply({repository:v,path:f,changes:E}).pipe(s.mapError(h=>new Qs({message:h.message})))}if(yield*e.publish(Dn.Moved,{sessionID:c.sessionID,location:ce.Ref.make({directory:f}),subdirectory:vt.make(uE.relative(m.directory,f).replaceAll("\\","/")),timestamp:yield*ns.now}),E){let v=yield*t.repo.discover(p.location.directory);if(!v)return yield*new Ks({directory:p.location.directory,message:"Source is not a Git repository"});yield*t.change.discard({repository:v,path:p.location.directory,index:"preserve",untracked:"remove"}).pipe(s.mapError(h=>new Ks({directory:p.location.directory,message:h.message,cause:h.cause})))}});return Po.of({moveSession:a})})),fE=Br({service:Po,layer:lE,deps:[uo.node,le.node,Fe.node,mo.node]});var wt={};me(wt,{ConnectToken:()=>SE,PtyTicket:()=>wt,Service:()=>To,make:()=>$l,node:()=>IE});var Bn={};me(Bn,{ConnectToken:()=>yE,PtyTicket:()=>Bn});var yE=o.Struct({ticket:o.String,expires_in:In}).annotate({identifier:"PtyTicket.ConnectToken"});var gE=Si.seconds(60),hE=1e4,SE=Bn.ConnectToken,To=class extends oe.Service()("@opencode/PtyTicket"){static{i(this,"Service")}};function vE(t,e){return t.ptyID===e.ptyID&&t.directory===e.directory&&t.workspaceID===e.workspaceID}i(vE,"matches");var EE=i(()=>s.die("PtyTicket cache must be used via set/invalidateWhen, never get"),"noLookup"),$l=i((t=gE)=>s.gen(function*(){let e=yield*Vi.make({capacity:hE,lookup:EE,timeToLive:t}),r=Math.max(1,Math.round(Si.toSeconds(Si.fromInputUnsafe(t))));return To.of({issue:s.fn("PtyTicket.issue")(function*(n){let a=crypto.randomUUID();return yield*Vi.set(e,a,n),{ticket:a,expires_in:r}}),consume:s.fn("PtyTicket.consume")(function*(n){return yield*Vi.invalidateWhen(e,n.ticket,a=>vE(a,n))})})}),"make"),AE=P.effect(To,$l()),IE=Br({service:To,layer:AE,deps:[]});var Xs={};me(Xs,{SessionRunCoordinator:()=>Xs,make:()=>wE});var wE=i(t=>s.gen(function*(){let e=new Map,r=yield*cu.makeRuntime(),n=i(()=>({done:cr.makeUnsafe(),pendingWake:!1,stopping:!1}),"makeEntry"),a=i((m,y,g,E=!1)=>{let v=cr.makeUnsafe(),h=r((E?s.yieldNow:cr.await(v)).pipe(s.andThen(s.suspend(()=>t.drain(m,g))),s.onExit(w=>s.sync(()=>c(m,y,w))),s.exit,s.asVoid));y.owner=h,E||cr.doneUnsafe(v,s.void)},"start"),c=i((m,y,g)=>{if(ro.isSuccess(g)&&!y.stopping&&y.pendingWake){y.pendingWake=!1,a(m,y,!1,!0);return}let E=y.pendingWake?n():void 0;E===void 0?e.delete(m):(e.set(m,E),a(m,E,!1,!0)),cr.doneUnsafe(y.done,g)},"settle"),p=i(m=>s.uninterruptibleMask(y=>{let g=e.get(m);if(g!==void 0)return g.stopping?y(cr.await(g.done).pipe(s.andThen(p(m)))):y(cr.await(g.done));let E=n();return e.set(m,E),a(m,E,!0),y(cr.await(E.done))}),"run"),f=i(m=>s.sync(()=>{let y=e.get(m);if(y!==void 0){y.pendingWake=!0;return}let g=n();e.set(m,g),a(m,g,!1)}),"wake"),l=i(m=>s.suspend(()=>{let y=e.get(m);return y?.owner===void 0?s.void:(y.stopping=!0,y.pendingWake=!1,Ac.interrupt(y.owner))}),"interrupt");return{active:s.sync(()=>new Set(e.keys())),run:p,wake:f,interrupt:l}}),"make");var DE=P.effect(lo.Service,s.gen(function*(){let t=yield*mo.Service,e=yield*Ge.Service,r=yield*Xs.make({drain:s.fnUntraced(function*(n,a){let c=yield*t.get(n);return c?yield*Ku.Service.use(p=>p.run({sessionID:n,force:a})).pipe(s.provide(e.get(c.location)),s.tapCause(p=>_t.hasInterruptsOnly(p)?s.void:s.logError("Failed to drain Session",p).pipe(s.annotateLogs({sessionID:n})))):yield*s.die(`Session not found: ${n}`)})});return lo.Service.of({active:r.active,interrupt:r.interrupt,resume:r.run,wake:r.wake})})),Vl=Br({service:lo.Service,layer:DE,deps:[mo.node,Ge.node]});function Js(t){let e,r=!1,n=i(()=>(r||(e=t(),r=!0),e),"result");return n.reset=()=>{r=!1,e=void 0},n.loaded=()=>r,n}i(Js,"lazy");var RE=/^https:\/\/([a-z0-9-]+\.)*opencode\.ai$/,Fn=oe.Reference("@opencode/ServerCorsConfig",{defaultValue:i(()=>{},"defaultValue")});function Dp(t,e){return!t||t.startsWith("http://localhost:")||t.startsWith("http://127.0.0.1:")||t.startsWith("oc://renderer")||t==="tauri://localhost"||t==="http://tauri.localhost"||t==="https://tauri.localhost"||RE.test(t)?!0:e?.cors?.includes(t)??!1}i(Dp,"isAllowedCorsOrigin");function Zs(t,e,r){return!t||e&&CE(t,e)?!0:Dp(t,r)}i(Zs,"isAllowedRequestOrigin");function CE(t,e){try{return new URL(t).host===e}catch{return!1}}i(CE,"sameHost");import{createHash as bE}from"node:crypto";var Rr={};me(Rr,{ProxyUtil:()=>Rr,headers:()=>HE,websocketProtocols:()=>PE,websocketTargetURL:()=>TE});var xE=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade","host"]);function kE(t){for(let e of xE)t.delete(e);t.delete("accept-encoding"),t.delete("x-opencode-directory"),t.delete("x-opencode-workspace")}i(kE,"sanitize");function HE(t,e){let r=t instanceof Request?t.headers:t,n=new Headers(r instanceof Headers?r:Object.entries(r));if(kE(n),!e)return n;for(let[a,c]of new Headers(e).entries())n.set(a,c);return n}i(HE,"headers");function PE(t){let e=t instanceof Request?t.headers.get("sec-websocket-protocol"):t["sec-websocket-protocol"];return e?e.split(",").map(r=>r.trim()).filter(Boolean):[]}i(PE,"websocketProtocols");function TE(t){let e=new URL(t);return e.protocol==="http:"&&(e.protocol="ws:"),e.protocol==="https:"&&(e.protocol="wss:"),e.toString()}i(TE,"websocketTargetURL");var qE,Yl=new URL("https://app.opencode.ai"),Rp=i((t="")=>`default-src 'self'; script-src 'self' 'wasm-unsafe-eval'${t?` 'sha256-${t}'`:""}; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: blob:; font-src 'self' data:; media-src 'self' data:; connect-src * data: blob:`,"csp"),Mx=Rp();function ME(t){return t.match(/<script\b(?![^>]*\bsrc\s*=)[^>]*\bid=(['"])oc-theme-preload-script\1[^>]*>([\s\S]*?)<\/script>/i)}i(ME,"themePreloadHash");function Kl(t){let e=ME(t);return Rp(e?bE("sha256").update(e[2]).digest("base64"):"")}i(Kl,"cspForHtml");function OE(t){if(t.method==="GET"||t.method==="HEAD")return An.empty;let e=t.headers["content-length"];return An.stream(t.stream,t.headers["content-type"],e===void 0?void 0:Number(e))}i(OE,"requestBody");function LE(t){let e=new Headers(t);return e.delete("content-encoding"),e.delete("content-length"),e.delete("transfer-encoding"),e}i(LE,"proxyResponseHeaders");function UE(t){return new URL(t,Yl).toString()}i(UE,"upstreamURL");function NE(t){return t?Promise.resolve(null):qE??=import("opencode-web-ui.gen.ts").then(e=>e.default).catch(()=>null)}i(NE,"embeddedUI");function Ql(){return q.jsonUnsafe({error:"Not Found"},{status:404})}i(Ql,"notFound");function _E(t,e){let r=ur.mimeType(t),n=new Headers({"content-type":r});return r.startsWith("text/html")&&n.set("content-security-policy",Kl(new TextDecoder().decode(e))),q.raw(e,{headers:n})}i(_E,"embeddedUIResponse");function BE(t,e,r){let n=r[t.replace(/^\//,"")]??r["index.html"]??null;return n?e.readFile(n).pipe(s.map(a=>_E(n,a)),s.catchReason("PlatformError","NotFound",()=>s.succeed(Ql()))):s.succeed(Ql())}i(BE,"serveEmbeddedUIEffect");function Xl(t,e){return s.gen(function*(){let r=yield*s.promise(()=>NE(e.disableEmbeddedWebUi)),n=new URL(t.url,"http://localhost").pathname;if(r)return yield*BE(n,e.fs,r);let a=yield*e.client.execute(_i.make(t.method)(UE(n),{headers:Rr.headers(t.headers,{host:Yl.host}),body:OE(t)})),c=LE(a.headers);if(a.headers["content-type"]?.includes("text/html")){let p=yield*a.text;return c.set("Content-Security-Policy",Kl(p)),q.text(p,{status:a.status,headers:c})}return c.set("Content-Security-Policy",Rp()),q.stream(a.stream.pipe(se.catchCause(()=>se.empty)),{status:a.status,headers:c})})}i(Xl,"serveUIEffect");var Cr={};me(Cr,{Definitions:()=>_a,Durable:()=>Ji,EventManifest:()=>Cr,Latest:()=>Cp});var ei={};me(ei,{Definitions:()=>_a,Durable:()=>Ji,EventManifest:()=>ei,Latest:()=>Cp,ServerDefinitions:()=>$E});var jn={};me(jn,{Connected:()=>Jl,Definitions:()=>FE,Disposed:()=>Zl,ServerEvent:()=>jn});var Jl=st.define({type:"server.connected",schema:{}}),Zl=st.define({type:"global.disposed",schema:{}}),FE=st.inventory(Jl,Zl);var jE=Tc.Event.Definitions.filter(t=>t.durable!==void 0),GE=Tc.Event.Definitions.filter(t=>t.durable===void 0),WE=st.inventory(...jE,...Dn.Definitions),ef=st.inventory(...nm.Event.Definitions,...Ye.Event.Definitions,...Cu.Event.Definitions,...WE),tf=st.inventory(...Rn.Event.Definitions,...ta.Event.Definitions,...be.Event.Definitions,...Xu.Event.Definitions,...om.Event.Definitions,...Gu.Event.Definitions,...Ke.Event.Definitions,...Qr.Event.Definitions),$E=st.inventory(...ef,...tf,...Mc.Event.Definitions),_a=st.inventory(...ef,...GE,...bm.Definitions,...tf,...Mc.Event.Definitions,...Rm.Definitions,...Nu.Event.Definitions,...ie.Definitions,...Em.Definitions,...xm.Definitions,...Ht.Event.Definitions,...Sm.Definitions,...hm.Event.Definitions,...Im.Definitions,...km.Definitions,...$u.Definitions,...Tm.Definitions,...jn.Definitions),Cp=st.latest(_a);var rf=jn,Ba=o.Struct({id:o.String,type:o.Literal("server.instance.disposed"),properties:o.Struct({directory:o.String})}).annotate({identifier:"Event.server.instance.disposed"});var ti="ticket",nf="x-opencode-ticket";var VE=/^\/pty\/[^/]+\/connect$/;function zE(t){return VE.test(t)}i(zE,"isPtyConnectPath");function of(t){return zE(t.pathname)&&!!t.searchParams.get(ti)}i(of,"hasPtyConnectTicketURL");var QE=new Set(["/site.webmanifest","/web-app-manifest-192x192.png","/web-app-manifest-512x512.png"]);function sf(t,e){return t==="GET"&&QE.has(e)}i(sf,"isPublicUIPath");var Gn={};me(Gn,{Config:()=>xp,ServerAuth:()=>Gn,authorized:()=>KE,header:()=>af,headers:()=>XE,required:()=>YE});var xp=class t extends oe.Service()("@opencode/ServerAuthConfig"){static{i(this,"Config")}static configLayer(e){return P.succeed(this,this.of(e))}static get layer(){return P.effect(this,s.gen(function*(){return t.of(yield*co.all({password:co.string("OPENCODE_SERVER_PASSWORD").pipe(co.option),username:co.string("OPENCODE_SERVER_USERNAME").pipe(co.withDefault("opencode"))}))}))}};function YE(t){return Re.isSome(t.password)&&t.password.value!==""}i(YE,"required");function KE(t,e){return Re.isSome(e.password)&&t.username===e.username&&dr.value(t.password)===e.password.value}i(KE,"authorized");function af(t){let e=t?.password??process.env.OPENCODE_SERVER_PASSWORD;if(e)return`Basic ${Buffer.from(`${t?.username??process.env.OPENCODE_SERVER_USERNAME??"opencode"}:${e}`).toString("base64")}`}i(af,"header");function XE(t){let e=af(t);if(e)return{Authorization:e}}i(XE,"headers");var Pe=class extends o.TaggedErrorClass()("InvalidRequestError",{message:o.String,kind:o.optional(o.String),field:o.optional(o.String)},{httpApiStatus:400}){static{i(this,"InvalidRequestError")}},bo=class extends o.TaggedErrorClass()("UnauthorizedError",{message:o.String},{httpApiStatus:401}){static{i(this,"UnauthorizedError")}},qo=class extends o.TaggedErrorClass()("ConflictError",{message:o.String,resource:o.optional(o.String)},{httpApiStatus:409}){static{i(this,"ConflictError")}},mt=class extends o.TaggedErrorClass()("ServiceUnavailableError",{message:o.String,service:o.optional(o.String)},{httpApiStatus:503}){static{i(this,"ServiceUnavailableError")}},tt=class extends o.TaggedErrorClass()("UnknownError",{message:o.String,ref:o.optional(o.String)},{httpApiStatus:500}){static{i(this,"UnknownError")}},Mo=class extends o.TaggedErrorClass()("ProviderNotFoundError",{providerID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"ProviderNotFoundError")}},N=class extends o.TaggedErrorClass()("SessionNotFoundError",{sessionID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"SessionNotFoundError")}},sn=class extends o.TaggedErrorClass()("MessageNotFoundError",{sessionID:o.String,messageID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"MessageNotFoundError")}},Lt=class extends o.TaggedErrorClass()("InvalidCursorError",{message:o.String},{httpApiStatus:400}){static{i(this,"InvalidCursorError")}},Wn=class extends o.TaggedErrorClass()("PermissionNotFoundError",{requestID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"PermissionNotFoundError")}},$n=class extends o.TaggedErrorClass()("QuestionNotFoundError",{requestID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"QuestionNotFoundError")}},Vn=class extends o.TaggedErrorClass()("ForbiddenError",{message:o.String},{httpApiStatus:403}){static{i(this,"ForbiddenError")}},lt=class extends o.TaggedErrorClass()("PtyNotFoundError",{ptyID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"PtyNotFoundError")}};var or=class extends ye.Service()("@opencode/HttpApiAuthorization",{error:bo}){static{i(this,"Authorization")}};var _=o.Struct({location:o.optional(o.Struct({directory:o.optional(o.String),workspace:o.optional(o.String)}))}).annotate({identifier:"LocationQuery"}),B=d.annotations({transform:i(t=>{let e=t.parameters;return Array.isArray(e)?{...t,parameters:e.map(r=>r?.name==="location"&&r?.in==="query"?{...r,style:"deepObject",explode:!0}:r)}:t},"transform")}),cf=H.make("server.location").add(u.get("location.get","/api/location",{query:_,success:z.Info}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.location.get",summary:"Get location",description:"Resolve the requested location or the server default location."})));var Fa="ticket",pf="x-opencode-ticket",df="1",JE=/^\/api\/pty\/[^/]+\/connect$/;function uf(t){return JE.test(t.pathname)&&!!t.searchParams.get(Fa)}i(uf,"hasPtyConnectTicketURL");var mf=H.make("server.pty").add(u.get("pty.list","/api/pty",{query:_,success:z.response(o.Array(Ke.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.list",summary:"List PTY sessions",description:"List PTY sessions for a location, including exited sessions retained until removal."}))).add(u.post("pty.create","/api/pty",{query:_,payload:Ke.CreateInput,success:z.response(Ke.Info)}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.create",summary:"Create PTY session",description:"Create a pseudo-terminal session for a location."}))).add(u.get("pty.get","/api/pty/:ptyID",{params:{ptyID:Ke.ID},query:_,success:z.response(Ke.Info),error:lt}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.get",summary:"Get PTY session",description:"Get one PTY session, including its exit code once exited."}))).add(u.put("pty.update","/api/pty/:ptyID",{params:{ptyID:Ke.ID},query:_,payload:Ke.UpdateInput,success:z.response(Ke.Info),error:lt}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.update",summary:"Update PTY session",description:"Update the title or viewport size of one PTY session."}))).add(u.delete("pty.remove","/api/pty/:ptyID",{params:{ptyID:Ke.ID},query:_,success:k.NoContent,error:lt}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.remove",summary:"Remove PTY session",description:"Terminate and remove one PTY session."}))).add(u.post("pty.connectToken","/api/pty/:ptyID/connect-token",{params:{ptyID:Ke.ID},query:_,success:z.response(Bn.ConnectToken),error:[Vn,lt]}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.pty.connectToken",summary:"Create PTY WebSocket token",description:"Create a short-lived single-use ticket for opening a PTY WebSocket connection."}))).add(u.get("pty.connect","/api/pty/:ptyID/connect",{params:{ptyID:Ke.ID},success:o.Boolean,error:[Vn,lt]}).annotateMerge(d.annotations({identifier:"v2.pty.connect",summary:"Connect to PTY session",description:"Establish a WebSocket connection streaming PTY output and accepting terminal input.",transform:i(t=>({...t,"x-websocket":!0,parameters:[...t.parameters??[],...["location[directory]","location[workspace]","cursor",Fa].map(e=>({in:"query",name:e,schema:{type:"string"}}))]}),"transform")}))).annotateMerge(d.annotations({title:"pty",description:"Experimental location-scoped PTY routes."}));var ZE="auth_token",eA='Basic realm="Secure Area"';function kp(){return{username:"",password:dr.make("")}}i(kp,"emptyCredential");function lf(t){return s.fromResult(Lr.decodeBase64String(t)).pipe(s.match({onFailure:kp,onSuccess:i(e=>{let r=e.indexOf(":");return r===-1?kp():{username:e.slice(0,r),password:dr.make(e.slice(r+1))}},"onSuccess")}))}i(lf,"decodeCredential");function tA(t){let r=new URL(t.url,"http://localhost").searchParams.get(ZE);if(r)return lf(r);let n=/^Basic\s+(.+)$/i.exec(t.headers.authorization??"");return n?lf(n[1]):s.succeed(kp())}i(tA,"credentialFromRequest");var Hp=P.effect(or,s.gen(function*(){let t=yield*Gn.Config;return Gn.required(t)?or.of(e=>s.gen(function*(){let r=yield*ge.HttpServerRequest;if(uf(new URL(r.url,"http://localhost")))return yield*e;let n=yield*tA(r);return Gn.authorized(n,t)?yield*e:(yield*_r.appendPreResponseHandler((a,c)=>s.succeed(q.setHeader(c,"www-authenticate",eA))),yield*new bo({message:"Authentication required"}))})):or.of(e=>e)}));var rA="auth_token",nA=401,yf='Basic realm="Secure Area"',j=class extends ye.Service()("@opencode/ExperimentalHttpApiAuthorization",{error:D.UnauthorizedNoContent}){static{i(this,"Authorization")}},zn=class extends ye.Service()("@opencode/ExperimentalHttpApiPtyConnectAuthorization",{error:D.UnauthorizedNoContent}){static{i(this,"PtyConnectAuthorization")}};function Pp(){return{username:"",password:dr.make("")}}i(Pp,"emptyCredential");function gf(t,e,r){return s.gen(function*(){return Ne.required(r)?Ne.authorized(e,r)?yield*t:(yield*_r.appendPreResponseHandler((n,a)=>s.succeed(q.setHeader(a,"www-authenticate",yf))),yield*new D.Unauthorized({})):yield*t})}i(gf,"validateCredential");function ff(t){return s.fromResult(Lr.decodeBase64String(t)).pipe(s.match({onFailure:Pp,onSuccess:i(e=>{let r=e.indexOf(":");return r===-1?Pp():{username:e.slice(0,r),password:dr.make(e.slice(r+1))}},"onSuccess")}))}i(ff,"decodeCredential");function oA(t){return Tp(new URL(t.url,"http://localhost"),t)}i(oA,"credentialFromRequest");function Tp(t,e){let r=t.searchParams.get(rA);if(r)return ff(r);let n=/^Basic\s+(.+)$/i.exec(e.headers.authorization??"");return n?ff(n[1]):s.succeed(Pp())}i(Tp,"credentialFromURL");function sA(t,e,r){return Ne.required(r)?Ne.authorized(e,r)?t:s.succeed(q.empty({status:nA,headers:{"www-authenticate":yf}})):t}i(sA,"validateRawCredential");var hf=Ce.middleware()(s.gen(function*(){let t=yield*Ne.Config;return Ne.required(t)?e=>s.gen(function*(){let r=yield*ge.HttpServerRequest,n=new URL(r.url,"http://localhost");return sf(r.method,n.pathname)?yield*e:yield*Tp(n,r).pipe(s.flatMap(a=>sA(e,a,t)))}):e=>e})),Sf=P.effect(j,s.gen(function*(){let t=yield*Ne.Config;return Ne.required(t)?j.of(e=>s.gen(function*(){let r=yield*ge.HttpServerRequest;return yield*oA(r).pipe(s.flatMap(n=>gf(e,n,t)))})):j.of(e=>e)})),vf=P.effect(zn,s.gen(function*(){let t=yield*Ne.Config;return Ne.required(t)?zn.of(e=>s.gen(function*(){let r=yield*ge.HttpServerRequest,n=new URL(r.url,"http://localhost");return of(n)?yield*e:yield*Tp(n,r).pipe(s.flatMap(a=>gf(e,a,t)))})):zn.of(e=>e)}));var Oo={};me(Oo,{HttpApiProxy:()=>Oo,http:()=>mA,websocket:()=>uA});var $e={};me($e,{SERVER_CLOSING_EVENT:()=>iA,Service:()=>Qn,WebSocketTracker:()=>$e,node:()=>cA,register:()=>pA});var iA=i(()=>new Le(1001,"server closing"),"SERVER_CLOSING_EVENT"),Qn=class extends oe.Service()("@opencode/HttpApiWebSocketTracker"){static{i(this,"Service")}},aA=P.sync(Qn)(()=>{let t=new Set,e=!1;return Qn.of({add:i(r=>s.gen(function*(){return e?!1:(t.add(r),!0)}),"add"),remove:i(r=>s.sync(()=>{t.delete(r)}),"remove"),closeAll:s.gen(function*(){e=!0;let r=Array.from(t);t.clear(),yield*s.all(r.map(n=>n.pipe(s.timeout("1 second"),s.catch(()=>s.void))),{concurrency:"unbounded",discard:!0})})})}),cA=zi.make({service:Qn,layer:aA,deps:[]}),pA=i(t=>s.gen(function*(){let e=yield*s.serviceOption(Qn);return Re.isNone(e)?!0:(yield*e.value.add(t))?(yield*s.addFinalizer(()=>e.value.remove(t)),!0):!1}),"register");function dA(t){if(t.method==="GET"||t.method==="HEAD")return An.empty;if(t.source instanceof Request&&t.source.body===null)return An.empty;let e=t.headers["content-length"];return An.stream(t.stream,t.headers["content-type"],e?Number(e):void 0)}i(dA,"requestBody");function uA(t,e){return s.scoped(s.gen(function*(){let r=yield*s.orDie(t.upgrade),n=yield*du(Rr.websocketTargetURL(e),{protocols:Rr.websocketProtocols(t.headers)}),a=yield*r.writer,c=yield*n.writer,p=i((m,y)=>m.runRaw(()=>s.void,{onOpen:y($e.SERVER_CLOSING_EVENT()).pipe(s.catch(()=>s.void))}).pipe(s.timeout("1 second"),s.catchReason("SocketError","SocketCloseError",()=>s.void),s.catch(()=>s.void)),"closeSocket"),f=s.all([p(r,a),p(n,c)],{concurrency:"unbounded",discard:!0});return(yield*$e.register(s.all([a($e.SERVER_CLOSING_EVENT()),c($e.SERVER_CLOSING_EVENT())],{concurrency:"unbounded",discard:!0})))?(yield*n.runRaw(m=>a(m)).pipe(s.catchReason("SocketError","SocketCloseError",m=>a(new Le(m.code,m.closeReason)).pipe(s.catch(()=>s.void))),s.catch(()=>a(new Le(1011,"proxy error")).pipe(s.catch(()=>s.void))),s.forkScoped),yield*r.runRaw(m=>c(typeof m=="string"?m:m.slice())).pipe(s.catch(()=>s.void),s.ensuring(c(new Le).pipe(s.catch(()=>s.void)))),q.empty()):(yield*f,q.empty())}).pipe(s.orDie))}i(uA,"websocket");function Ef(t){return t.source?.statusText}i(Ef,"statusText");function mA(t,e,r,n){return s.gen(function*(){let a=yield*t.execute(_i.make(n.method)(e,{headers:Rr.headers(n.headers,r),body:dA(n)})),c=new Headers(a.headers);if(c.delete("content-encoding"),c.delete("content-length"),a.status>=500){let p=yield*a.text.pipe(s.catch(()=>s.succeed(""))),f=a.headers["content-type"]??"application/json";return c.delete("content-type"),yield*s.logError("workspace proxy upstream error",{url:e.toString(),method:n.method,status:a.status,body:p.slice(0,2e3)}),q.text(p,{status:a.status,statusText:Ef(a),headers:c,contentType:f})}return q.stream(a.stream.pipe(se.catchCause(()=>se.empty)),{status:a.status,statusText:Ef(a),headers:c})}).pipe(s.catch(()=>s.succeed(q.empty({status:500}))))}i(mA,"http");var bp="x-opencode-sync";function qp(t,e){return s.gen(function*(){let r=yield*(e?.length?t.select().from(Xi).where(Tu(Xi.aggregate_id,e)).all():t.select().from(Xi).all()).pipe(s.orDie);return Object.fromEntries(r.map(n=>[n.aggregate_id,n.seq]))})}i(qp,"load");function Af(t,e){let r=new Set([...Object.keys(t),...Object.keys(e)]);return Object.fromEntries([...r].map(n=>[n,e[n]??-1]).filter(([n,a])=>(t[n]??-1)!==a))}i(Af,"diff");function If(t){let e=t.get(bp);if(!e)return;let r;try{r=JSON.parse(e)}catch{return}if(!(!r||typeof r!="object"))return Object.fromEntries(Object.entries(r).filter(n=>typeof n[0]=="string"&&Number.isInteger(n[1])))}i(If,"parse");function wf(t,e,r){return s.gen(function*(){yield*s.logInfo("waiting for state",{workspaceID:t,state:e}),yield*fe.Service.use(n=>n.waitForSync(t,e,r)),yield*s.logInfo("state fully synced",{workspaceID:t,state:e})})}i(wf,"wait");var lA=[{path:"/experimental/workspace",action:"local"},{path:"/session/status",action:"forward"},{method:"GET",path:"/session",action:"local"}];function Rf(t,e){for(let r of lA){if(r.method&&r.method!==t)continue;if(r.exact?e===r.path:e===r.path||e.startsWith(r.path+"/"))return r.action==="local"}return!1}i(Rf,"isLocalWorkspaceRoute");function Cf(t){if(t.pathname==="/session/status")return null;let e=t.pathname.match(/^\/session\/([^/]+)(?:\/|$)/)?.[1]??t.pathname.match(/^\/experimental\/session\/([^/]+)\/background$/)?.[1];return e?Y.make(e):null}i(Cf,"getWorkspaceRouteSessionID");function xf(t,e){let r=new URL(t);return r.pathname=`${r.pathname.replace(/\/$/,"")}${e.pathname}`,r.search=e.search,r.hash=e.hash,r.searchParams.delete("workspace"),r.searchParams.delete("directory"),r}i(xf,"workspaceProxyURL");var Yn=class extends o.TaggedErrorClass()("InvalidRequestError",{message:o.String,kind:o.optional(o.String),field:o.optional(o.String)},{httpApiStatus:400}){static{i(this,"InvalidRequestError")}},kf=class extends o.TaggedErrorClass()("UnauthorizedError",{message:o.String},{httpApiStatus:401}){static{i(this,"UnauthorizedError")}},Hf=class extends o.TaggedErrorClass()("ForbiddenError",{message:o.String},{httpApiStatus:403}){static{i(this,"ForbiddenError")}},Pf=class extends o.TaggedErrorClass()("ConflictError",{message:o.String,resource:o.optional(o.String)},{httpApiStatus:409}){static{i(this,"ConflictError")}},Tf=class extends o.TaggedErrorClass()("UpstreamError",{message:o.String,service:o.optional(o.String),status:o.optional(o.Number)},{httpApiStatus:502}){static{i(this,"UpstreamError")}},bf=class extends o.TaggedErrorClass()("ServiceUnavailableError",{message:o.String,service:o.optional(o.String)},{httpApiStatus:503}){static{i(this,"ServiceUnavailableError")}},qf=class extends o.TaggedErrorClass()("TimeoutError",{message:o.String,operation:o.optional(o.String)},{httpApiStatus:504}){static{i(this,"TimeoutError")}},Mf=class extends o.TaggedErrorClass()("UnknownError",{message:o.String,ref:o.optional(o.String)},{httpApiStatus:500}){static{i(this,"UnknownError")}},Of=class extends o.TaggedErrorClass()("ProviderNotFoundError",{providerID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"ProviderNotFoundError")}},Lf=class extends o.TaggedErrorClass()("ModelNotFoundError",{providerID:o.String,modelID:o.String,suggestions:o.Array(o.String),message:o.String},{httpApiStatus:404}){static{i(this,"ModelNotFoundError")}},Uf=class extends o.TaggedErrorClass()("SessionNotFoundError",{sessionID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"SessionNotFoundError")}},Nf=class extends o.TaggedErrorClass()("MessageNotFoundError",{sessionID:o.String,messageID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"MessageNotFoundError")}},_f=class extends o.TaggedErrorClass()("InvalidCursorError",{message:o.String},{httpApiStatus:400}){static{i(this,"InvalidCursorError")}},xr=class extends o.TaggedErrorClass()("SessionBusyError",{sessionID:o.String,message:o.String},{httpApiStatus:409}){static{i(this,"SessionBusyError")}},an=class extends o.TaggedErrorClass()("QuestionNotFoundError",{requestID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"QuestionNotFoundError")}},sr=class extends o.TaggedErrorClass()("PermissionNotFoundError",{requestID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"PermissionNotFoundError")}},_e=class extends o.TaggedErrorClass()("McpServerNotFoundError",{name:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"McpServerNotFoundError")}},Dt=class extends o.TaggedErrorClass()("PtyNotFoundError",{ptyID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"PtyNotFoundError")}},Lo=class extends o.TaggedErrorClass()("PtyForbiddenError",{message:o.String},{httpApiStatus:403}){static{i(this,"PtyForbiddenError")}},Uo=class extends o.TaggedErrorClass()("ProjectNotFoundError",{projectID:o.String,message:o.String},{httpApiStatus:404}){static{i(this,"ProjectNotFoundError")}},te=class extends o.ErrorClass("NotFoundError")({name:o.Literal("NotFoundError"),data:o.Struct({message:o.String})},{httpApiStatus:404}){static{i(this,"ApiNotFoundError")}};function ja(t){return new te({name:"NotFoundError",data:{message:t}})}i(ja,"notFound");var xe={directory:o.optional(o.String),workspace:o.optional(o.String)},I=o.Struct(xe),No=pc.taggedEnum(),Ff=Symbol("InvalidWorkspaceID"),_o=class extends oe.Service()("@opencode/ExperimentalHttpApiWorkspaceRouteContext"){static{i(this,"WorkspaceRouteContext")}},W=class extends ye.Service()("@opencode/ExperimentalHttpApiWorkspaceRouting"){static{i(this,"WorkspaceRoutingMiddleware")}};function jf(t){return new URL(t.url,"http://localhost")}i(jf,"requestURL");function fA(){return ms.OPENCODE_WORKSPACE_ID?$r.ID.make(ms.OPENCODE_WORKSPACE_ID):void 0}i(fA,"configuredWorkspaceID");function yA(t,e){let r=t.searchParams.get("workspace");return e??(r?$r.ID.make(r):void 0)}i(yA,"selectedWorkspaceID");function gA(t,e){if(e)return e;let r=t.searchParams.get("workspace");if(!r)return;let n=o.decodeUnknownOption($r.ID)(r);return Re.isNone(n)?Ff:n.value}i(gA,"selectedV2WorkspaceID");function hA(t,e){return e.searchParams.get("directory")||t.headers["x-opencode-directory"]||process.cwd()}i(hA,"defaultDirectory");function SA(t,e){return Rf(t.method,e.pathname)||e.pathname.startsWith("/console")}i(SA,"shouldStayOnControlPlane");function vA(t,e){return!t||e?s.void:fe.Service.use(r=>r.get(t))}i(vA,"resolveWorkspace");function EA(t){return q.text(`Workspace not found: ${t}`,{status:500,contentType:"text/plain; charset=utf-8"})}i(EA,"missingWorkspaceResponse");function AA(t){return Hm.target(t)}i(AA,"resolveTarget");function IA(t,e,r,n,a){return s.gen(function*(){if(!(yield*fe.Service.use(y=>y.isSyncing(r.id))))return q.text(`broken sync connection for workspace: ${r.id}`,{status:503,contentType:"text/plain; charset=utf-8"});let p=xf(n.url,a);if(e.headers.upgrade?.toLowerCase()==="websocket")return yield*Oo.websocket(e,p);let l=yield*Oo.http(t,p,n.headers,e),m=If(new Headers(l.headers));if(m){let y=yield*wf(r.id,m,e.source instanceof Request?e.source.signal:void 0).pipe(s.as(void 0),s.catch(g=>s.succeed(q.text(g.message,{status:503}))));if(y)return y}return l})}i(IA,"proxyRemote");function wA(t,e,r){return s.gen(function*(){let n=yield*AA(r);return n.type==="remote"?No.Remote({request:t,workspace:r,target:n,url:e}):No.Local({directory:n.directory,workspaceID:r.id})})}i(wA,"planWorkspaceRequest");function DA(t,e){return s.gen(function*(){let r=jf(t),n=fA(),a=r.pathname.startsWith("/api/")?gA(r,e?.workspaceID):yA(r,e?.workspaceID);if(a===Ff)return No.InvalidWorkspace();let c=yield*vA(a,n);return a&&c===void 0&&!n?No.MissingWorkspace({workspaceID:a}):c!==void 0&&!n&&!SA(t,r)?yield*wA(t,r,c):No.Local({directory:e?.directory||hA(t,r),workspaceID:n??a})})}i(DA,"planRequest");function RA(t,e,r){return No.$match(r,{InvalidWorkspace:i(()=>s.succeed(q.jsonUnsafe(new Yn({message:"Invalid workspace query parameter",kind:"Query",field:"workspace"}),{status:400})),"InvalidWorkspace"),MissingWorkspace:i(({workspaceID:n})=>s.succeed(EA(n)),"MissingWorkspace"),Remote:i(({request:n,workspace:a,target:c,url:p})=>IA(t,n,a,c,p),"Remote"),Local:i(({directory:n,workspaceID:a})=>e.pipe(s.provideService(_o,_o.of({directory:n,workspaceID:a}))),"Local")})}i(RA,"routeWorkspace");function CA(t,e){return s.gen(function*(){let r=yield*ge.HttpServerRequest,n=Cf(jf(r)),a=n?yield*X.Service.use(p=>p.get(n)).pipe(s.catchIf(p=>lm.isInstance(p),()=>s.succeed(void 0)),s.catchDefect(()=>s.succeed(void 0))):void 0,c=yield*DA(r,a);return yield*RA(t,e,c)})}i(CA,"routeHttpApiWorkspace");var Gf=P.effect(W,s.gen(function*(){let t=yield*xc,e=yield*fe.Service,r=yield*Bi.HttpClient;return W.of(n=>CA(r,n).pipe(s.provideService(xc,t),s.provideService(fe.Service,e)))}));var $=class extends ye.Service()("@opencode/ExperimentalHttpApiInstanceContext"){static{i(this,"InstanceContextMiddleware")}};function xA(t){try{return decodeURIComponent(t)}catch{return t}}i(xA,"decode");function kA(t,e){return s.gen(function*(){let r=yield*_o,n=yield*e.load({directory:xA(r.directory)});return yield*t.pipe(s.provideService(aa,n),s.provideService(ca,r.workspaceID))})}i(kA,"provideInstanceContext");var Ga=P.effect($,s.gen(function*(){let t=yield*It.Service;return $.of(e=>kA(e,t))}));function S(t,e){return t.annotate({description:e})}i(S,"described");var Mp="/config",Wf=U.make("config").add(H.make("config").add(u.get("get",Mp,{query:I,success:S(Gr.Info,"Get config info")}).annotateMerge(d.annotations({identifier:"config.get",summary:"Get configuration",description:"Retrieve the current OpenCode configuration settings and preferences."})),u.patch("update",Mp,{query:I,payload:Gr.Info,success:S(Gr.Info,"Successfully updated config"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"config.update",summary:"Update configuration",description:"Update OpenCode configuration settings and preferences."})),u.get("providers",`${Mp}/providers`,{query:I,success:S(Me.ConfigProvidersResult,"List of providers")}).annotateMerge(d.annotations({identifier:"config.providers",summary:"List config providers",description:"Get a list of all configured AI providers and their default models."}))).annotateMerge(d.annotations({title:"config",description:"Experimental HttpApi config routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var HA=o.Struct({paused:o.Boolean,waiting:o.Array(o.String)}),PA=o.Struct({paused:o.Boolean}),TA=o.Struct({paused:o.Boolean,stopped:o.optional(o.Array(o.String)),waiting:o.optional(o.Array(o.String))}),bA=o.Struct({ok:o.Boolean,deferred:o.optional(o.Boolean)}),qA=o.Struct({kind:o.String,label:o.String,usedPercent:o.Number,resetsAt:o.NullOr(o.Number)}),MA=o.Struct({fetchedAt:o.Number,providers:o.Array(o.Struct({providerID:o.String,plan:o.NullOr(o.String),error:o.optional(o.String),readAt:o.optional(o.Number),windows:o.Array(qA)}))}),OA=o.Struct({exa:o.Boolean,tavily:o.Boolean}),$f=U.make("alchemy").add(H.make("alchemy").add(u.get("pauseState","/config/pause",{query:I,success:S(HA,"Pause state")}).annotateMerge(d.annotations({identifier:"config.pauseState",summary:"Pause state",description:"Whether this project's turns are paused, and the sessions whose turns wait for Resume."})),u.post("pause","/config/pause",{query:I,payload:PA,success:S(TA,"The new state; stopped on pause, waiting on resume")}).annotateMerge(d.annotations({identifier:"config.pause",summary:"Pause or resume the project",description:"Paused, no turn runs: running turns stop and their sessions wait, and anything sent meanwhile lands and waits. Resume returns the sessions that wait, for the caller to wake."})),u.post("reload","/config/reload",{query:I,success:S(bA,"Config cache invalidated")}).annotateMerge(d.annotations({identifier:"config.reload",summary:"Reload configuration",description:"Drop cached config and agent state so the next request reads them again. While a session is busy the reload waits for all sessions to be idle (two minutes at most)."})),u.get("usage","/config/usage",{query:o.Struct({...xe,force:o.optional(o.String)}),success:S(MA,"Per-provider usage windows")}).annotateMerge(d.annotations({identifier:"config.usage",summary:"Plan usage",description:"Percent used and reset times of the usage windows on the OAuth providers this instance is signed into."})),u.get("mcpTools","/mcp/tools",{query:I,success:S(o.Record(o.String,o.Array(qe.ToolManifestEntry)),"Tools per connected server")}).annotateMerge(d.annotations({identifier:"mcp.tools",summary:"List MCP tools",description:"The tool catalogue each connected MCP server advertises, with read-only annotations intact. This is the catalogue, not the callable tool set: use it to show or govern what a server offers."})),u.get("searchKeys","/websearch/keys",{query:I,success:S(OA,"Whether each search service has a key")}).annotateMerge(d.annotations({identifier:"websearch.keys",summary:"Web search keys",description:"Which web search services have a key of the user's own set. Yes or no, never a key."}))).annotateMerge(d.annotations({title:"alchemy",description:"AlchemyLab fork routes."})).middleware($).middleware(W).middleware(j));var Vf=o.Struct({providerID:kt.ID}),LA=o.Struct({directory:o.optional(o.String),workspace:o.optional(o.String)}),UA=o.Struct({service:o.String.annotate({description:"Service name for the log entry"}),level:o.Union([o.Literal("debug"),o.Literal("info"),o.Literal("error"),o.Literal("warn")]).annotate({description:"Log level"}),message:o.String.annotate({description:"Log message"}),extra:o.optional(o.Record(o.String,o.Unknown)).annotate({description:"Additional metadata for the log entry"})}),Op={auth:"/auth/:providerID",log:"/log"},zf=U.make("control").add(H.make("control").add(u.put("authSet",Op.auth,{params:Vf,payload:Gt.Info,success:S(o.Boolean,"Successfully set authentication credentials"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"auth.set",summary:"Set auth credentials",description:"Set authentication credentials"})),u.delete("authRemove",Op.auth,{params:Vf,success:S(o.Boolean,"Successfully removed authentication credentials"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"auth.remove",summary:"Remove auth credentials",description:"Remove authentication credentials"})),u.post("log",Op.log,{query:LA,payload:UA,success:S(o.Boolean,"Log entry written successfully"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"app.log",summary:"Write log",description:"Write a log entry to the server logs with specified level and metadata."}))).annotateMerge(d.annotations({title:"control",description:"Control plane routes."})));var NA="/experimental/control-plane",_A=o.Struct({...Ot.Input.fields}),ni=class extends o.ErrorClass("MoveSessionError")({name:o.Literal("MoveSessionError"),data:o.Struct({message:o.String})},{httpApiStatus:400}){static{i(this,"ApiMoveSessionError")}},Qf=U.make("controlPlane").add(H.make("controlPlane").add(u.post("moveSession",`${NA}/move-session`,{payload:_A,success:S(k.NoContent,"Session moved"),error:ni}).annotateMerge(d.annotations({identifier:"experimental.controlPlane.moveSession",summary:"Move session",description:"Move a session to another project directory, optionally transferring local changes."}))).annotateMerge(d.annotations({title:"controlPlane",description:"Control-plane orchestration routes."})));var BA={event:"/event"},Bo=U.make("event").add(H.make("event").add(u.get("subscribe",BA.event,{query:I,success:o.String.pipe(k.asText({contentType:"text/event-stream"}))}).annotateMerge(d.annotations({identifier:"event.subscribe",summary:"Subscribe to events",description:"Get events"}))).middleware($).middleware(W).middleware(j).annotateMerge(d.annotations({title:"event",description:"Instance event stream route."})));var oi=o.Literals(["true","false"]).pipe(o.decodeTo(o.Boolean,{decode:gc.transform(t=>t==="true"),encode:gc.transform(t=>t?"true":"false")})),si={anyOf:[{type:"boolean"},{type:"string",enum:["true","false"]}]};var FA=o.Struct({consoleManagedProviders:o.mutable(o.Array(o.String)),activeOrgName:o.optionalKey(o.String),switchableOrgCount:Ae}).annotate({identifier:"ConsoleState"}),jA=o.Struct({backgroundSubagents:o.Boolean}).annotate({identifier:"ExperimentalCapabilities"}),GA=o.Struct({accountID:o.String,accountEmail:o.String,accountUrl:o.String,orgID:o.String,orgName:o.String,active:o.Boolean}),WA=o.Struct({orgs:o.Array(GA)}),$A=o.Struct({accountID:cm,orgID:pm}),VA=o.Array(o.String).annotate({identifier:"ToolIDs"}),zA=o.Struct({id:o.String,description:o.String,parameters:o.Unknown}).annotate({identifier:"ToolListItem"}),QA=o.Array(zA).annotate({identifier:"ToolList"}),YA=o.Struct({...xe,provider:kt.ID,model:us.ID}),KA=o.Array(o.String),XA=o.Union([o.Literal("WorktreeNotGitError"),o.Literal("WorktreeNameGenerationFailedError"),o.Literal("WorktreeCreateFailedError"),o.Literal("WorktreeStartCommandFailedError"),o.Literal("WorktreeRemoveFailedError"),o.Literal("WorktreeResetFailedError"),o.Literal("WorktreeListFailedError")]),cn=class extends o.ErrorClass("WorktreeError")({name:XA,data:o.Struct({message:o.String})},{httpApiStatus:400}){static{i(this,"WorktreeApiError")}},JA=o.Struct({...xe,roots:o.optional(oi),start:o.optional(o.NumberFromString),cursor:o.optional(o.NumberFromString),search:o.optional(o.String),limit:o.optional(o.NumberFromString),archived:o.optional(oi)}),ft={capabilities:"/experimental/capabilities",console:"/experimental/console",consoleOrgs:"/experimental/console/orgs",consoleSwitch:"/experimental/console/switch",tool:"/experimental/tool",toolIDs:"/experimental/tool/ids",worktree:"/experimental/worktree",worktreeReset:"/experimental/worktree/reset",session:"/experimental/session",sessionBackground:"/experimental/session/:sessionID/background",resource:"/experimental/resource"},Yf=U.make("experimental").add(H.make("experimental").add(u.get("capabilities",ft.capabilities,{query:I,success:S(jA,"Experimental capabilities")}).annotateMerge(d.annotations({identifier:"experimental.capabilities.get",summary:"Get experimental capabilities",description:"Get experimental features enabled on the OpenCode server."})),u.get("console",ft.console,{query:I,success:S(FA,"Active Console provider metadata"),error:D.InternalServerError}).annotateMerge(d.annotations({identifier:"experimental.console.get",summary:"Get active Console provider metadata",description:"Get the active Console org name and the set of provider IDs managed by that Console org."})),u.get("consoleOrgs",ft.consoleOrgs,{query:I,success:S(WA,"Switchable Console orgs"),error:D.InternalServerError}).annotateMerge(d.annotations({identifier:"experimental.console.listOrgs",summary:"List switchable Console orgs",description:"Get the available Console orgs across logged-in accounts, including the current active org."})),u.post("consoleSwitch",ft.consoleSwitch,{query:I,payload:$A,success:S(o.Boolean,"Switch success"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"experimental.console.switchOrg",summary:"Switch active Console org",description:"Persist a new active Console account/org selection for the current local OpenCode state."})),u.get("tool",ft.tool,{query:YA,success:S(QA,"Tools"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"tool.list",summary:"List tools",description:"Get a list of available tools with their JSON schema parameters for a specific provider and model combination."})),u.get("toolIDs",ft.toolIDs,{query:I,success:S(VA,"Tool IDs"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"tool.ids",summary:"List tool IDs",description:"Get a list of all available tool IDs, including both built-in tools and dynamically registered tools."})),u.get("worktree",ft.worktree,{query:I,success:S(KA,"List of worktree directories"),error:cn}).annotateMerge(d.annotations({identifier:"worktree.list",summary:"List worktrees",description:"List all sandbox worktrees for the current project."})),u.post("worktreeCreate",ft.worktree,{disableCodecs:!0,query:I,payload:[k.NoContent,lr.CreateInput],success:S(lr.Info,"Worktree created"),error:cn}).annotateMerge(d.annotations({identifier:"worktree.create",summary:"Create worktree",description:"Create a new git worktree for the current project and run any configured startup scripts."})),u.delete("worktreeRemove",ft.worktree,{query:I,payload:lr.RemoveInput,success:S(o.Boolean,"Worktree removed"),error:cn}).annotateMerge(d.annotations({identifier:"worktree.remove",summary:"Remove worktree",description:"Remove a git worktree and delete its branch."})),u.post("worktreeReset",ft.worktreeReset,{query:I,payload:lr.ResetInput,success:S(o.Boolean,"Worktree reset"),error:cn}).annotateMerge(d.annotations({identifier:"worktree.reset",summary:"Reset worktree",description:"Reset a worktree branch to the primary default branch."})),u.get("session",ft.session,{query:JA,success:S(o.Array(X.GlobalInfo),"List of sessions")}).annotateMerge(d.annotations({identifier:"experimental.session.list",summary:"List sessions",description:"Get a list of all OpenCode sessions across projects, sorted by most recently updated. Archived sessions are excluded by default."})),u.post("sessionBackground",ft.sessionBackground,{params:{sessionID:Y},query:I,success:S(o.Boolean,"Backgrounded subagents"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"experimental.session.background",summary:"Background subagents",description:"Detach any synchronous subagents currently blocking the session and continue them in the background."})),u.get("resource",ft.resource,{query:I,success:S(o.Record(o.String,qe.Resource),"MCP resources")}).annotateMerge(d.annotations({identifier:"experimental.resource.list",summary:"Get MCP resources",description:"Get all available MCP resources from connected servers. Optionally filter by name."}))).annotateMerge(d.annotations({title:"experimental",description:"Experimental HttpApi read-only routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var Kf=o.Struct({...xe,path:o.String}),ZA=o.Struct({...xe,pattern:o.String}),eI=o.Struct({...xe,query:o.String,dirs:o.optional(o.Literals(["true","false"])),type:o.optional(o.Literals(["file","directory"])),limit:o.optional(o.NumberFromString.check(o.isInt(),o.isGreaterThanOrEqualTo(1),o.isLessThanOrEqualTo(200)))}),tI=o.Struct({...xe,query:o.String}),rI=o.Struct({path:o.Struct({text:o.String}),lines:o.Struct({text:o.String}),line_number:Ae,absolute_offset:Ae,submatches:o.Array(o.Struct({match:o.Struct({text:o.String}),start:Ae,end:Ae}))}),nI=o.Struct({name:o.String,path:o.String,absolute:o.String,type:o.Literals(["file","directory"]),ignored:o.Boolean}).annotate({identifier:"FileNode"}),oI=o.Struct({type:o.Literals(["text","binary"]),content:o.String,diff:o.optional(o.String),patch:o.optional(o.Struct({oldFileName:o.String,newFileName:o.String,oldHeader:o.optional(o.String),newHeader:o.optional(o.String),hunks:o.Array(o.Struct({oldStart:Ae,oldLines:Ae,newStart:Ae,newLines:Ae,lines:o.Array(o.String)})),index:o.optional(o.String)})),encoding:o.optional(o.Literal("base64")),mimeType:o.optional(o.String)}).annotate({identifier:"FileContent"}),sI=o.Struct({path:o.String,added:Ae,removed:Ae,status:o.Literals(["added","deleted","modified"])}).annotate({identifier:"File"}),Fo={findText:"/find",findFile:"/find/file",findSymbol:"/find/symbol",list:"/file",content:"/file/content",status:"/file/status"},Xf=U.make("file").add(H.make("file").add(u.get("findText",Fo.findText,{query:ZA,success:S(o.Array(rI),"Matches")}).annotateMerge(d.annotations({identifier:"find.text",summary:"Find text",description:"Search for text patterns across files in the project using ripgrep."})),u.get("findFile",Fo.findFile,{query:eI,success:S(o.Array(o.String),"File paths")}).annotateMerge(d.annotations({identifier:"find.files",summary:"Find files",description:"Search for files or directories by name or pattern in the project directory."})),u.get("findSymbol",Fo.findSymbol,{query:tI,success:S(o.Array(Xr.Symbol),"Symbols")}).annotateMerge(d.annotations({identifier:"find.symbols",summary:"Find symbols",description:"Search for workspace symbols like functions, classes, and variables using LSP."})),u.get("list",Fo.list,{query:Kf,success:S(o.Array(nI),"Files and directories")}).annotateMerge(d.annotations({identifier:"file.list",summary:"List files",description:"List files and directories in a specified path."})),u.get("content",Fo.content,{query:Kf,success:S(oI,"File content")}).annotateMerge(d.annotations({identifier:"file.read",summary:"Read file",description:"Read the content of a specified file."})),u.get("status",Fo.status,{query:I,success:S(o.Array(sI),"File status")}).annotateMerge(d.annotations({identifier:"file.status",summary:"Get file status",description:"Get the git status of all files in the project."}))).annotateMerge(d.annotations({title:"file",description:"Experimental HttpApi file routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var iI=o.Struct({home:o.String,state:o.String,config:o.String,worktree:o.String,directory:o.String}).annotate({identifier:"Path"}),aI=o.Struct({...xe,mode:at.Mode,context:o.optional(o.NumberFromString.check(o.isInt(),o.isGreaterThanOrEqualTo(0)))}),kr=class extends o.ErrorClass("VcsApplyError")({name:o.Literal("VcsApplyError"),data:o.Struct({message:o.String,reason:o.Literals(["non-git","not-clean"])})},{httpApiStatus:400}){static{i(this,"ApiVcsApplyError")}},Rt={dispose:"/instance/dispose",path:"/path",vcs:"/vcs",vcsStatus:"/vcs/status",vcsDiff:"/vcs/diff",vcsDiffRaw:"/vcs/diff/raw",vcsApply:"/vcs/apply",command:"/command",agent:"/agent",skill:"/skill",lsp:"/lsp",formatter:"/formatter"},Jf=U.make("instance").add(H.make("instance").add(u.post("dispose",Rt.dispose,{query:I,success:S(o.Boolean,"Instance disposed")}).annotateMerge(d.annotations({identifier:"instance.dispose",summary:"Dispose instance",description:"Clean up and dispose the current OpenCode instance, releasing all resources."})),u.get("path",Rt.path,{query:I,success:iI}).annotateMerge(d.annotations({identifier:"path.get",summary:"Get paths",description:"Retrieve the current working directory and related path information for the OpenCode instance."})),u.get("vcs",Rt.vcs,{query:I,success:S(at.Info,"VCS info")}).annotateMerge(d.annotations({identifier:"vcs.get",summary:"Get VCS info",description:"Retrieve version control system (VCS) information for the current project, such as git branch."})),u.get("vcsStatus",Rt.vcsStatus,{query:I,success:S(o.Array(at.FileStatus),"VCS status")}).annotateMerge(d.annotations({identifier:"vcs.status",summary:"Get VCS status",description:"Retrieve changed files in the current working tree without patches."})),u.get("vcsDiff",Rt.vcsDiff,{query:aI,success:S(o.Array(at.FileDiff),"VCS diff")}).annotateMerge(d.annotations({identifier:"vcs.diff",summary:"Get VCS diff",description:"Retrieve the current git diff for the working tree or against the default branch."})),u.get("vcsDiffRaw",Rt.vcsDiffRaw,{query:I,success:S(o.String.pipe(k.asText({contentType:"text/x-diff; charset=utf-8"})),"Raw VCS diff")}).annotateMerge(d.annotations({identifier:"vcs.diff.raw",summary:"Get raw VCS diff",description:"Retrieve a raw patch for current uncommitted changes."})),u.post("vcsApply",Rt.vcsApply,{query:I,payload:at.ApplyInput,success:S(at.ApplyResult,"VCS patch applied"),error:kr}).annotateMerge(d.annotations({identifier:"vcs.apply",summary:"Apply VCS patch",description:"Apply a raw patch to the current working tree."})),u.get("command",Rt.command,{query:I,success:S(o.Array(Jr.Info),"List of commands")}).annotateMerge(d.annotations({identifier:"command.list",summary:"List commands",description:"Get a list of all available commands in the OpenCode system."})),u.get("agent",Rt.agent,{query:I,success:S(o.Array(zt.Info),"List of agents")}).annotateMerge(d.annotations({identifier:"app.agents",summary:"List agents",description:"Get a list of all available AI agents in the OpenCode system."})),u.get("skill",Rt.skill,{query:I,success:S(o.Array(So.Info),"List of skills")}).annotateMerge(d.annotations({identifier:"app.skills",summary:"List skills",description:"Get a list of all available skills in the OpenCode system."})),u.get("lsp",Rt.lsp,{query:I,success:S(o.Array(Xr.Status),"LSP server status")}).annotateMerge(d.annotations({identifier:"lsp.status",summary:"Get LSP status",description:"Get LSP server status"})),u.get("formatter",Rt.formatter,{query:I,success:S(o.Array(Io.Status),"Formatter status")}).annotateMerge(d.annotations({identifier:"formatter.status",summary:"Get formatter status",description:"Get formatter status"}))).annotateMerge(d.annotations({title:"instance",description:"Experimental HttpApi instance read routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var cI=o.Struct({name:o.String,config:ju.Info}),Lp=o.Record(o.String,qe.Status),pI=o.Struct({authorizationUrl:o.String,oauthState:o.String}),dI=o.Struct({code:o.String}),uI=o.Struct({success:o.Literal(!0)}),Kn=class extends o.ErrorClass("McpUnsupportedOAuthError")({error:o.String},{httpApiStatus:400}){static{i(this,"UnsupportedOAuthError")}},pn={status:"/mcp",auth:"/mcp/:name/auth",authCallback:"/mcp/:name/auth/callback",authAuthenticate:"/mcp/:name/auth/authenticate",connect:"/mcp/:name/connect",disconnect:"/mcp/:name/disconnect"},Zf=U.make("mcp").add(H.make("mcp").add(u.get("status",pn.status,{query:I,success:S(o.Record(o.String,qe.Status),"MCP server status")}).annotateMerge(d.annotations({identifier:"mcp.status",summary:"Get MCP status",description:"Get the status of all Model Context Protocol (MCP) servers."})),u.post("add",pn.status,{query:I,payload:cI,success:S(Lp,"MCP server added successfully"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"mcp.add",summary:"Add MCP server",description:"Dynamically add a new Model Context Protocol (MCP) server to the system."})),u.post("authStart",pn.auth,{params:{name:o.String},query:I,success:S(pI,"OAuth flow started"),error:[Kn,_e]}).annotateMerge(d.annotations({identifier:"mcp.auth.start",summary:"Start MCP OAuth",description:"Start OAuth authentication flow for a Model Context Protocol (MCP) server."})),u.post("authCallback",pn.authCallback,{params:{name:o.String},query:I,payload:dI,success:S(qe.Status,"OAuth authentication completed"),error:[D.BadRequest,_e]}).annotateMerge(d.annotations({identifier:"mcp.auth.callback",summary:"Complete MCP OAuth",description:"Complete OAuth authentication for a Model Context Protocol (MCP) server using the authorization code."})),u.post("authAuthenticate",pn.authAuthenticate,{params:{name:o.String},query:I,success:S(qe.Status,"OAuth authentication completed"),error:[Kn,_e]}).annotateMerge(d.annotations({identifier:"mcp.auth.authenticate",summary:"Authenticate MCP OAuth",description:"Start OAuth flow and wait for callback (opens browser)."})),u.delete("authRemove",pn.auth,{params:{name:o.String},query:I,success:S(uI,"OAuth credentials removed"),error:_e}).annotateMerge(d.annotations({identifier:"mcp.auth.remove",summary:"Remove MCP OAuth",description:"Remove OAuth credentials for an MCP server."})),u.post("connect",pn.connect,{params:{name:o.String},query:I,success:S(o.Boolean,"MCP server connected successfully"),error:_e}).annotateMerge(d.annotations({identifier:"mcp.connect",description:"Connect an MCP server."})),u.post("disconnect",pn.disconnect,{params:{name:o.String},query:I,success:S(o.Boolean,"MCP server disconnected successfully"),error:_e}).annotateMerge(d.annotations({identifier:"mcp.disconnect",description:"Disconnect an MCP server."}))).annotateMerge(d.annotations({title:"mcp",description:"Experimental HttpApi MCP routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var ey="/permission",mI=o.Struct({reply:zr.Reply,message:o.optional(o.String)}),ty=U.make("permission").add(H.make("permission").add(u.get("list",ey,{query:I,success:S(o.Array(zr.Request),"List of pending permissions")}).annotateMerge(d.annotations({identifier:"permission.list",summary:"List pending permissions",description:"Get all pending permission requests across all sessions."})),u.post("reply",`${ey}/:requestID/reply`,{params:{requestID:zr.ID},query:I,payload:mI,success:S(o.Boolean,"Permission processed successfully"),error:[D.BadRequest,sr]}).annotateMerge(d.annotations({identifier:"permission.reply",summary:"Respond to permission request",description:"Approve or deny a permission request from the AI assistant."}))).annotateMerge(d.annotations({title:"permission",description:"Experimental HttpApi permission routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var ii="/project",lI=o.Struct({name:o.optional(o.String),icon:o.optional(it.Info.fields.icon),commands:o.optional(it.Info.fields.commands)}),ry=U.make("project").add(H.make("project").add(u.get("list",ii,{query:I,success:S(o.Array(it.Info),"List of projects")}).annotateMerge(d.annotations({identifier:"project.list",summary:"List all projects",description:"Get a list of projects that have been opened with OpenCode."})),u.get("current",`${ii}/current`,{query:I,success:S(it.Info,"Current project information")}).annotateMerge(d.annotations({identifier:"project.current",summary:"Get current project",description:"Retrieve the currently active project that OpenCode is working with."})),u.post("initGit",`${ii}/git/init`,{query:I,success:S(it.Info,"Project information after git initialization")}).annotateMerge(d.annotations({identifier:"project.initGit",summary:"Initialize git repository",description:"Create a git repository for the current project and return the refreshed project info."})),u.patch("update",`${ii}/:projectID`,{params:{projectID:Fe.ID},query:I,payload:lI,success:S(it.Info,"Updated project information"),error:[D.BadRequest,Uo]}).annotateMerge(d.annotations({identifier:"project.update",summary:"Update project",description:"Update project properties such as name, icon, and commands."})),u.get("directories",`${ii}/:projectID/directories`,{params:{projectID:Fe.ID},query:I,success:S(Fe.Directories,"Project directories")}).annotateMerge(d.annotations({identifier:"project.directories",summary:"List project directories",description:"List known local absolute directories for a project."}))).annotateMerge(d.annotations({title:"project",description:"Experimental HttpApi project routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var fI=o.Struct({context:o.optional(o.String)}),ny=U.make("projectCopyName").add(H.make("projectCopyName").add(u.post("generateName","/experimental/project/:projectID/copy/generate-name",{params:{projectID:Fe.ID},query:I,payload:fI,success:o.Struct({name:o.String})}).annotateMerge(d.annotations({identifier:"experimental.projectCopy.generateName",summary:"Generate project copy name",description:"Generate a short name for a project copy from task context."}))).annotateMerge(d.annotations({title:"projectCopy",description:"Project copy naming routes."})).middleware($).middleware(W).middleware(j));var Wa="/provider",yI=o.Union([o.Literal("BadRequest"),o.Literal("ProviderAuthOauthMissing"),o.Literal("ProviderAuthOauthCodeMissing"),o.Literal("ProviderAuthOauthCallbackFailed"),o.Literal("ProviderAuthValidationFailed")]),Ut=class extends o.ErrorClass("ProviderAuthError")({name:yI,data:o.Struct({providerID:o.optional(kt.ID),field:o.optional(o.String),message:o.optional(o.String),kind:o.optional(o.String)})},{httpApiStatus:400}){static{i(this,"ProviderAuthApiError")}},oy=U.make("provider").add(H.make("provider").add(u.get("list",Wa,{query:I,success:S(Me.ListResult,"List of providers")}).annotateMerge(d.annotations({identifier:"provider.list",summary:"List providers",description:"Get a list of all available AI providers, including both available and connected ones."})),u.get("auth",`${Wa}/auth`,{query:I,success:S(Xe.Methods,"Provider auth methods")}).annotateMerge(d.annotations({identifier:"provider.auth",summary:"Get provider auth methods",description:"Retrieve available authentication methods for all AI providers."})),u.post("authorize",`${Wa}/:providerID/oauth/authorize`,{params:{providerID:kt.ID},query:I,payload:Xe.AuthorizeInput,success:S(o.UndefinedOr(Xe.Authorization),"Authorization URL and method"),error:Ut}).annotateMerge(d.annotations({identifier:"provider.oauth.authorize",summary:"Start OAuth authorization",description:"Start the OAuth authorization flow for a provider."})),u.post("callback",`${Wa}/:providerID/oauth/callback`,{params:{providerID:kt.ID},query:I,payload:Xe.CallbackInput,success:S(o.Boolean,"OAuth callback processed successfully"),error:Ut}).annotateMerge(d.annotations({identifier:"provider.oauth.callback",summary:"Handle OAuth callback",description:"Handle the OAuth callback from a provider after user authorization."}))).annotateMerge(d.annotations({title:"provider",description:"Experimental HttpApi provider routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var dn="/pty",gI=o.Struct({ptyID:yo}),sy=o.Struct({...xe,cursor:o.optional(o.String)}),hI=o.Struct({path:o.String,name:o.String,acceptable:o.Boolean}),un={shells:`${dn}/shells`,list:dn,create:dn,get:`${dn}/:ptyID`,update:`${dn}/:ptyID`,remove:`${dn}/:ptyID`,connectToken:`${dn}/:ptyID/connect-token`,connect:`${dn}/:ptyID/connect`},iy=U.make("pty").add(H.make("pty").add(u.get("shells",un.shells,{query:I,success:S(o.Array(hI),"List of shells")}).annotateMerge(d.annotations({identifier:"pty.shells",summary:"List available shells",description:"Get a list of available shells on the system."})),u.get("list",un.list,{query:I,success:S(o.Array(he.Info),"List of sessions")}).annotateMerge(d.annotations({identifier:"pty.list",summary:"List PTY sessions",description:"Get a list of all active pseudo-terminal (PTY) sessions managed by OpenCode."})),u.post("create",un.create,{query:I,payload:he.CreateInput,success:S(he.Info,"Created session"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"pty.create",summary:"Create PTY session",description:"Create a new pseudo-terminal (PTY) session for running shell commands and processes."})),u.get("get",un.get,{params:{ptyID:yo},query:I,success:S(he.Info,"Session info"),error:Dt}).annotateMerge(d.annotations({identifier:"pty.get",summary:"Get PTY session",description:"Retrieve detailed information about a specific pseudo-terminal (PTY) session."})),u.put("update",un.update,{params:{ptyID:yo},query:I,payload:he.UpdateInput,success:S(he.Info,"Updated session"),error:[Dt,D.BadRequest]}).annotateMerge(d.annotations({identifier:"pty.update",summary:"Update PTY session",description:"Update properties of an existing pseudo-terminal (PTY) session."})),u.delete("remove",un.remove,{params:{ptyID:yo},query:I,success:S(o.Boolean,"Session removed"),error:Dt}).annotateMerge(d.annotations({identifier:"pty.remove",summary:"Remove PTY session",description:"Remove and terminate a specific pseudo-terminal (PTY) session."})),u.post("connectToken",un.connectToken,{params:{ptyID:yo},query:I,success:S(wt.ConnectToken,"WebSocket connect token"),error:[Lo,Dt]}).annotateMerge(d.annotations({identifier:"pty.connectToken",summary:"Create PTY WebSocket token",description:"Create a short-lived ticket for opening a PTY WebSocket connection."}))).annotateMerge(d.annotations({title:"pty",description:"Experimental HttpApi PTY routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."})),jo=U.make("pty-connect").add(H.make("pty-connect").add(u.get("connect",un.connect,{params:gI,success:S(o.Boolean,"Connected session"),error:[D.Forbidden,D.NotFound]}).annotateMerge(d.annotations({identifier:"pty.connect",summary:"Connect to PTY session",description:"Establish a WebSocket connection to interact with a pseudo-terminal (PTY) session in real-time.",transform:i(t=>({...t,parameters:[...t.parameters??[],...["directory","workspace","cursor",ti].map(e=>({in:"query",name:e,schema:{type:"string"}}))]}),"transform")}))).annotateMerge(d.annotations({title:"pty",description:"PTY websocket route."})).middleware($).middleware(W).middleware(zn));var Up="/question",SI=o.Struct({answers:o.Array($t.Answer).annotate({description:"User answers in order of questions (each answer is an array of selected labels)"})}),ay=U.make("question").add(H.make("question").add(u.get("list",Up,{query:I,success:S(o.Array($t.Request),"List of pending questions")}).annotateMerge(d.annotations({identifier:"question.list",summary:"List pending questions",description:"Get all pending question requests across all sessions."})),u.post("reply",`${Up}/:requestID/reply`,{params:{requestID:Nc},query:I,payload:SI,success:S(o.Boolean,"Question answered successfully"),error:[D.BadRequest,an]}).annotateMerge(d.annotations({identifier:"question.reply",summary:"Reply to question request",description:"Provide answers to a question request from the AI assistant."})),u.post("reject",`${Up}/:requestID/reject`,{params:{requestID:Nc},query:I,success:S(o.Boolean,"Question rejected successfully"),error:[D.BadRequest,an]}).annotateMerge(d.annotations({identifier:"question.reject",summary:"Reject question request",description:"Reject a question request from the AI assistant."}))).annotateMerge(d.annotations({title:"question",description:"Question routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode HttpApi",version:"0.0.1",description:"Effect HttpApi surface for instance routes."}));var de="/session",vI=o.Struct({...xe,scope:o.optional(o.Literals(["project"])),path:o.optional(o.String),roots:o.optional(oi),start:o.optional(o.NumberFromString),search:o.optional(o.String),limit:o.optional(o.NumberFromString)}),EI=o.Struct({...xe,...ze.omit(Eo.DiffInput.fields,["sessionID"])}),AI=o.Struct({...xe,limit:o.optional(o.NumberFromString.check(o.isInt(),o.isGreaterThanOrEqualTo(0))),before:o.optional(o.String)}),II=o.Record(o.String,Kr.Info),wI=o.Struct({title:o.optional(o.String),metadata:o.optional(X.Metadata),permission:o.optional(zr.Ruleset),time:o.optional(o.Struct({archived:o.optional(X.ArchivedTimestamp)}))}),Np=o.Struct(ze.omit(X.ForkInput.fields,["sessionID"])),DI=o.Struct({modelID:us.ID,providerID:kt.ID,messageID:Yr}),RI=o.Struct({providerID:kt.ID,modelID:us.ID,auto:o.optional(o.Boolean)}),cy=o.Struct(ze.omit(Vt.PromptInput.fields,["sessionID"])),CI=o.Struct(ze.omit(Vt.CommandInput.fields,["sessionID"])),xI=o.Struct(ze.omit(Vt.ShellInput.fields,["sessionID"])),kI=o.Struct(ze.omit(Ao.RevertInput.fields,["sessionID"])),HI=o.Struct({response:zr.Reply}),ae={list:de,status:`${de}/status`,get:`${de}/:sessionID`,children:`${de}/:sessionID/children`,todo:`${de}/:sessionID/todo`,diff:`${de}/:sessionID/diff`,messages:`${de}/:sessionID/message`,message:`${de}/:sessionID/message/:messageID`,create:de,remove:`${de}/:sessionID`,update:`${de}/:sessionID`,fork:`${de}/:sessionID/fork`,abort:`${de}/:sessionID/abort`,share:`${de}/:sessionID/share`,init:`${de}/:sessionID/init`,summarize:`${de}/:sessionID/summarize`,prompt:`${de}/:sessionID/message`,promptAsync:`${de}/:sessionID/prompt_async`,command:`${de}/:sessionID/command`,shell:`${de}/:sessionID/shell`,revert:`${de}/:sessionID/revert`,unrevert:`${de}/:sessionID/unrevert`,permissions:`${de}/:sessionID/permissions/:permissionID`,deleteMessage:`${de}/:sessionID/message/:messageID`,deletePart:`${de}/:sessionID/message/:messageID/part/:partID`,updatePart:`${de}/:sessionID/message/:messageID/part/:partID`},py=U.make("session").add(H.make("session").add(u.get("list",ae.list,{query:vI,success:S(o.Array(X.Info),"List of sessions")}).annotateMerge(d.annotations({identifier:"session.list",summary:"List sessions",description:"Get a list of all OpenCode sessions, sorted by most recently updated."})),u.get("status",ae.status,{query:I,success:S(II,"Get session status"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"session.status",summary:"Get session status",description:"Retrieve the current status of all sessions, including active, idle, and completed states."})),u.get("get",ae.get,{params:{sessionID:Y},query:I,success:S(X.Info,"Get session"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.get",summary:"Get session",description:"Retrieve detailed information about a specific OpenCode session."})),u.get("children",ae.children,{params:{sessionID:Y},query:I,success:S(o.Array(X.Info),"List of children"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.children",summary:"Get session children",description:"Retrieve all child sessions that were forked from the specified parent session."})),u.get("todo",ae.todo,{params:{sessionID:Y},query:I,success:S(o.Array(vo.Info),"Todo list"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.todo",summary:"Get session todos",description:"Retrieve the todo list associated with a specific session, showing tasks and action items."})),u.get("diff",ae.diff,{params:{sessionID:Y},query:EI,success:S(o.Array(ua.FileDiff),"Successfully retrieved diff")}).annotateMerge(d.annotations({identifier:"session.diff",summary:"Get message diff",description:"Get the file changes (diff) that resulted from a specific user message in the session."})),u.get("messages",ae.messages,{params:{sessionID:Y},query:AI,success:S(o.Array(Vr.WithParts),"List of messages"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.messages",summary:"Get session messages",description:"Retrieve all messages in a session, including user prompts and AI responses."})),u.get("message",ae.message,{params:{sessionID:Y,messageID:Yr},query:I,success:S(Vr.WithParts,"Message"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.message",summary:"Get message",description:"Retrieve a specific message from a session by its message ID."})),u.post("create",ae.create,{query:I,payload:[k.NoContent,X.CreateInput],success:S(X.Info,"Successfully created session"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"session.create",summary:"Create session",description:"Create a new OpenCode session for interacting with AI assistants and managing conversations."})),u.delete("remove",ae.remove,{params:{sessionID:Y},query:I,success:S(o.Boolean,"Successfully deleted session"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.delete",summary:"Delete session",description:"Delete a session and permanently remove all associated data, including messages and history."})),u.patch("update",ae.update,{params:{sessionID:Y},query:I,payload:wI,success:S(X.Info,"Successfully updated session"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.update",summary:"Update session",description:"Update properties of an existing session, such as title or other metadata."})),u.post("fork",ae.fork,{params:{sessionID:Y},query:I,payload:[k.NoContent,Np],success:S(X.Info,"200"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.fork",summary:"Fork session",description:"Create a new session by forking an existing session at a specific message point."})),u.post("abort",ae.abort,{params:{sessionID:Y},query:I,success:S(o.Boolean,"Aborted session"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"session.abort",summary:"Abort session",description:"Abort an active session and stop any ongoing AI processing or command execution."})),u.post("init",ae.init,{params:{sessionID:Y},query:I,payload:DI,success:S(o.Boolean,"200"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.init",summary:"Initialize session",description:"Analyze the current application and create an AGENTS.md file with project-specific agent configurations."})),u.post("share",ae.share,{params:{sessionID:Y},query:I,success:S(X.Info,"Successfully shared session"),error:[D.InternalServerError,te]}).annotateMerge(d.annotations({identifier:"session.share",summary:"Share session",description:"Create a shareable link for a session, allowing others to view the conversation."})),u.delete("unshare",ae.share,{params:{sessionID:Y},query:I,success:S(X.Info,"Successfully unshared session"),error:[D.InternalServerError,te]}).annotateMerge(d.annotations({identifier:"session.unshare",summary:"Unshare session",description:"Remove the shareable link for a session, making it private again."})),u.post("summarize",ae.summarize,{params:{sessionID:Y},query:I,payload:RI,success:S(o.Boolean,"Summarized session"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.summarize",summary:"Summarize session",description:"Generate a concise summary of the session using AI compaction to preserve key information."})),u.post("prompt",ae.prompt,{params:{sessionID:Y},query:I,payload:cy,success:S(Vr.WithParts,"Created message"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.prompt",summary:"Send message",description:"Create and send a new message to a session, streaming the AI response."})),u.post("promptAsync",ae.promptAsync,{params:{sessionID:Y},query:I,payload:cy,success:S(k.NoContent,"Prompt accepted"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.prompt_async",summary:"Send async message",description:"Create and send a new message to a session asynchronously, starting the session if needed and returning immediately."})),u.post("command",ae.command,{params:{sessionID:Y},query:I,payload:CI,success:S(Vr.WithParts,"Created message"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"session.command",summary:"Send command",description:"Send a new command to a session for execution by the AI assistant."})),u.post("shell",ae.shell,{params:{sessionID:Y},query:I,payload:xI,success:S(Vr.WithParts,"Created message"),error:[D.BadRequest,te,xr]}).annotateMerge(d.annotations({identifier:"session.shell",summary:"Run shell command",description:"Execute a shell command within the session context and return the AI's response."})),u.post("revert",ae.revert,{params:{sessionID:Y},query:I,payload:kI,success:S(X.Info,"Updated session"),error:[D.BadRequest,te,xr]}).annotateMerge(d.annotations({identifier:"session.revert",summary:"Revert message",description:"Revert a specific message in a session, undoing its effects and restoring the previous state."})),u.post("unrevert",ae.unrevert,{params:{sessionID:Y},query:I,success:S(X.Info,"Updated session"),error:[D.BadRequest,te,xr]}).annotateMerge(d.annotations({identifier:"session.unrevert",summary:"Restore reverted messages",description:"Restore all previously reverted messages in a session."})),u.post("permissionRespond",ae.permissions,{params:{sessionID:Y,permissionID:zr.ID},query:I,payload:HI,success:S(o.Boolean,"Permission processed successfully"),error:[D.BadRequest,te,sr]}).annotateMerge(d.annotations({identifier:"permission.respond",summary:"Respond to permission",description:"Approve or deny a permission request from the AI assistant.",deprecated:!0})),u.delete("deleteMessage",ae.deleteMessage,{params:{sessionID:Y,messageID:Yr},query:I,success:S(o.Boolean,"Successfully deleted message"),error:[D.BadRequest,te,xr]}).annotateMerge(d.annotations({identifier:"session.deleteMessage",summary:"Delete message",description:"Permanently delete a specific message and all of its parts from a session without reverting file changes."})),u.delete("deletePart",ae.deletePart,{params:{sessionID:Y,messageID:Yr,partID:Uc},query:I,success:S(o.Boolean,"Successfully deleted part"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"part.delete",description:"Delete a part from a message."})),u.patch("updatePart",ae.updatePart,{params:{sessionID:Y,messageID:Yr,partID:Uc},query:I,payload:Vr.Part,success:S(Vr.Part,"Successfully updated part"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"part.update",description:"Update a part in a message."}))).annotateMerge(d.annotations({title:"session",description:"Experimental HttpApi session routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var $a="/sync",PI=o.Struct({id:le.ID,aggregateID:o.String,seq:Ae,type:o.String,data:o.Record(o.String,o.Unknown)}),TI=o.Struct({directory:o.String,events:o.NonEmptyArray(PI)}),bI=o.Struct({sessionID:o.String}),dy=o.Struct({sessionID:Y}),qI=o.Record(o.String,Ae),MI=o.Struct({id:le.ID,aggregate_id:o.String,seq:Ae,type:o.String,data:o.Record(o.String,o.Unknown)}),Va={start:`${$a}/start`,replay:`${$a}/replay`,steal:`${$a}/steal`,history:`${$a}/history`},uy=U.make("sync").add(H.make("sync").add(u.post("start",Va.start,{query:I,success:S(o.Boolean,"Workspace sync started")}).annotateMerge(d.annotations({identifier:"sync.start",summary:"Start workspace sync",description:"Start sync loops for workspaces in the current project that have active sessions."})),u.post("replay",Va.replay,{query:I,payload:TI,success:S(bI,"Replayed sync events"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"sync.replay",summary:"Replay sync events",description:"Validate and replay a complete sync event history."})),u.post("steal",Va.steal,{query:I,payload:dy,success:S(dy,"Session stolen into workspace"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"sync.steal",summary:"Steal session into workspace",description:"Update a session to belong to the current workspace through the sync event system."})),u.post("history",Va.history,{query:I,payload:qI,success:S(o.Array(MI),"Sync events"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"sync.history.list",summary:"List sync events",description:"List sync events for all aggregates. Keys are aggregate IDs the client already knows about, values are the last known sequence ID. Events with seq > value are returned for those aggregates. Aggregates not listed in the input get their full history."}))).annotateMerge(d.annotations({title:"sync",description:"Experimental HttpApi sync routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var ai=class{static{i(this,"AsyncQueue")}queue=[];resolvers=[];push(e){let r=this.resolvers.shift();r?r(e):this.queue.push(e)}async next(){return this.queue.length>0?this.queue.shift():new Promise(e=>this.resolvers.push(e))}async*[Symbol.asyncIterator](){for(;;)yield await this.next()}};var my=o.Struct({path:o.String,body:o.Unknown}),OI=new ai,LI=new ai;function ly(){return OI.next()}i(ly,"nextTuiRequest");function fy(t){LI.push(t)}i(fy,"submitTuiResponse");var yt="/tui",UI=o.Struct({command:o.String}),NI=o.Struct({type:o.Literal(ie.PromptAppend.type),properties:ie.PromptAppend.data}).annotate({identifier:"EventTuiPromptAppend"}),_I=o.Struct({type:o.Literal(ie.CommandExecute.type),properties:ie.CommandExecute.data}).annotate({identifier:"EventTuiCommandExecute"}),BI=o.Struct({type:o.Literal(ie.ToastShow.type),properties:ie.ToastShow.data}).annotate({identifier:"EventTuiToastShow"}),FI=o.Struct({type:o.Literal(ie.SessionSelect.type),properties:ie.SessionSelect.data}).annotate({identifier:"EventTuiSessionSelect"}),jI=o.Union([NI,_I,BI,FI]),gt={appendPrompt:`${yt}/append-prompt`,openHelp:`${yt}/open-help`,openSessions:`${yt}/open-sessions`,openThemes:`${yt}/open-themes`,openModels:`${yt}/open-models`,submitPrompt:`${yt}/submit-prompt`,clearPrompt:`${yt}/clear-prompt`,executeCommand:`${yt}/execute-command`,showToast:`${yt}/show-toast`,publish:`${yt}/publish`,selectSession:`${yt}/select-session`,controlNext:`${yt}/control/next`,controlResponse:`${yt}/control/response`},yy=U.make("tui").add(H.make("tui").add(u.post("appendPrompt",gt.appendPrompt,{query:I,payload:ie.PromptAppend.data,success:S(o.Boolean,"Prompt processed successfully"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"tui.appendPrompt",summary:"Append TUI prompt",description:"Append prompt to the TUI."})),u.post("openHelp",gt.openHelp,{query:I,success:S(o.Boolean,"Help dialog opened successfully")}).annotateMerge(d.annotations({identifier:"tui.openHelp",summary:"Open help dialog",description:"Open the help dialog in the TUI to display user assistance information."})),u.post("openSessions",gt.openSessions,{query:I,success:S(o.Boolean,"Session dialog opened successfully")}).annotateMerge(d.annotations({identifier:"tui.openSessions",summary:"Open sessions dialog",description:"Open the session dialog."})),u.post("openThemes",gt.openThemes,{query:I,success:S(o.Boolean,"Theme dialog opened successfully")}).annotateMerge(d.annotations({identifier:"tui.openThemes",summary:"Open themes dialog",description:"Open the theme dialog."})),u.post("openModels",gt.openModels,{query:I,success:S(o.Boolean,"Model dialog opened successfully")}).annotateMerge(d.annotations({identifier:"tui.openModels",summary:"Open models dialog",description:"Open the model dialog."})),u.post("submitPrompt",gt.submitPrompt,{query:I,success:S(o.Boolean,"Prompt submitted successfully")}).annotateMerge(d.annotations({identifier:"tui.submitPrompt",summary:"Submit TUI prompt",description:"Submit the prompt."})),u.post("clearPrompt",gt.clearPrompt,{query:I,success:S(o.Boolean,"Prompt cleared successfully")}).annotateMerge(d.annotations({identifier:"tui.clearPrompt",summary:"Clear TUI prompt",description:"Clear the prompt."})),u.post("executeCommand",gt.executeCommand,{query:I,payload:UI,success:S(o.Boolean,"Command executed successfully"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"tui.executeCommand",summary:"Execute TUI command",description:"Execute a TUI command."})),u.post("showToast",gt.showToast,{query:I,payload:ie.ToastShow.data,success:S(o.Boolean,"Toast notification shown successfully")}).annotateMerge(d.annotations({identifier:"tui.showToast",summary:"Show TUI toast",description:"Show a toast notification in the TUI."})),u.post("publish",gt.publish,{query:I,payload:jI,success:S(o.Boolean,"Event published successfully"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"tui.publish",summary:"Publish TUI event",description:"Publish a TUI event."})),u.post("selectSession",gt.selectSession,{query:I,payload:ie.SessionSelect.data,success:S(o.Boolean,"Session selected successfully"),error:[D.BadRequest,te]}).annotateMerge(d.annotations({identifier:"tui.selectSession",summary:"Select session",description:"Navigate the TUI to display the specified session."})),u.get("controlNext",gt.controlNext,{query:I,success:S(my,"Next TUI request")}).annotateMerge(d.annotations({identifier:"tui.control.next",summary:"Get next TUI request",description:"Retrieve the next TUI request from the queue for processing."})),u.post("controlResponse",gt.controlResponse,{query:I,payload:o.Unknown,success:S(o.Boolean,"Response submitted successfully")}).annotateMerge(d.annotations({identifier:"tui.control.response",summary:"Submit TUI response",description:"Submit a response to the TUI request queue to complete a pending request."}))).annotateMerge(d.annotations({title:"tui",description:"Experimental HttpApi TUI routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var Go="/experimental/workspace",GI=o.Struct(ze.omit(fe.CreateInput.fields,["projectID"])),WI=o.Struct({id:o.NullOr(fe.Info.fields.id),sessionID:fe.SessionWarpInput.fields.sessionID,copyChanges:fe.SessionWarpInput.fields.copyChanges}),ci=class extends o.ErrorClass("WorkspaceWarpError")({name:o.Literal("WorkspaceWarpError"),data:o.Struct({message:o.String})},{httpApiStatus:400}){static{i(this,"ApiWorkspaceWarpError")}},pi=class extends o.ErrorClass("WorkspaceCreateError")({name:o.Literal("WorkspaceCreateError"),data:o.Struct({message:o.String})},{httpApiStatus:400}){static{i(this,"ApiWorkspaceCreateError")}},Xn={adapters:`${Go}/adapter`,list:Go,syncList:`${Go}/sync-list`,status:`${Go}/status`,remove:`${Go}/:id`,warp:`${Go}/warp`},gy=U.make("workspace").add(H.make("workspace").add(u.get("adapters",Xn.adapters,{query:I,success:S(o.Array(ym),"Workspace adapters")}).annotateMerge(d.annotations({identifier:"experimental.workspace.adapter.list",summary:"List workspace adapters",description:"List all available workspace adapters for the current project."})),u.get("list",Xn.list,{query:I,success:S(o.Array(fe.Info),"Workspaces")}).annotateMerge(d.annotations({identifier:"experimental.workspace.list",summary:"List workspaces",description:"List all workspaces."})),u.post("create",Xn.list,{query:I,payload:GI,success:S(fe.Info,"Workspace created"),error:[pi,D.BadRequest]}).annotateMerge(d.annotations({identifier:"experimental.workspace.create",summary:"Create workspace",description:"Create a workspace for the current project."})),u.post("syncList",Xn.syncList,{query:I,success:S(k.NoContent,"Workspace list synced")}).annotateMerge(d.annotations({identifier:"experimental.workspace.syncList",summary:"Sync workspace list",description:"Register missing workspaces returned by workspace adapters."})),u.get("status",Xn.status,{query:I,success:S(o.Array(fe.ConnectionStatus),"Workspace status")}).annotateMerge(d.annotations({identifier:"experimental.workspace.status",summary:"Workspace status",description:"Get connection status for workspaces in the current project."})),u.delete("remove",Xn.remove,{params:{id:fe.Info.fields.id},query:I,success:S(o.UndefinedOr(fe.Info),"Workspace removed"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"experimental.workspace.remove",summary:"Remove workspace",description:"Remove an existing workspace."})),u.post("warp",Xn.warp,{query:I,payload:WI,success:S(k.NoContent,"Session warped"),error:[ci,kr,te]}).annotateMerge(d.annotations({identifier:"experimental.workspace.warp",summary:"Warp session into workspace",description:"Move a session's sync history into the target workspace, or detach it to the local project."}))).annotateMerge(d.annotations({title:"workspace",description:"Experimental HttpApi workspace routes."})).middleware($).middleware(W).middleware(j)).annotateMerge(d.annotations({title:"opencode experimental HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."}));var Jn=class extends ye.Service()("@opencode/HttpApiSchemaError",{error:Pe}){static{i(this,"SchemaErrorMiddleware")}};var $I=o.Struct({limit:o.optional(o.NumberFromString.check(o.isInt(),o.isGreaterThanOrEqualTo(1),o.isLessThanOrEqualTo(200))).annotate({description:"Maximum number of messages to return. When omitted, the endpoint returns its default page size."}),order:o.optional(o.Union([o.Literal("asc"),o.Literal("desc")])).annotate({description:"Message order for the first page. Use desc for newest first or asc for oldest first."}),cursor:o.optional(o.String.annotate({description:"Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response. Do not combine with order."}))}).annotate({identifier:"SessionMessagesQuery"}),hy=H.make("server.message").add(u.get("session.messages","/api/session/:sessionID/message",{params:{sessionID:K.ID},query:$I,success:o.Struct({data:o.Array(jr.Message),cursor:o.Struct({previous:o.String.pipe(o.optional),next:o.String.pipe(o.optional)})}).annotate({identifier:"SessionMessagesResponse"}),error:[Lt,N,tt]}).annotateMerge(d.annotations({identifier:"v2.session.messages",summary:"Get session messages",description:"Retrieve projected messages for a session. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline."}))).annotateMerge(d.annotations({title:"messages",description:"Experimental message routes."}));var Sy=H.make("server.model").add(u.get("model.list","/api/model",{query:_,success:z.response(o.Array(ds.Info)),error:mt}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.model.list",summary:"List models",description:"Retrieve available models ordered by release date."}))).annotateMerge(d.annotations({title:"models",description:"Experimental model routes."}));var vy=H.make("server.provider").add(u.get("provider.list","/api/provider",{query:_,success:z.response(o.Array(Qi.Info)),error:mt}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.provider.list",summary:"List providers",description:"Retrieve active AI providers so clients can show provider availability and configuration."}))).add(u.get("provider.get","/api/provider/:providerID",{params:{providerID:Qi.ID},query:_,success:z.response(Qi.Info),error:[Mo,mt]}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.provider.get",summary:"Get provider",description:"Retrieve a single AI provider so clients can inspect its availability and endpoint settings."}))).annotateMerge(d.annotations({title:"providers",description:"Experimental provider routes."}));var za={workspace:Vu.ID.pipe(o.optional),limit:o.NumberFromString.pipe(o.decodeTo(In),o.optional).annotate({description:"Maximum number of sessions to return. Defaults to the newest 50 sessions."}),order:o.optional(o.Union([o.Literal("asc"),o.Literal("desc")])).annotate({description:"Session order for the first page. Use desc for newest first or asc for oldest first."}),search:o.optional(o.String)},VI=o.Struct({...za,directory:Ie}),zI=o.Struct({...za,project:Ht.ID,subpath:vt.pipe(o.optional)}),QI=o.Struct(za),_p=i(t=>t.mapFields(e=>({...ze.omit(e,["limit"]),anchor:K.ListAnchor})),"withCursor"),YI=o.Union([_p(VI),_p(zI),_p(QI)]),Ay=o.fromJsonString(YI),KI=o.encodeSync(Ay),XI=o.decodeUnknownEffect(Ay),Ey="Invalid cursor",Zn=o.String.pipe(o.brand("SessionsCursor"),Du(t=>{let e=t.make.bind(t);return{make:i(r=>e(Lr.encodeBase64Url(KI(r))),"make"),parse:i(r=>s.suspend(()=>{let n=Lr.decodeBase64UrlString(r);return sc.isFailure(n)?s.fail(Ey):XI(n.success).pipe(s.mapError(()=>Ey))}),"parse")}})),JI=o.Struct({type:o.Literal("running")}).annotate({identifier:"SessionActive"}),ZI=In.check(o.isLessThanOrEqualTo(100)),ew=o.Struct({limit:o.NumberFromString.pipe(o.decodeTo(ZI),o.optional),after:o.NumberFromString.pipe(o.decodeTo(Ae),o.optional)}),tw=Zn.annotate({description:"Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response."}),rw=o.Struct({...za,directory:Ie.pipe(o.optional),project:Ht.ID.pipe(o.optional),subpath:vt.pipe(o.optional),cursor:tw.pipe(o.optional)}).annotate({identifier:"SessionsQuery"}),Iy=i(t=>H.make("server.session").add(u.get("session.list","/api/session",{query:rw,success:o.Struct({data:o.Array(K.Info),cursor:o.Struct({previous:Zn.pipe(o.optional),next:Zn.pipe(o.optional)})}).annotate({identifier:"SessionsResponse"}),error:[Lt,Pe]}).annotateMerge(d.annotations({identifier:"v2.session.list",summary:"List sessions",description:"Retrieve sessions in the requested order. Items keep that order across pages; use cursor.next or cursor.previous to move through the ordered list."}))).add(u.post("session.create","/api/session",{payload:o.Struct({id:K.ID.pipe(o.optional),agent:wn.ID.pipe(o.optional),model:ds.Ref.pipe(o.optional),location:z.Ref.pipe(o.optional)}),success:o.Struct({data:K.Info})}).annotateMerge(d.annotations({identifier:"v2.session.create",summary:"Create session",description:"Create a session at the requested location."}))).add(u.get("session.active","/api/session/active",{success:o.Struct({data:o.Record(K.ID,JI)})}).annotateMerge(d.annotations({identifier:"v2.session.active",summary:"List active sessions",description:"Retrieve foreground Session drains currently owned by this OpenCode process. Sessions absent from the result are inactive."}))).add(u.get("session.get","/api/session/:sessionID",{params:{sessionID:K.ID},success:o.Struct({data:K.Info}),error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.get",summary:"Get session",description:"Retrieve a session by ID."}))).add(u.post("session.switchAgent","/api/session/:sessionID/agent",{params:{sessionID:K.ID},payload:o.Struct({agent:wn.ID}),success:k.NoContent,error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.switchAgent",summary:"Switch session agent",description:"Switch the agent used by subsequent provider turns."}))).add(u.post("session.switchModel","/api/session/:sessionID/model",{params:{sessionID:K.ID},payload:o.Struct({model:ds.Ref}),success:k.NoContent,error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.switchModel",summary:"Switch session model",description:"Switch the model used by subsequent provider turns."}))).add(u.post("session.prompt","/api/session/:sessionID/prompt",{params:{sessionID:K.ID},payload:o.Struct({id:jr.ID.pipe(o.optional),prompt:Qu.Prompt,delivery:bc.Delivery.pipe(o.optional),resume:o.Boolean.pipe(o.optional)}),success:o.Struct({data:bc.Admitted}),error:[qo,N]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.prompt",summary:"Send message",description:"Durably admit one session input and schedule agent-loop execution unless resume is false."}))).add(u.post("session.compact","/api/session/:sessionID/compact",{params:{sessionID:K.ID},success:k.NoContent,error:[N,mt]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.compact",summary:"Compact session",description:"Compact a session conversation."}))).add(u.post("session.wait","/api/session/:sessionID/wait",{params:{sessionID:K.ID},success:k.NoContent,error:[N,mt]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.wait",summary:"Wait for session",description:"Wait for a session agent loop to become idle."}))).add(u.post("session.revert.stage","/api/session/:sessionID/revert/stage",{params:{sessionID:K.ID},payload:o.Struct({messageID:jr.ID,files:o.Boolean.pipe(o.optional)}),success:o.Struct({data:Uu.State}),error:[sn,N,tt]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.revert.stage",summary:"Stage session revert",description:"Stage or move a reversible session boundary and optionally apply its file changes."}))).add(u.post("session.revert.clear","/api/session/:sessionID/revert/clear",{params:{sessionID:K.ID},success:k.NoContent,error:[N,tt]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.revert.clear",summary:"Clear staged revert"}))).add(u.post("session.revert.commit","/api/session/:sessionID/revert/commit",{params:{sessionID:K.ID},success:k.NoContent,error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.revert.commit",summary:"Commit staged revert"}))).add(u.get("session.context","/api/session/:sessionID/context",{params:{sessionID:K.ID},success:o.Struct({data:o.Array(jr.Message)}),error:[N,tt]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.context",summary:"Get session context",description:"Retrieve the active context messages for a session (all messages after the last compaction)."}))).add(u.get("session.history","/api/session/:sessionID/history",{params:{sessionID:K.ID},query:ew,success:o.Struct({data:o.Array(Dn.Durable),hasMore:o.Boolean}).annotate({identifier:"SessionHistory"}),error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.history",summary:"Get session history",description:"Read one finite page of public durable Session events after an exclusive aggregate sequence. Newly committed events may appear on later pages."}))).add(u.get("session.events","/api/session/:sessionID/event",{params:{sessionID:K.ID},query:{after:o.NumberFromString.pipe(o.decodeTo(Ae),o.optional)},success:k.StreamSse({data:Dn.Durable}),error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.events",summary:"Subscribe to session events",description:"Replay durable events after an aggregate sequence, then continue with new durable events."}))).add(u.post("session.interrupt","/api/session/:sessionID/interrupt",{params:{sessionID:K.ID},success:k.NoContent,error:N}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.interrupt",summary:"Interrupt session execution",description:"Interrupt active execution owned by this OpenCode process. Idle interruption is a no-op."}))).add(u.get("session.message","/api/session/:sessionID/message/:messageID",{params:{sessionID:K.ID,messageID:jr.ID},success:o.Struct({data:jr.Message}),error:[N,sn]}).middleware(t).annotateMerge(d.annotations({identifier:"v2.session.message",summary:"Get session message",description:"Retrieve one projected message owned by the Session."}))).annotateMerge(d.annotations({title:"sessions",description:"Experimental session routes."})),"makeSessionGroup");var wy=i((t,e)=>H.make("server.permission").add(u.get("permission.request.list","/api/permission/request",{query:_,success:z.response(o.Array(be.Request))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.permission.request.list",summary:"List pending permission requests",description:"Retrieve pending permission requests for a location."}))).add(u.get("permission.saved.list","/api/permission/saved",{query:o.Struct({projectID:Ht.ID.pipe(o.optional)}),success:o.Struct({data:o.Array(qc.Info)})}).annotateMerge(d.annotations({identifier:"v2.permission.saved.list",summary:"List saved permissions",description:"Retrieve saved permissions, optionally filtered by project."}))).add(u.delete("permission.saved.remove","/api/permission/saved/:id",{params:{id:qc.ID},success:k.NoContent}).annotateMerge(d.annotations({identifier:"v2.permission.saved.remove",summary:"Remove saved permission",description:"Remove a saved permission by ID."}))).middleware(t).add(u.post("session.permission.create","/api/session/:sessionID/permission",{params:{sessionID:K.ID},payload:o.Struct({id:be.ID.pipe(o.optional),action:be.Request.fields.action,resources:be.Request.fields.resources,save:be.Request.fields.save,metadata:be.Request.fields.metadata,source:be.Request.fields.source,agent:wn.ID.pipe(o.optional)}),success:o.Struct({data:o.Struct({id:be.ID,effect:be.Effect})}),error:N}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.permission.create",summary:"Create permission request",description:"Evaluate and, when approval is required, create a permission request for a session."}))).add(u.get("session.permission.list","/api/session/:sessionID/permission",{params:{sessionID:K.ID},success:o.Struct({data:o.Array(be.Request)}),error:N}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.permission.list",summary:"List session permission requests",description:"Retrieve pending permission requests owned by a session."}))).add(u.get("session.permission.get","/api/session/:sessionID/permission/:requestID",{params:{sessionID:K.ID,requestID:be.ID},success:o.Struct({data:be.Request}),error:[N,Wn]}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.permission.get",summary:"Get permission request",description:"Retrieve a pending permission request owned by a session."}))).add(u.post("session.permission.reply","/api/session/:sessionID/permission/:requestID/reply",{params:{sessionID:K.ID,requestID:be.ID},payload:o.Struct({reply:be.Reply,message:o.String.pipe(o.optional)}),success:k.NoContent,error:[N,Wn]}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.permission.reply",summary:"Reply to pending permission request",description:"Respond to a pending permission request owned by a session."}))).annotateMerge(d.annotations({title:"permissions",description:"Experimental permission routes."})),"makePermissionGroup");var nw=o.Struct({..._.fields,path:vt.pipe(o.optional)}),ow=o.Struct({..._.fields,query:Rn.FindInput.fields.query,type:Rn.FindInput.fields.type,limit:o.NumberFromString.pipe(o.decodeTo(In),o.optional)}),Dy=H.make("server.fs").add(u.get("fs.read","/api/fs/read/*",{query:_,success:o.Uint8Array.pipe(k.asUint8Array())}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.fs.read",summary:"Read file",description:"Serve one file relative to the requested location."}))).add(u.get("fs.list","/api/fs/list",{query:nw,success:z.response(o.Array(Rn.Entry))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.fs.list",summary:"List directory",description:"List direct children of one directory relative to the requested location."}))).add(u.get("fs.find","/api/fs/find",{query:ow,success:z.response(o.Array(Rn.Entry))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.fs.find",summary:"Find files",description:"Find recursively ranked filesystem entries relative to the requested location."}))).annotateMerge(d.annotations({title:"filesystem",description:"Experimental location-scoped filesystem routes."}));var Ry=H.make("server.command").add(u.get("command.list","/api/command",{query:_,success:z.response(o.Array(Bu.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.command.list",summary:"List commands",description:"Retrieve currently registered commands."}))).annotateMerge(d.annotations({title:"commands",description:"Experimental command routes."}));var Cy=H.make("server.skill").add(u.get("skill.list","/api/skill",{query:_,success:z.response(o.Array(Zu.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.skill.list",summary:"List skills",description:"Retrieve currently registered skills."}))).annotateMerge(d.annotations({title:"skills",description:"Experimental skill routes."}));var sw={id:st.ID,metadata:o.optional(o.Record(o.String,o.Unknown)),durable:o.optional(o.Struct({aggregateID:o.String,seq:o.Int,version:o.Int})),location:o.optional(z.Ref)},iw=i(t=>o.Union([...t,...t.some(e=>e.type==="server.connected")?[]:[o.Struct({...sw,type:o.Literal("server.connected"),data:o.Struct({})}).annotate({identifier:"V2Event.server.connected"})]]).annotate({identifier:"V2Event"}),"schema"),xy=i(t=>{let e=iw(t);return{schema:e,group:H.make("server.event").add(u.get("event.subscribe","/api/event",{success:k.StreamSse({data:e})}).annotateMerge(d.annotations({identifier:"v2.event.subscribe",summary:"Subscribe to events",description:"Subscribe to native event payloads for the server."}))).annotateMerge(d.annotations({title:"events",description:"Experimental event stream route."}))}},"make"),ky=i(t=>xy(t).group,"makeEventGroup"),Hy=xy(ei.ServerDefinitions),Py=Hy.group,Ty=Hy.schema;var by=H.make("server.agent").add(u.get("agent.list","/api/agent",{query:_,success:z.response(o.Array(wn.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.agent.list",summary:"List agents",description:"Retrieve currently registered agents."})));var qy=H.make("server.health").add(u.get("health.get","/api/health",{success:o.Struct({healthy:o.Literal(!0)})}).annotateMerge(d.annotations({identifier:"v2.health.get",summary:"Check server health",description:"Check whether the API server is ready to accept requests."})));var My=i((t,e)=>H.make("server.question").add(u.get("question.request.list","/api/question/request",{query:_,success:z.response(o.Array(Qr.Request))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.question.request.list",summary:"List pending question requests",description:"Retrieve pending question requests for a location."}))).annotateMerge(d.annotations({title:"questions",description:"Experimental question routes."})).middleware(t).add(u.get("session.question.list","/api/session/:sessionID/question",{params:{sessionID:K.ID},success:o.Struct({data:o.Array(Qr.Request)}),error:N}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.question.list",summary:"List session question requests",description:"Retrieve pending question requests owned by a session."}))).add(u.post("session.question.reply","/api/session/:sessionID/question/:requestID/reply",{params:{sessionID:K.ID,requestID:Qr.ID},payload:Qr.Reply,success:k.NoContent,error:[N,$n]}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.question.reply",summary:"Reply to pending question request",description:"Answer a pending question request owned by a session."}))).add(u.post("session.question.reject","/api/session/:sessionID/question/:requestID/reject",{params:{sessionID:K.ID,requestID:Qr.ID},success:k.NoContent,error:[N,$n]}).middleware(e).annotateMerge(d.annotations({identifier:"v2.session.question.reject",summary:"Reject pending question request",description:"Reject a pending question request owned by a session."}))).annotateMerge(d.annotations({title:"session questions",description:"Experimental session question routes."})),"makeQuestionGroup");var Oy=H.make("server.reference").add(u.get("reference.list","/api/reference",{query:_,success:z.response(o.Array(ta.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.reference.list",summary:"List references",description:"List references available in the requested location."}))).annotateMerge(d.annotations({title:"reference",description:"Location-scoped project references."}));var aw=o.Record(o.String,o.String),Ly=H.make("server.integration").add(u.get("integration.list","/api/integration",{query:_,success:z.response(o.Array(Ye.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.list",summary:"List integrations",description:"Retrieve available integrations and their authentication methods."}))).add(u.get("integration.get","/api/integration/:integrationID",{params:{integrationID:Ye.ID},query:_,success:z.response(o.UndefinedOr(Ye.Info))}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.get",summary:"Get integration",description:"Retrieve one integration and its authentication methods."}))).add(u.post("integration.connect.key","/api/integration/:integrationID/connect/key",{params:{integrationID:Ye.ID},query:_,payload:o.Struct({key:o.String,label:o.optional(o.String)}),success:k.NoContent,error:Pe}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.connect.key",summary:"Connect with key",description:"Run a key authentication method and store the resulting credential."}))).add(u.post("integration.connect.oauth","/api/integration/:integrationID/connect/oauth",{params:{integrationID:Ye.ID},query:_,payload:o.Struct({methodID:Ye.MethodID,inputs:aw,label:o.optional(o.String)}),success:z.response(Ye.Attempt),error:Pe}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.connect.oauth",summary:"Begin OAuth connection",description:"Start an OAuth attempt and return the authorization details."}))).add(u.get("integration.attempt.status","/api/integration/attempt/:attemptID",{params:{attemptID:Ye.AttemptID},query:_,success:z.response(Ye.AttemptStatus)}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.attempt.status",summary:"Get OAuth attempt status",description:"Poll the current status of an OAuth attempt."}))).add(u.post("integration.attempt.complete","/api/integration/attempt/:attemptID/complete",{params:{attemptID:Ye.AttemptID},query:_,payload:o.Struct({code:o.optional(o.String)}),success:k.NoContent,error:Pe}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.attempt.complete",summary:"Complete OAuth connection",description:"Complete a code-based OAuth attempt and store the resulting credential."}))).add(u.delete("integration.attempt.cancel","/api/integration/attempt/:attemptID",{params:{attemptID:Ye.AttemptID},query:_,success:k.NoContent}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.integration.attempt.cancel",summary:"Cancel OAuth connection",description:"Cancel an OAuth attempt and release its resources."}))).annotateMerge(d.annotations({title:"integrations",description:"Integration discovery and authentication routes."}));var Uy=H.make("server.credential").add(u.patch("credential.update","/api/credential/:credentialID",{params:{credentialID:Pc.ID},query:_,payload:o.Struct({label:o.String}),success:k.NoContent}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.credential.update",summary:"Update credential",description:"Update a stored credential label."}))).add(u.delete("credential.remove","/api/credential/:credentialID",{params:{credentialID:Pc.ID},query:_,success:k.NoContent}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.credential.remove",summary:"Remove credential",description:"Remove a stored integration credential."})));var Bp="/experimental/project/:projectID/copy",eo=class extends o.ErrorClass("ProjectCopyError")({name:o.Literal("ProjectCopyError"),data:o.Struct({message:o.String,forceRequired:o.optional(o.Boolean)})},{httpApiStatus:400}){static{i(this,"ProjectCopyError")}},cw=o.Struct(ze.omit(oa.CreateInput.fields,["projectID","sourceDirectory"])),pw=o.Struct(ze.omit(oa.RemoveInput.fields,["projectID"])),Ny=H.make("server.projectCopy").add(u.post("projectCopy.create",Bp,{params:{projectID:Ht.ID},query:_,payload:cw,success:oa.Copy,error:eo}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.projectCopy.create"}))).add(u.delete("projectCopy.remove",Bp,{params:{projectID:Ht.ID},query:_,payload:pw,success:k.NoContent,error:eo}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.projectCopy.remove"}))).add(u.post("projectCopy.refresh",`${Bp}/refresh`,{params:{projectID:Ht.ID},query:_,success:k.NoContent,error:eo}).annotateMerge(B).annotateMerge(d.annotations({identifier:"v2.projectCopy.refresh"}))).annotateMerge(d.annotations({title:"projectCopy",description:"Project copy management routes."}));var _y=i((t,e,r)=>U.make("server").add(qy).add(cf.middleware(e)).add(by.middleware(e)).add(Iy(r)).add(hy.middleware(r)).add(Sy.middleware(e)).add(vy.middleware(e)).add(Ly.middleware(e)).add(Uy.middleware(e)).add(wy(e,r)).add(Dy.middleware(e)).add(Ry.middleware(e)).add(Cy.middleware(e)).add(t).add(mf.middleware(e)).add(My(e,r)).add(Oy.middleware(e)).add(Ny.middleware(e)).annotateMerge(d.annotations({title:"opencode HttpApi",version:"0.0.1",description:"Experimental HttpApi surface for selected instance routes."})).middleware(or).middleware(Jn),"makeApiFromGroup"),By=i(t=>_y(ky(t.definitions),t.locationMiddleware,t.sessionLocationMiddleware),"makeApi"),Fy=i(t=>_y(Py,t.locationMiddleware,t.sessionLocationMiddleware),"makeDefaultApi");var mn=class extends ye.Service()("@opencode/HttpApiLocation"){static{i(this,"LocationMiddleware")}};function J(t){return s.gen(function*(){let e=yield*ce.Service;return{location:new ce.Info({directory:e.directory,workspaceID:e.workspaceID,project:e.project}),data:yield*t}})}i(J,"response");function dw(t){let e=new URL(t.url,"http://localhost").searchParams,r=e.get("location[workspace]")||t.headers["x-opencode-workspace"],n=e.get("location[directory]")||(t.headers["x-opencode-directory"]?uw(t.headers["x-opencode-directory"]):process.cwd());return ce.Ref.make({directory:Ie.make(n),workspaceID:r?$r.ID.make(r):void 0})}i(dw,"ref");function uw(t){try{return decodeURIComponent(t)}catch{return t}}i(uw,"decode");var jy=P.effect(mn,s.gen(function*(){let t=yield*Ge.Service;return mn.of(e=>s.gen(function*(){let r=yield*ge.HttpServerRequest;return yield*e.pipe(s.provide(t.get(dw(r))))}))}));var ln=class extends ye.Service()("@opencode/HttpApiSessionLocation",{error:[Pe,N]}){static{i(this,"SessionLocationMiddleware")}},mw=o.decodeUnknownEffect(Et.ID),Gy=P.effect(ln,s.gen(function*(){let{db:t}=yield*Fr.Service,e=yield*Ge.Service;return ln.of(r=>s.gen(function*(){let n=yield*Ce.RouteContext,a=yield*mw(n.params.sessionID).pipe(s.mapError(()=>new Pe({message:"Invalid session ID",field:"sessionID"}))),c=yield*t.select({directory:ys.directory,workspaceID:ys.workspace_id}).from(ys).where(Yi(ys.id,a)).get().pipe(s.orDie);return c?yield*r.pipe(s.provide(e.get(ce.Ref.make({directory:Ie.make(c.directory),workspaceID:c.workspaceID?$r.ID.make(c.workspaceID):void 0})))):yield*new N({sessionID:a,message:`Session not found: ${a}`})}))}));var Wy=oc(Ch(),1);var lw=o.Struct({healthy:o.Literal(!0),version:o.String}),fw=Cr.Latest.values().flatMap(t=>t.durable?[o.Struct({type:o.Literal("sync"),id:le.ID,syncEvent:o.Struct({type:o.Literal(le.versionedType(t.type,t.durable.version)),id:le.ID,seq:o.Finite,aggregateID:o.String,data:t.data})}).annotate({identifier:`SyncEvent.${t.type}`})]:[]).toArray(),yw=o.Struct({directory:o.String,project:o.optional(o.String),workspace:o.optional(o.String),payload:o.Union([...Cr.Latest.values().map(t=>o.Struct({id:le.ID,type:o.Literal(t.type),properties:t.data})).toArray(),Ba,...fw])}).annotate({identifier:"GlobalEvent"}),gw=o.Struct({target:o.String.check(o.makeFilter(t=>Wy.default.valid(t)===null?"Expected a semantic version":void 0))}),hw=o.Union([o.Struct({success:o.Literal(!0),version:o.String}),o.Struct({success:o.Literal(!1),error:o.String})]),Wo={health:"/global/health",event:"/global/event",config:"/global/config",dispose:"/global/dispose",upgrade:"/global/upgrade"},$y=U.make("global").add(H.make("global").add(u.get("health",Wo.health,{success:S(lw,"Health information")}).annotateMerge(d.annotations({identifier:"global.health",summary:"Get health",description:"Get health information about the OpenCode server."})),u.get("event",Wo.event,{success:yw}).annotateMerge(d.annotations({identifier:"global.event",summary:"Get global events",description:"Subscribe to global events from the OpenCode system using server-sent events."})),u.get("configGet",Wo.config,{success:S(Gr.Info,"Get global config info")}).annotateMerge(d.annotations({identifier:"global.config.get",summary:"Get global configuration",description:"Retrieve the current global OpenCode configuration settings and preferences."})),u.patch("configUpdate",Wo.config,{payload:Gr.Info,success:S(Gr.Info,"Successfully updated global config"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"global.config.update",summary:"Update global configuration",description:"Update global OpenCode configuration settings and preferences."})),u.post("dispose",Wo.dispose,{success:S(o.Boolean,"Global disposed")}).annotateMerge(d.annotations({identifier:"global.dispose",summary:"Dispose instance",description:"Clean up and dispose all OpenCode instances, releasing all resources."})),u.post("upgrade",Wo.upgrade,{payload:gw,success:S(hw,"Upgrade result"),error:D.BadRequest}).annotateMerge(d.annotations({identifier:"global.upgrade",summary:"Upgrade opencode",description:"Upgrade opencode to the specified version."}))).annotateMerge(d.annotations({title:"global",description:"Global server routes."})));var Fp=1024;function Sw(t){return t.length<=Fp?t:t.slice(0,Fp)+`\u2026 (${t.length-Fp} more chars)`}i(Sw,"truncateReason");var $o=class extends ye.Service()("@opencode/HttpApiSchemaError",{error:Yn}){static{i(this,"SchemaErrorMiddleware")}},jp=ye.layerSchemaErrorTransform($o,(t,e)=>{let r=Sw(t.cause.message),n=e.endpoint.path.startsWith("/api/")?s.fail(new Yn({message:r,kind:t.kind})):s.succeed(q.jsonUnsafe({name:"BadRequest",data:{message:r,kind:t.kind}},{status:400}));return s.logWarning("schema rejection",{kind:t.kind,reason:r}).pipe(s.andThen(n))});var vw=o.Union([...Cr.Latest.values().map(t=>o.Struct({id:le.ID,type:o.Literal(t.type),properties:t.data}).annotate({identifier:`Event.${t.type}`})).toArray(),Ba]).annotate({identifier:"Event"}),Ew=By({definitions:Cr.Latest.values().toArray(),locationMiddleware:mn,sessionLocationMiddleware:ln}),Hr=U.make("opencode-root").addHttpApi(zf).addHttpApi(Qf).addHttpApi($y).middleware($o).middleware(j),Q=U.make("opencode-instance").addHttpApi($f).addHttpApi(Wf).addHttpApi(Yf).addHttpApi(Xf).addHttpApi(Jf).addHttpApi(Zf).addHttpApi(ry).addHttpApi(ny).addHttpApi(iy).addHttpApi(ay).addHttpApi(ty).addHttpApi(oy).addHttpApi(py).addHttpApi(uy).addHttpApi(yy).addHttpApi(gy).middleware($o),Gp=U.make("opencode").addHttpApi(Hr).addHttpApi(Bo).addHttpApi(Q).addHttpApi(Ew).addHttpApi(jo).annotate(U.AdditionalSchemas,[vw,$t.Replied,$t.Rejected,_u.Value,je.Inputs,je.Method,je.Ref,ra.Source]);var V=Fy({locationMiddleware:mn,sessionLocationMiddleware:ln});var Aw={"GET /experimental/session start":{type:"number"},"GET /experimental/session roots":si,"GET /experimental/session archived":si,"GET /find/file limit":{type:"integer",minimum:1,maximum:200},"GET /experimental/session cursor":{type:"number"},"GET /experimental/session limit":{type:"number"},"GET /session start":{type:"number"},"GET /session roots":si,"GET /session limit":{type:"number"},"GET /session/{sessionID}/message limit":{type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER},"GET /vcs/diff context":{type:"integer",minimum:0},"GET /api/session limit":{type:"number"},"GET /api/session start":{type:"number"},"GET /api/session roots":si,"GET /api/session/{sessionID}/message limit":{type:"number"}},Iw={LogLevel:"Log level",ServerConfig:"Server configuration for opencode serve and web commands",LayoutConfig:"@deprecated Always uses stretch layout."};function ww(t){let e=t;Lw(e);for(let[r,n]of Object.entries(e.components?.schemas??{}))e.components.schemas[r]=ht(structuredClone(n));xw(e),Cw(e),Hw(e),Pw(e),Rw(e),delete e.components?.securitySchemes;for(let[r,n]of Object.entries(e.paths??{}))for(let a of["get","post","put","delete","patch"]){let c=n[a];if(!c)continue;let p=Dw(r);if(c.requestBody){p||delete c.requestBody.required;let l=c.requestBody.content?.["application/json"];if(l?.schema&&(l.schema=ht(structuredClone(l.schema))),r==="/experimental/workspace"&&a==="post"){let m=c.requestBody.content?.["application/json"]?.schema?.$ref?.replace("#/components/schemas/",""),y=m?e.components?.schemas?.[m]?.properties:c.requestBody.content?.["application/json"]?.schema?.properties;y?.branch&&(y.branch={anyOf:[y.branch,{type:"null"}]}),y?.extra&&(y.extra={anyOf:[y.extra,{type:"null"}]})}if(r==="/experimental/workspace/warp"&&a==="post"){let m=c.requestBody.content?.["application/json"]?.schema?.$ref?.replace("#/components/schemas/",""),y=m?e.components?.schemas?.[m]?.properties:c.requestBody.content?.["application/json"]?.schema?.properties;y?.id&&(y.id={anyOf:[y.id,{type:"null"}]})}}for(let l of Object.values(c.responses??{}))for(let m of Object.values(l.content??{}))m.schema&&(m.schema=ht(structuredClone(m.schema)));p||(delete c.security,delete c.responses?.[401],bw(c)),Mw(c,r,a),(r==="/event"||r==="/global/event"||r==="/api/event")&&a==="get"&&(c.responses[200]={description:"Event stream",content:{"text/event-stream":{schema:r==="/event"?{$ref:"#/components/schemas/Event"}:r==="/global/event"?{$ref:"#/components/schemas/GlobalEvent"}:{$ref:"#/components/schemas/V2Event"}}}});let f=`${a.toUpperCase()} ${r}`;for(let l of c.parameters??[])Bw(l,f)}return qw(e),t}i(ww,"matchLegacyOpenApi");function Dw(t){return t==="/api"||t.startsWith("/api/")}i(Dw,"isV2ApiPath");function Rw(t){t.components?.schemas&&(t.components.schemas.BadRequestError={type:"object",required:["name","data"],properties:{name:{type:"string",enum:["BadRequest"]},data:{type:"object",required:["message"],properties:{message:{type:"string"},kind:{type:"string",enum:["Params","Headers","Query","Body","Payload"]}}}}},t.components.schemas.NotFoundError={type:"object",required:["name","data"],properties:{name:{type:"string",enum:["NotFoundError"]},data:{type:"object",required:["message"],properties:{message:{type:"string"}}}}})}i(Rw,"addLegacyErrorSchemas");function Cw(t){let e=t.components?.schemas;if(e)for(let r of Object.keys(e)){let n=r.replace(/\d+$/,"");n===r||!e[n]||Qa(e[r],e)===Qa(e[n],e)&&(di(t,r,n),delete e[r])}}i(Cw,"collapseDuplicateComponents");function xw(t){let e=t.components?.schemas;if(e)for(let r of Object.keys(e)){let n=kw(r);if(n!==r){if(e[n]){Qa(e[r],e)===Qa(e[n],e)&&(di(t,r,n),delete e[r]);continue}e[n]=e[r],di(t,r,n),delete e[r]}}}i(xw,"normalizeComponentNames");function kw(t){return t.includes(".")?t.split(".").filter(e=>!/^\d+$/.test(e)).map(e=>e.slice(0,1).toUpperCase()+e.slice(1)).join(""):t}i(kw,"componentTypeName");function Hw(t){let e=t.components?.schemas;if(!e)return;e.AgentConfig&&(e.AgentConfig.additionalProperties={}),e.Command?.properties?.template&&(e.Command.properties.template={type:"string"}),e.Workspace?.properties&&(e.Workspace.properties.branch=Vo(e.Workspace.properties.branch),e.Workspace.properties.directory=Vo(e.Workspace.properties.directory),e.Workspace.properties.extra=Vo(e.Workspace.properties.extra)),e.GlobalSession?.properties?.project&&(e.GlobalSession.properties.project=Vo(e.GlobalSession.properties.project));let r=e.ProviderConfig?.properties?.options;r&&(r.additionalProperties={});let n=e.ProviderConfig?.properties?.models?.additionalProperties,a=typeof n=="object"?n.properties?.variants?.additionalProperties:void 0;a&&typeof a=="object"&&(a.additionalProperties={});let c=e.SyncEventSessionUpdated?.properties?.data?.properties?.info;c?.properties&&zy(c.properties)}i(Hw,"applyLegacySchemaOverrides");function Pw(t){for(let[e,r]of Object.entries(t.components?.schemas??{})){let n=Iw[e];if(n){r.description=n;continue}delete r.description}}i(Pw,"normalizeComponentDescriptions");function zy(t){for(let[e,r]of Object.entries(t)){if(e==="share"&&r.properties?.url){r.properties.url=Vo(r.properties.url);continue}if(e==="time"&&r.properties){zy(r.properties);continue}t[e]=Vo(r)}}i(zy,"makePropertiesNullable");function Vo(t){return Vp(t.anyOf??t.oneOf)?.some(e=>e.type==="null")?t:{anyOf:[t,{type:"null"}]}}i(Vo,"nullable");function Qa(t,e){return JSON.stringify(Wp(t,e))}i(Qa,"stableSchema");function Wp(t,e){if(Array.isArray(t))return t.map(n=>Wp(n,e));if(!t||typeof t!="object")return t;let r=t;return r.$ref?{$ref:Tw(r.$ref,e)}:Object.fromEntries(Object.entries(t).filter(([n])=>n!=="description").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,Wp(a,e)]))}i(Wp,"canonicalizeSchema");function Tw(t,e){let r=t.replace("#/components/schemas/",""),n=r.replace(/\d+$/,"");return n!==r&&e[n]?`#/components/schemas/${n}`:t}i(Tw,"canonicalRef");function di(t,e,r){if(Array.isArray(t)){for(let a of t)di(a,e,r);return}if(!t||typeof t!="object")return;let n=t;n.$ref===`#/components/schemas/${e}`&&(n.$ref=`#/components/schemas/${r}`);for(let a of Object.values(t))di(a,e,r)}i(di,"rewriteRefs");function bw(t){t.responses?.["400"]&&Ow(t.responses[400])&&(t.responses[400]=Vy("Bad request","BadRequestError")),t.responses?.["404"]&&Yy(t.responses[404],"NotFound")&&(t.responses[404]=Vy("Not found","NotFoundError"))}i(bw,"normalizeLegacyErrorResponses");function qw(t){for(let e of["Unauthorized","EffectHttpApiErrorBadRequest","EffectHttpApiErrorNotFound","effect_HttpApiError_BadRequest","effect_HttpApiError_NotFound"])$p(t.paths,e)||delete t.components?.schemas?.[e]}i(qw,"deleteUnusedLegacyErrorComponents");function $p(t,e){return Array.isArray(t)?t.some(r=>$p(r,e)):!t||typeof t!="object"?!1:t.$ref===`#/components/schemas/${e}`?!0:Object.values(t).some(r=>$p(r,e))}i($p,"referencesComponent");function Mw(t,e,r){if(e==="/experimental/console/switch"&&r==="post"&&delete t.responses?.[400],e!=="/session/{sessionID}/message"&&e!=="/session/{sessionID}/command"||r!=="post")return;let n=t.responses?.["200"]?.content?.["application/json"];n&&(n.schema={type:"object",required:["info","parts"],properties:{info:{$ref:"#/components/schemas/AssistantMessage"},parts:{type:"array",items:{$ref:"#/components/schemas/Part"}}}})}i(Mw,"normalizeLegacyOperation");function Qy(t,e){return t.content?.["application/json"]?.schema?.$ref===`#/components/schemas/${e}`}i(Qy,"isRefResponse");function Yy(t,e){return t.description===e||Qy(t,`EffectHttpApiError${e}`)}i(Yy,"isBuiltInErrorResponse");function Ow(t){return Yy(t,"BadRequest")||Qy(t,"InvalidRequestError")}i(Ow,"isLegacyBadRequestResponse");function Vy(t,e){return{description:t,content:{"application/json":{schema:{$ref:`#/components/schemas/${e}`}}}}}i(Vy,"legacyErrorResponse");function Lw(t){let e=t.components?.schemas;if(!e)return;let r=new Set;for(let[c,p]of Object.entries(e))p.$ref===`#/components/schemas/${c}`&&r.add(c);if(r.size===0)return;for(let[,c]of Object.entries(e))for(let p of c.anyOf??c.oneOf??[]){let f=p.$ref?.replace("#/components/schemas/","");!f||r.has(f)}let a=d.fromApi(Gp).components?.schemas;if(a)for(let c of r)a[c]&&(e[c]=a[c])}i(Lw,"fixSelfReferencingComponents");function ht(t){if(t.allOf?.length===1){let[r]=t.allOf;return delete t.allOf,ht({...t,...r})}if(Uw(t))return{type:"object",properties:{}};let e=Vp(t.anyOf??t.oneOf);if(e){let r=e.filter(n=>n.type!=="null");if(r.length===1)return ht(r[0]);t.anyOf&&(t.anyOf=r.map(ht)),t.oneOf&&(t.oneOf=r.map(ht))}if(t.allOf){let r=t.allOf.map(ht);if(t.type){delete t.allOf;for(let n of r)Object.assign(t,n)}else t.allOf=r}if(t.prefixItems&&t.items&&delete t.prefixItems,t.items&&(t.items=ht(t.items)),t.properties)for(let[r,n]of Object.entries(t.properties))t.properties[r]=ht(n);return t.additionalProperties&&typeof t.additionalProperties=="object"&&(t.additionalProperties=ht(t.additionalProperties)),t}i(ht,"stripOptionalNull");function Uw(t){let e=t.anyOf??t.oneOf;return e?.length===2&&e.some(Nw)&&e.some(_w)}i(Uw,"isEmptyObjectUnion");function Nw(t){return t.type==="object"&&!t.properties&&!t.additionalProperties}i(Nw,"isBareObjectSchema");function _w(t){return t.type==="array"&&!t.items&&!t.prefixItems}i(_w,"isBareArraySchema");function Vp(t){return t?.flatMap(e=>Vp(e.anyOf??e.oneOf)??[e])}i(Vp,"flattenOptions");function Bw(t,e){if(!(!t.schema||typeof t.schema!="object")){if(t.in==="path"){t.schema=ht(t.schema);return}if(t.in==="query"){let r=Aw[`${e} ${t.name}`];if(r){t.schema=r;return}}t.schema=ht(t.schema)}}i(Bw,"normalizeParameter");var Ya=Gp.annotateMerge(d.annotations({title:"opencode",version:"1.0.0",description:"opencode api",transform:ww}));function Fw(t){return{_tag:"Event",event:"message",id:void 0,data:JSON.stringify(t)}}i(Fw,"eventData");function zp(){return le.ID.create()}i(zp,"eventID");function jw(t){return s.gen(function*(){let e=yield*Ue.context,r=yield*Ue.workspaceID,n=yield*Ee.unbounded(),a=yield*t.listen(m=>s.sync(()=>Ee.offerUnsafe(n,m)));yield*s.addFinalizer(()=>a);let c=Gd(n).pipe($d(m=>m.location?.directory===e.directory&&(m.location.workspaceID===void 0||m.location.workspaceID===r)),Ft(m=>({id:m.id,type:m.type,properties:m.data}))),p=Ri(m=>{let y=i(g=>{g.directory!==e.directory||g.payload.type!=="server.instance.disposed"||Ee.offerUnsafe(m,{id:g.payload.id??zp(),type:"server.instance.disposed",properties:g.payload.properties??{}})},"listener");return s.acquireRelease(s.sync(()=>mr.on("event",y)),()=>s.sync(()=>mr.off("event",y)))}),f=c.pipe(is(p,{haltStrategy:"left"}),zd(m=>m.type==="server.instance.disposed")),l=Di("10 seconds").pipe(xi(1),Ft(()=>({id:zp(),type:"server.heartbeat",properties:{}})));return yield*s.logInfo("event connected"),q.stream(io({id:zp(),type:"server.connected",properties:{}}).pipe(Ci(f.pipe(is(l,{haltStrategy:"left"}))),Ft(Fw),ki(po()),Ur,Hi(s.logInfo("event disconnected"))),{contentType:"text/event-stream",headers:{"Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no","X-Content-Type-Options":"nosniff"}})})}i(jw,"eventResponse");var Ky=x.group(Bo,"event",t=>s.gen(function*(){let e=yield*Wt.Service;return t.handleRaw("subscribe",s.fn("EventHttpApi.subscribe")(function*(){return yield*jw(e)}))}));var Qp=new WeakMap,Xy=i(t=>s.gen(function*(){return{ctx:t,store:yield*It.Service,bridge:yield*ho.make()}}),"mark"),Ka=i(t=>s.gen(function*(){let e=yield*Xy(t);return yield*_r.appendPreResponseHandler((r,n)=>s.sync(()=>(Qp.set(r.source,e),n)))}),"markInstanceForDisposal"),Jy=i((t,e)=>s.gen(function*(){let r=yield*Xy(t);return yield*_r.appendPreResponseHandler((n,a)=>s.as(s.uninterruptible(r.bridge.run(r.store.reload(e))),a))}),"markInstanceForReload"),Xa=i(t=>s.gen(function*(){let e=yield*t,r=yield*ge.HttpServerRequest,n=Qp.get(r.source);return n&&(Qp.delete(r.source),yield*s.uninterruptible(n.bridge.run(n.store.dispose(n.ctx))).pipe(s.catchCause(a=>s.logWarning("instance disposal failed",{cause:a})))),e}),"disposeMiddleware");var Zy=x.group(Q,"config",t=>s.gen(function*(){let e=yield*Me.Service,r=yield*At.Service,n=s.fn("ConfigHttpApi.get")(function*(){return yield*r.get()}),a=s.fn("ConfigHttpApi.update")(function*(p){return yield*r.update(p.payload),yield*Ka(yield*pe),p.payload}),c=s.fn("ConfigHttpApi.providers")(function*(){let p=yield*e.list();return{providers:Object.values(p).map(Me.toPublicInfo),default:Me.defaultModelIDs(p)}});return t.handle("get",n).handle("update",a).handle("providers",c)}));var zo,eg=new Map;async function tg(t,e){let r=await fetch(t,{headers:e,signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`HTTP ${r.status}`);return r.json()}i(tg,"readUsageJson");function Gw(t){let e=[];for(let r of["primary_window","secondary_window"]){let n=t?.[r];if(!n||typeof n!="object")continue;let a=Number(n.limit_window_seconds??0),c=a>=5e5?"7d":a>0&&a<=21600?"5h":"other";e.push({kind:c,label:c==="7d"?"weekly":c==="5h"?"5-hour window":`${Math.round(a/3600)}h window`,usedPercent:Number(n.used_percent??0),resetsAt:typeof n.reset_at=="number"?n.reset_at:null})}return e}i(Gw,"openaiWindows");async function Ww(t){let e={authorization:`Bearer ${t.access}`};t.accountId&&(e["ChatGPT-Account-Id"]=t.accountId);let r=await tg("https://chatgpt.com/backend-api/wham/usage",e);return{providerID:"openai",plan:typeof r?.plan_type=="string"?r.plan_type:null,windows:Gw(r?.rate_limit)}}i(Ww,"openaiUsage");async function $w(t){let e=await tg("https://api.anthropic.com/api/oauth/usage",{authorization:`Bearer ${t.access}`,"anthropic-beta":"oauth-2025-04-20"}),r=i(a=>typeof a=="string"&&!Number.isNaN(Date.parse(a))?Math.floor(Date.parse(a)/1e3):null,"toTs"),n=[];e?.five_hour&&typeof e.five_hour=="object"&&n.push({kind:"5h",label:"5-hour window",usedPercent:Number(e.five_hour.utilization??0),resetsAt:r(e.five_hour.resets_at)}),e?.seven_day&&typeof e.seven_day=="object"&&n.push({kind:"7d",label:"weekly",usedPercent:Number(e.seven_day.utilization??0),resetsAt:r(e.seven_day.resets_at)});for(let a of Array.isArray(e?.limits)?e.limits:[]){let c=a?.scope?.model?.display_name;a?.kind==="weekly_scoped"&&typeof c=="string"&&c&&n.push({kind:"other",label:`weekly, ${c}`,usedPercent:Number(a.percent??0),resetsAt:r(a.resets_at)})}return{providerID:"anthropic",plan:null,windows:n}}i($w,"anthropicUsage");async function rg(t,e=!1){if(!e&&zo&&Date.now()-zo.at<6e4)return{providers:zo.data,fetchedAt:zo.at};let r=[];for(let[n,a]of Object.entries(t)){if(a.type!=="oauth"||n!=="openai"&&n!=="anthropic")continue;let c=a;if(c.expires<Date.now()){r.push({providerID:n,plan:null,windows:[],error:"token expired; it refreshes on the next model call"});continue}try{let p={...n==="openai"?await Ww(c):await $w(c),readAt:Date.now()};eg.set(n,p),r.push(p)}catch(p){let f=p instanceof Error?p.message:String(p),l=eg.get(n);r.push(l?{...l,error:f}:{providerID:n,plan:null,windows:[],error:f})}}return zo={at:Date.now(),data:r},{providers:r,fetchedAt:zo.at}}i(rg,"providerUsage");var Ja,ng=x.group(Q,"alchemy",t=>s.gen(function*(){let e=yield*Gt.Service,r=yield*At.Service,n=yield*qe.Service,a=yield*Vt.Service,c=yield*Kr.Service,p=yield*It.Service,f=s.fn("AlchemyHttpApi.anyBusy")(function*(){for(let w of(yield*c.list()).values())if(w.type!=="idle")return!0;return!1}),l=s.fn("AlchemyHttpApi.reloadNow")(function*(){yield*r.invalidate(),yield*p.disposeAll()}),m=s.fn("AlchemyHttpApi.pauseState")(function*(){return ga.state()}),y=s.fn("AlchemyHttpApi.pause")(function*(w){return w.payload.paused?(ga.pause(),{paused:!0,stopped:yield*a.stopForPause()}):{paused:!1,waiting:ga.resume()}}),g=s.fn("AlchemyHttpApi.reload")(function*(){if(yield*f()){if(!Ja){let w=yield*ho.make(),C=Date.now();Ja=setInterval(()=>{w.promise(s.gen(function*(){(yield*f())&&Date.now()-C<12e4||(clearInterval(Ja),Ja=void 0,yield*l())})).catch(()=>{})},2e3)}return{ok:!0,deferred:!0}}return yield*l(),{ok:!0}}),E=s.fn("AlchemyHttpApi.usage")(function*(w){let C=yield*e.all().pipe(s.orElseSucceed(()=>({})));return yield*s.promise(()=>rg(C,w.query.force==="1"))}),v=s.fn("AlchemyHttpApi.mcpTools")(function*(){return yield*n.defs()}),h=s.fn("AlchemyHttpApi.searchKeys")(function*(){let w=yield*e.all().pipe(s.orElseSucceed(()=>({}))),C=i(R=>{let b=w[R];return b?.type==="api"&&b.key.trim().length>0},"has");return{exa:C(_c.exa),tavily:C(_c.tavily)}});return t.handle("pauseState",m).handle("pause",y).handle("reload",g).handle("usage",E).handle("mcpTools",v).handle("searchKeys",h)}));var og=x.group(Hr,"control",t=>s.gen(function*(){let e=yield*Gt.Service,r=s.fn("ControlHttpApi.authSet")(function*(c){return yield*e.set(c.params.providerID,c.payload).pipe(s.orDie),!0}),n=s.fn("ControlHttpApi.authRemove")(function*(c){return yield*e.remove(c.params.providerID).pipe(s.orDie),!0}),a=s.fn("ControlHttpApi.log")(function*(c){return yield*(c.payload.level==="debug"?s.logDebug:c.payload.level==="info"?s.logInfo:c.payload.level==="warn"?s.logWarning:s.logError)(c.payload.message).pipe(s.annotateLogs(c.payload.extra??{})),!0});return t.handle("authSet",r).handle("authRemove",n).handle("log",a)}));var sg=x.group(Hr,"controlPlane",t=>s.gen(function*(){let e=yield*Ot.Service,r=s.fn("ControlPlaneHttpApi.moveSession")(function*(n){yield*e.moveSession(n.payload).pipe(s.mapError(a=>new ni({name:"MoveSessionError",data:{message:Vw(a)}})))});return t.handle("moveSession",r)}));function Vw(t){return t instanceof Et.NotFoundError?`Session not found: ${t.sessionID}`:t instanceof Ot.DestinationProjectMismatchError?"Destination directory belongs to another project":t instanceof Ot.ApplyChangesError?"Unable to apply your changes in the destination directory. The files may conflict with existing changes.":t.message}i(Vw,"message");function Yp(t){return t.pipe(s.mapError(e=>new cn({name:e._tag,data:{message:e.message}})))}i(Yp,"mapWorktreeError");var ig=x.group(Q,"experimental",t=>s.gen(function*(){let e=yield*ia.Service,r=yield*zt.Service,n=yield*At.Service,a=yield*qe.Service,c=yield*it.Service,p=yield*ya.Service,f=yield*lr.Service,l=yield*X.Service,m=yield*pa.Service,y=yield*vs.Service,g=s.fn("ExperimentalHttpApi.capabilities")(function*(){return{backgroundSubagents:y.experimentalBackgroundSubagents}}),E=s.fn("ExperimentalHttpApi.console")(function*(){let[F,ue]=yield*s.all([n.getConsoleState(),e.orgsByAccount().pipe(s.catch(()=>s.fail(new D.InternalServerError({}))))],{concurrency:"unbounded"});return{consoleManagedProviders:F.consoleManagedProviders,...F.activeOrgName?{activeOrgName:F.activeOrgName}:{},switchableOrgCount:ue.reduce((ke,ne)=>ke+ne.orgs.length,0)}}),v=s.fn("ExperimentalHttpApi.consoleOrgs")(function*(){let[F,ue]=yield*s.all([e.orgsByAccount().pipe(s.catch(()=>s.fail(new D.InternalServerError({})))),e.active().pipe(s.catch(()=>s.fail(new D.InternalServerError({}))))],{concurrency:"unbounded"}),ke=Re.getOrUndefined(ue);return{orgs:F.flatMap(ne=>ne.orgs.map(Ve=>({accountID:ne.account.id,accountEmail:ne.account.email,accountUrl:ne.account.url,orgID:Ve.id,orgName:Ve.name,active:!!ke&&ke.id===ne.account.id&&ke.active_org_id===Ve.id})))}}),h=s.fn("ExperimentalHttpApi.consoleSwitch")(function*(F){return yield*e.use(F.payload.accountID,Re.some(F.payload.orgID)).pipe(s.catch(()=>s.fail(new D.BadRequest({})))),!0}),w=s.fn("ExperimentalHttpApi.tool")(function*(F){return(yield*p.tools({providerID:F.query.provider,modelID:F.query.model,agent:yield*r.defaultInfo()})).map(ke=>({id:ke.id,description:ke.description,parameters:Cm.fromTool(ke)}))}),C=s.fn("ExperimentalHttpApi.toolIDs")(function*(){return yield*p.ids()}),R=s.fn("ExperimentalHttpApi.worktree")(function*(){let F=yield*Ue.context;return yield*c.sandboxes(F.project.id)}),b=s.fn("ExperimentalHttpApi.worktreeCreate")(function*(F){return yield*Yp(f.create(F.payload??void 0))}),M=s.fn("ExperimentalHttpApi.worktreeRemove")(function*(F){let ue=yield*Ue.context;return yield*Yp(f.remove(F.payload)),yield*c.removeSandbox(ue.project.id,F.payload.directory),!0}),Z=s.fn("ExperimentalHttpApi.worktreeReset")(function*(F){return yield*Yp(f.reset(F.payload)),!0}),Se=s.fn("ExperimentalHttpApi.session")(function*(F){let ue=F.query.limit??100,ke=F.query.directory?yield*Ue.directory:void 0,ne=yield*l.listGlobal({directory:ke,roots:F.query.roots,start:F.query.start,cursor:F.query.cursor,search:F.query.search,limit:ue+1,archived:F.query.archived}),Ve=ne.length>ue?ne.slice(0,ue):ne;return Gi(Ve,{headers:ne.length>ue&&Ve.length>0?{"x-next-cursor":String(Ve[Ve.length-1].time.updated)}:void 0})}),De=s.fn("ExperimentalHttpApi.sessionBackground")(function*(F){if(!y.experimentalBackgroundSubagents)return!1;let ue=(yield*m.list()).filter(ne=>ne.type==="task"&&ne.status==="running"&&ne.metadata?.parentSessionId===F.params.sessionID&&ne.metadata.background!==!0);return(yield*s.forEach(ue,ne=>m.promote(ne.id),{concurrency:"unbounded"})).some(ne=>ne!==void 0)}),ar=s.fn("ExperimentalHttpApi.resource")(function*(){return yield*a.resources()});return t.handle("capabilities",g).handle("console",E).handle("consoleOrgs",v).handle("consoleSwitch",h).handle("tool",w).handle("toolIDs",C).handle("worktree",R).handle("worktreeCreate",b).handle("worktreeRemove",M).handle("worktreeReset",Z).handle("session",Se).handle("sessionBackground",De).handle("resource",ar)}));var gg=oc(yg(),1);import to from"path";var hg=x.group(Q,"file",t=>s.gen(function*(){let e=yield*Zi.Service,r=yield*Ge.Service,n=s.fnUntraced(function*(y){return yield*y.pipe(s.provide(r.get(ce.Ref.make({directory:Ie.make((yield*pe).directory)}))))}),a=s.fn("FileHttpApi.findText")(function*(y){return(yield*e.grep({cwd:(yield*pe).directory,pattern:y.query.pattern,limit:10}).pipe(s.orDie)).map(g=>({path:{text:g.entry.path},lines:{text:g.text},line_number:g.line,absolute_offset:g.offset,submatches:g.submatches.map(E=>({match:{text:E.text},start:E.start,end:E.end}))}))}),c=s.fn("FileHttpApi.findFile")(function*(y){let g=(yield*pe).directory,E=y.query.limit??10,v=y.query.type??(y.query.dirs==="false"?"file":void 0),h=performance.now(),w=yield*n(Wr.Service.use(C=>C.find({query:y.query.query,limit:E,type:v})));return yield*s.logInfo("find file",{query:y.query.query,type:v,directory:g,limit:E,results:w.length,duration:Math.round(performance.now()-h)}),w.map(C=>C.path)}),p=s.fn("FileHttpApi.findSymbol")(function*(){return[]}),f=s.fn("FileHttpApi.list")(function*(y){let g=(yield*pe).directory;return yield*n(s.gen(function*(){let E=yield*Wr.Service,v=yield*ur.Service,h=yield*ce.Service,w=(0,gg.default)(),C=yield*v.readFileString(to.join(h.project.directory,".gitignore")).pipe(s.catch(()=>s.succeed("")));C&&w.add(C);let R=yield*v.readFileString(to.join(h.project.directory,".ignore")).pipe(s.catch(()=>s.succeed("")));return R&&w.add(R),(yield*E.list({path:vt.make(y.query.path)})).map(b=>({name:to.basename(b.path),path:b.path,absolute:to.resolve(h.directory,b.path),type:b.type,ignored:w.ignores(to.relative(h.project.directory,to.resolve(h.directory,b.path))+(b.type==="directory"?"/":""))}))}))}),l=s.fn("FileHttpApi.content")(function*(y){let g=(yield*pe).directory,E=to.resolve(g,y.query.path);return ur.contains(g,E)?(yield*ur.Service.use(v=>v.existsSafe(E)))?yield*n(Wr.Service.use(v=>v.read({path:vt.make(y.query.path)}))).pipe(s.flatMap(v=>s.gen(function*(){let h=v.content.includes(0)?Re.none():yield*s.sync(()=>new TextDecoder("utf-8",{fatal:!0}).decode(v.content)).pipe(s.option);return{item:v,text:h}})),s.map(({item:v,text:h})=>Re.isSome(h)?{type:"text",content:h.value.trim()}:{type:"binary",content:Buffer.from(v.content).toString("base64"),encoding:"base64",mimeType:v.mime})):{type:"text",content:""}:yield*s.die(new Error("Path escapes the location"))}),m=s.fn("FileHttpApi.status")(function*(){return[]});return t.handle("findText",a).handle("findFile",c).handle("findSymbol",p).handle("list",f).handle("content",l).handle("status",m)})).pipe(P.provide(Ss));var lD=s.sync(()=>mr.emit("event",{directory:"global",payload:{type:rf.Disposed.type,properties:{}}})),rd=s.fn("Server.disposeAllInstancesAndEmitGlobalDisposed")(function*(t){let e=yield*It.Service;yield*s.gen(function*(){yield*t?.swallowErrors?e.disposeAll().pipe(s.catchCause(r=>s.logWarning("global disposal failed",{cause:r}))):e.disposeAll(),yield*lD}).pipe(s.uninterruptible)});function yD(t){return{_tag:"Event",event:"message",id:void 0,data:JSON.stringify(t)}}i(yD,"eventData");function gD(){return s.gen(function*(){yield*s.logInfo("global event connected");let t=Ri(r=>{let n=i(a=>Ee.offerUnsafe(r,a),"handler");return s.acquireRelease(s.sync(()=>mr.on("event",n)),()=>s.sync(()=>mr.off("event",n)))}),e=Di("10 seconds").pipe(xi(1),Ft(()=>({payload:{id:le.ID.create(),type:"server.heartbeat",properties:{}}})));return q.stream(io({payload:{id:le.ID.create(),type:"server.connected",properties:{}}}).pipe(Ci(t.pipe(is(e,{haltStrategy:"left"}))),Ft(yD),ki(po()),Ur,Hi(s.logInfo("global event disconnected"))),{contentType:"text/event-stream",headers:{"Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no","X-Content-Type-Options":"nosniff"}})})}i(gD,"eventResponse");var Sg=x.group(Hr,"global",t=>s.gen(function*(){let e=yield*At.Service,r=yield*Es.Service,n=yield*ho.make(),a=s.fn("GlobalHttpApi.health")(function*(){return{healthy:!0,version:qu}}),c=s.fn("GlobalHttpApi.event")(function*(){return yield*gD()}),p=s.fn("GlobalHttpApi.configGet")(function*(){return yield*e.getGlobal()}),f=s.fn("GlobalHttpApi.configUpdate")(function*(y){let g=yield*e.updateGlobal(y.payload);return g.changed&&n.fork(rd({swallowErrors:!0})),g.info}),l=s.fn("GlobalHttpApi.dispose")(function*(){return yield*rd(),!0}),m=s.fn("GlobalHttpApi.upgrade")(function*(y){let g=yield*r.method();if(g==="unknown")return q.jsonUnsafe({success:!1,error:"Unknown installation method"},{status:400});let E=y.payload.target,v=yield*r.upgrade(g,E).pipe(s.as({success:!0,version:E}),s.catch(h=>s.succeed({success:!1,error:h instanceof Error?h.message:String(h)})));return v.success?(mr.emit("event",{directory:"global",payload:{type:Es.Event.Updated.type,properties:{version:E}}}),q.jsonUnsafe(v)):q.jsonUnsafe(v,{status:500})});return t.handle("health",a).handleRaw("event",c).handle("configGet",p).handle("configUpdate",f).handle("dispose",l).handle("upgrade",m)}));var vg=x.group(Q,"instance",t=>s.gen(function*(){let e=yield*zt.Service,r=yield*Jr.Service,n=yield*Io.Service,a=yield*Xr.Service,c=yield*So.Service,p=yield*at.Service,f=s.fn("InstanceHttpApi.dispose")(function*(){return yield*Ka(yield*pe),!0}),l=s.fn("InstanceHttpApi.path")(function*(){let M=yield*pe;return{home:Ki.Path.home,state:Ki.Path.state,config:Ki.Path.config,worktree:M.worktree,directory:M.directory}}),m=s.fn("InstanceHttpApi.vcs")(function*(){let[M,Z]=yield*s.all([p.branch(),p.defaultBranch()],{concurrency:"unbounded"});return{branch:M,default_branch:Z}}),y=s.fn("InstanceHttpApi.vcsStatus")(function*(){return yield*p.status()}),g=s.fn("InstanceHttpApi.vcsDiff")(function*(M){return yield*p.diff(M.query.mode,{context:M.query.context})}),E=s.fn("InstanceHttpApi.vcsDiffRaw")(function*(){return yield*p.diffRaw()}),v=s.fn("InstanceHttpApi.vcsApply")(function*(M){return yield*p.apply(M.payload).pipe(s.mapError(Z=>new kr({name:"VcsApplyError",data:{message:Z.message,reason:Z.reason}})))}),h=s.fn("InstanceHttpApi.command")(function*(){return yield*r.list()}),w=s.fn("InstanceHttpApi.agent")(function*(){return yield*e.list()}),C=s.fn("InstanceHttpApi.skill")(function*(){return yield*c.all()}),R=s.fn("InstanceHttpApi.lsp")(function*(){return yield*a.status()}),b=s.fn("InstanceHttpApi.formatter")(function*(){return yield*n.status()});return t.handle("dispose",f).handle("path",l).handle("vcs",m).handle("vcsStatus",y).handle("vcsDiff",g).handle("vcsDiffRaw",E).handle("vcsApply",v).handle("command",h).handle("agent",w).handle("skill",C).handle("lsp",R).handle("formatter",b)}));var Eg=x.group(Q,"mcp",t=>s.gen(function*(){let e=yield*qe.Service,r=s.fn("McpHttpApi.status")(function*(){return yield*e.status()}),n=s.fn("McpHttpApi.add")(function*(y){let g=(yield*e.add(y.payload.name,y.payload.config)).status;return yield*o.decodeUnknownEffect(Lp)("status"in g?{[y.payload.name]:g}:g).pipe(s.mapError(()=>new D.BadRequest({})))}),a=s.fn("McpHttpApi.authStart")(function*(y){return yield*s.gen(function*(){return(yield*e.supportsOAuth(y.params.name))?yield*e.startAuth(y.params.name):yield*new Kn({error:`MCP server ${y.params.name} does not support OAuth`})}).pipe(s.catchTag("MCP.NotFoundError",g=>s.fail(new _e({name:g.name,message:`MCP server not found: ${g.name}`}))))}),c=s.fn("McpHttpApi.authCallback")(function*(y){return yield*e.finishAuth(y.params.name,y.payload.code).pipe(s.catchTag("MCP.NotFoundError",g=>s.fail(new _e({name:g.name,message:`MCP server not found: ${g.name}`}))))}),p=s.fn("McpHttpApi.authAuthenticate")(function*(y){return yield*s.gen(function*(){return(yield*e.supportsOAuth(y.params.name))?yield*e.authenticate(y.params.name):yield*new Kn({error:`MCP server ${y.params.name} does not support OAuth`})}).pipe(s.catchTag("MCP.NotFoundError",g=>s.fail(new _e({name:g.name,message:`MCP server not found: ${g.name}`}))))}),f=s.fn("McpHttpApi.authRemove")(function*(y){let g=yield*e.status();return y.params.name in g?(yield*e.removeAuth(y.params.name),{success:!0}):yield*new _e({name:y.params.name,message:`MCP server not found: ${y.params.name}`})}),l=s.fn("McpHttpApi.connect")(function*(y){return yield*e.connect(y.params.name).pipe(s.catchTag("MCP.NotFoundError",g=>s.fail(new _e({name:g.name,message:`MCP server not found: ${g.name}`})))),!0}),m=s.fn("McpHttpApi.disconnect")(function*(y){return yield*e.disconnect(y.params.name).pipe(s.catchTag("MCP.NotFoundError",g=>s.fail(new _e({name:g.name,message:`MCP server not found: ${g.name}`})))),!0});return t.handle("status",r).handle("add",n).handle("authStart",a).handle("authCallback",c).handle("authAuthenticate",p).handle("authRemove",f).handle("connect",l).handle("disconnect",m)}));var Ag=x.group(Q,"permission",t=>s.gen(function*(){let e=yield*Cn.Service,r=s.fn("PermissionHttpApi.list")(function*(){return yield*e.list()}),n=s.fn("PermissionHttpApi.reply")(function*(a){return yield*e.reply({requestID:a.params.requestID,reply:a.payload.reply,message:a.payload.message}).pipe(s.catchTag("Permission.NotFoundError",c=>s.fail(new sr({requestID:String(c.requestID),message:`Permission request not found: ${c.requestID}`})))),!0});return t.handle("list",r).handle("reply",n)}));var Ig=x.group(Q,"project",t=>s.gen(function*(){let e=yield*it.Service,r=yield*Fe.Service,n=s.fn("ProjectHttpApi.list")(function*(){return yield*e.list()}),a=s.fn("ProjectHttpApi.current")(function*(){return(yield*pe).project}),c=s.fn("ProjectHttpApi.initGit")(function*(){let l=yield*pe,m=yield*e.initGit({directory:l.directory,project:l.project});return m.id===l.project.id&&m.vcs===l.project.vcs&&m.worktree===l.project.worktree||(yield*Jy(l,{directory:l.directory,worktree:l.directory,project:m})),m}),p=s.fn("ProjectHttpApi.update")(function*(l){return yield*e.update({...l.payload,projectID:l.params.projectID}).pipe(s.catchTag("Project.NotFoundError",m=>s.fail(new Uo({projectID:m.projectID,message:`Project not found: ${m.projectID}`}))))}),f=s.fn("ProjectHttpApi.directories")(l=>r.directories({projectID:l.params.projectID}));return t.handle("list",n).handle("current",a).handle("initGit",c).handle("update",p).handle("directories",f)}));var wg={name:"project-copy-name",mode:"primary",permission:[],options:{},native:!0,prompt:""},Dg=x.group(Q,"projectCopyName",t=>s.gen(function*(){let e=yield*la.Service,r=yield*Me.Service,n=s.fn("ProjectCopyHttpApi.generateName")(function*(a){let c=a?.trim();if(!c)return gs.create();let p=yield*r.defaultModel().pipe(s.catch(()=>s.succeed(void 0)));if(!p)return gs.create();let f=(yield*r.getSmallModel(p.providerID))??(yield*r.getModel(p.providerID,p.modelID)),l=Y.descending(),y=(yield*e.stream({agent:wg,user:{id:Yr.ascending(),sessionID:l,role:"user",time:{created:Date.now()},agent:wg.name,model:{providerID:f.providerID,modelID:f.id}},system:[],small:!0,tools:{},model:f,sessionID:l,retries:2,messages:[{role:"user",content:`Generate a short 2-3 word name that describes this task:
|
|
19
|
+
${c}`}]}).pipe(se.filter(Mu.is.textDelta),se.map(g=>g.text),se.mkString)).trim();return y?hD(y.split(/\s+/).slice(0,3).join(" ")):gs.create()});return t.handle("generateName",a=>n(a.payload.context).pipe(s.catchCause(c=>s.logWarning("project copy name generation failed",{projectID:a.params.projectID,cause:c}).pipe(s.as(gs.create()))),s.map(c=>({name:c}))))}));function hD(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}i(hD,"slugify");function Rg(t){return t.pipe(s.mapError(e=>e instanceof Xe.OauthMissing?new Ut({name:e._tag,data:{providerID:e.providerID}}):e instanceof Xe.OauthCodeMissing?new Ut({name:e._tag,data:{providerID:e.providerID}}):e instanceof Xe.OauthCallbackFailed?new Ut({name:e._tag,data:{}}):e instanceof Xe.ValidationFailed?new Ut({name:e._tag,data:{field:e.field,message:e.message}}):new Ut({name:"BadRequest",data:{}})))}i(Rg,"mapProviderAuthError");var Cg=x.group(Q,"provider",t=>s.gen(function*(){let e=yield*At.Service,r=yield*Me.Service,n=yield*Xe.Service,a=yield*Gt.Service,c=s.fn("ProviderHttpApi.list")(function*(){let y=yield*e.get(),g=yield*na.Service.use(b=>b.get()),E=new Set(y.disabled_providers??[]),v=y.enabled_providers?new Set(y.enabled_providers):void 0,h={};for(let[b,M]of Object.entries(g))(!v||v.has(b))&&!E.has(b)&&(h[b]=M);let w=yield*r.list(),C=yield*a.all().pipe(s.orDie),R=Object.assign(dm(h,b=>Me.fromModelsDevProvider(b)),w);return{all:Object.values(R).map(Me.toPublicInfo),default:Me.defaultModelIDs(R),connected:Object.keys(R).filter(b=>b in w||C[b])}}),p=s.fn("ProviderHttpApi.auth")(function*(){return yield*n.methods()}),f=s.fn("ProviderHttpApi.authorize")(function*(y){return yield*Rg(n.authorize({providerID:y.params.providerID,method:y.payload.method,inputs:y.payload.inputs}))}),l=s.fn("ProviderHttpApi.authorizeRaw")(function*(y){let g=yield*s.orDie(y.request.text),E=yield*o.decodeUnknownEffect(o.fromJsonString(Xe.AuthorizeInput))(g).pipe(s.mapError(()=>new Ut({name:"BadRequest",data:{}}))),v=yield*f({params:y.params,payload:E});return q.jsonUnsafe(v??null)}),m=s.fn("ProviderHttpApi.callback")(function*(y){return yield*Rg(n.callback({providerID:y.params.providerID,method:y.payload.method,code:y.payload.code})),!0});return t.handle("list",c).handle("auth",p).handleRaw("authorize",l).handle("callback",m)}));var Nt={};me(Nt,{PtyProtocol:()=>Nt,REPLAY_CHUNK:()=>nd,chunks:()=>AD,decodeInput:()=>ID,metaFrame:()=>ED});var SD=new TextEncoder,vD=new TextDecoder("utf-8",{fatal:!0}),nd=64*1024;function ED(t){let e=SD.encode(JSON.stringify({cursor:t})),r=new Uint8Array(e.length+1);return r[0]=0,r.set(e,1),r}i(ED,"metaFrame");function AD(t){let e=[];for(let r=0;r<t.length;r+=nd)e.push(t.slice(r,r+nd));return e}i(AD,"chunks");function ID(t){if(typeof t=="string")return t;try{return vD.decode(t instanceof ArrayBuffer?new Uint8Array(t):t)}catch{return}}i(ID,"decodeInput");function xg(t,e){return Zs(t.headers.origin,t.headers.host,e)}i(xg,"validOrigin");var kg=s.gen(function*(){let t=yield*aa,e=yield*ca;return{directory:t?.directory,workspaceID:e}}),Hg=x.group(Q,"pty",t=>s.gen(function*(){let e=yield*wt.Service,r=yield*Fn,n=yield*wo.Service,a=yield*Ge.Service,c=Oc(h=>s.runPromise(a.invalidate(ce.Ref.make({directory:Ie.make(h)}))));yield*s.addFinalizer(()=>s.sync(c));let p=s.fnUntraced(function*(h){return yield*h.pipe(s.provide(a.get(ce.Ref.make({directory:Ie.make((yield*pe).directory)}))))}),f=s.fn("PtyHttpApi.shells")(function*(){return yield*s.promise(()=>sm.list())}),l=s.fn("PtyHttpApi.list")(function*(){return(yield*p(he.Service.use(w=>w.list()))).filter(w=>w.status==="running")}),m=s.fn("PtyHttpApi.create")(function*(h){let w=h.payload.cwd||(yield*pe).directory,C=yield*n.trigger("shell.env",{cwd:w},{env:{}});return yield*p(he.Service.use(R=>R.create({...h.payload,args:h.payload.args?[...h.payload.args]:void 0,cwd:w,env:{...h.payload.env,...C.env}})))}),y=s.fn("PtyHttpApi.get")(function*(h){return yield*p(he.Service.use(w=>w.get(h.params.ptyID))).pipe(s.catchTag("Pty.NotFoundError",w=>new Dt({ptyID:w.ptyID,message:`PTY session not found: ${w.ptyID}`})),s.flatMap(w=>w.status==="running"?s.succeed(w):new Dt({ptyID:h.params.ptyID,message:`PTY session not found: ${h.params.ptyID}`})))}),g=s.fn("PtyHttpApi.update")(function*(h){return yield*y(h),yield*p(he.Service.use(w=>w.update(h.params.ptyID,{...h.payload,size:h.payload.size?{...h.payload.size}:void 0}))).pipe(s.catchTag("Pty.NotFoundError",w=>new Dt({ptyID:w.ptyID,message:`PTY session not found: ${w.ptyID}`})))}),E=s.fn("PtyHttpApi.remove")(function*(h){return yield*y(h),yield*p(he.Service.use(w=>w.remove(h.params.ptyID))).pipe(s.catchTag("Pty.NotFoundError",w=>new Dt({ptyID:w.ptyID,message:`PTY session not found: ${w.ptyID}`}))),!0}),v=s.fn("PtyHttpApi.connectToken")(function*(h){let w=yield*ge.HttpServerRequest;return w.headers[nf]!=="1"||!xg(w,r)?yield*new Lo({message:"Invalid PTY connect token request"}):(yield*y(h),yield*e.issue({ptyID:h.params.ptyID,...yield*kg}))});return t.handle("shells",f).handle("list",l).handle("create",m).handle("get",y).handle("update",g).handle("remove",E).handle("connectToken",v)})).pipe(P.provide(Ss)),Pg=x.group(jo,"pty-connect",t=>s.gen(function*(){let e=yield*wt.Service,r=yield*Fn,n=yield*Ge.Service,a=Oc(p=>s.runPromise(n.invalidate(ce.Ref.make({directory:Ie.make(p)}))));yield*s.addFinalizer(()=>s.sync(a));let c=s.fnUntraced(function*(p){return yield*p.pipe(s.provide(n.get(ce.Ref.make({directory:Ie.make((yield*pe).directory)}))))});return t.handleRaw("connect",s.fn("PtyHttpApi.connect")(function*(p){if(!(yield*c(he.Service.use(M=>M.get(p.params.ptyID))).pipe(s.map(M=>M.status==="running"),s.catchTag("Pty.NotFoundError",()=>s.succeed(!1)))))return q.empty({status:404});let l=o.decodeUnknownOption(sy)(yield*ge.ParsedSearchParams);if(Re.isNone(l))return q.empty({status:400});let m=new URL(p.request.url,"http://localhost").searchParams.get(ti);if(m&&!(xg(p.request,r)?yield*e.consume({ticket:m,ptyID:p.params.ptyID,...yield*kg}):!1))return q.empty({status:403});let y=l.value.cursor===void 0?void 0:Number(l.value.cursor),g=y!==void 0&&Number.isSafeInteger(y)&&y>=-1?y:void 0,E=yield*s.orDie(p.request.upgrade),v=yield*E.writer,h=i(M=>E.runRaw(()=>s.void,{onOpen:v(M).pipe(s.catch(()=>s.void))}).pipe(s.timeout("1 second"),s.catchReason("SocketError","SocketCloseError",()=>s.void),s.catch(()=>s.void)),"closeAccepted");if(!(yield*$e.register(v($e.SERVER_CLOSING_EVENT()))))return yield*h($e.SERVER_CLOSING_EVENT()),q.empty();let C=yield*Ee.unbounded(),R=yield*c(he.Service.use(M=>M.attach(p.params.ptyID,{cursor:g,onData:i(Z=>Ee.offerUnsafe(C,Z),"onData"),onEnd:i(()=>Ee.offerUnsafe(C,new Le(1e3)),"onEnd")}))).pipe(s.catchTags({"Pty.NotFoundError":i(()=>h(new Le(4404,"session not found")).pipe(s.as(void 0)),"Pty.NotFoundError"),"Pty.ExitedError":i(()=>h(new Le(4404,"session not found")).pipe(s.as(void 0)),"Pty.ExitedError")}));if(!R)return q.empty();for(let M of Nt.chunks(R.replay))Ee.offerUnsafe(C,M);Ee.offerUnsafe(C,Nt.metaFrame(R.cursor)),R.activate();let b=s.gen(function*(){for(;;){let M=yield*Ee.take(C);if(yield*v(M),M instanceof Le)return}});return yield*s.race(b,E.runRaw(M=>{let Z=Nt.decodeInput(M);Z!==void 0&&R.write(Z)})).pipe(s.catchReason("SocketError","SocketCloseError",()=>s.void),s.ensuring(s.sync(()=>R.detach())),s.orDie),q.empty()}))})).pipe(P.provide(Ss));var Tg=x.group(Q,"question",t=>s.gen(function*(){let e=yield*$t.Service,r=s.fn("QuestionHttpApi.list")(function*(){return yield*e.list()}),n=s.fn("QuestionHttpApi.reply")(function*(c){return yield*e.reply({requestID:c.params.requestID,answers:c.payload.answers}).pipe(s.catchTag("Question.NotFoundError",p=>s.fail(new an({requestID:String(p.requestID),message:`Question request not found: ${p.requestID}`})))),!0}),a=s.fn("QuestionHttpApi.reject")(function*(c){return yield*e.reject(c.params.requestID).pipe(s.catchTag("Question.NotFoundError",p=>s.fail(new an({requestID:String(p.requestID),message:`Question request not found: ${p.requestID}`})))),!0});return t.handle("list",r).handle("reply",n).handle("reject",a)}));function ir(t){return t.pipe(s.mapError(e=>ja(e.message)))}i(ir,"mapStorageNotFound");function mi(t){return t.pipe(s.catchTag("SessionBusyError",e=>s.fail(new xr({sessionID:e.sessionID,message:`Session is busy: ${e.sessionID}`}))))}i(mi,"mapBusy");var qg=i(t=>s.try({try:i(()=>JSON.parse(t),"try"),catch:i(()=>new D.BadRequest({}),"catch")}),"tryParseJson"),Mg=x.group(Q,"session",t=>s.gen(function*(){let e=yield*X.Service,r=yield*Sa.Service,n=yield*Vt.Service,a=yield*Ao.Service,c=yield*fa.Service,p=yield*ma.Service,f=yield*zt.Service,l=yield*Cn.Service,m=yield*Kr.Service,y=yield*vo.Service,g=yield*Eo.Service,E=yield*Wt.Service,v=yield*xt.Scope,h=s.fn("SessionHttpApi.list")(function*(A){let ee=A.query.directory?yield*Ue.directory:void 0;return yield*e.list({directory:A.query.scope==="project"?void 0:ee,scope:A.query.scope,path:A.query.path,roots:A.query.roots,start:A.query.start,search:A.query.search,limit:A.query.limit})}),w=s.fn("SessionHttpApi.status")(function*(){return Object.fromEntries(yield*m.list())}),C=s.fn("SessionHttpApi.requireSession")(function*(A){return yield*ir(e.get(A))}),R=s.fn("SessionHttpApi.get")(function*(A){return yield*C(A.params.sessionID)}),b=s.fn("SessionHttpApi.children")(function*(A){return yield*C(A.params.sessionID),yield*e.children(A.params.sessionID)}),M=s.fn("SessionHttpApi.todo")(function*(A){return yield*C(A.params.sessionID),yield*y.get(A.params.sessionID)}),Z=s.fn("SessionHttpApi.diff")(function*(A){return yield*g.diff({sessionID:A.params.sessionID,messageID:A.query.messageID})}),Se=s.fn("SessionHttpApi.messages")(function*(A){if(A.query.before&&A.query.limit===void 0)return yield*new D.BadRequest({});if(A.query.before){let Ko=A.query.before;yield*s.try({try:i(()=>da.cursor.decode(Ko),"try"),catch:i(()=>new D.BadRequest({}),"catch")})}if(yield*C(A.params.sessionID),A.query.limit===void 0||A.query.limit===0)return yield*ir(e.messages({sessionID:A.params.sessionID}));let ee=yield*ir(da.page({sessionID:A.params.sessionID,limit:A.query.limit,before:A.query.before}));if(!ee.cursor)return ee.items;let Tr=yield*ge.HttpServerRequest,rt=Re.getOrElse(ge.toURL(Tr),()=>new URL(Tr.url,"http://localhost"));return rt.searchParams.set("limit",A.query.limit.toString()),rt.searchParams.set("before",ee.cursor),q.jsonUnsafe(ee.items,{headers:{"Access-Control-Expose-Headers":"Link, X-Next-Cursor",Link:`<${rt.toString()}>; rel="next"`,"X-Next-Cursor":ee.cursor}})}),De=s.fn("SessionHttpApi.message")(function*(A){return yield*ir(da.get({sessionID:A.params.sessionID,messageID:A.params.messageID}))}),ar=s.fn("SessionHttpApi.create")(function*(A){return yield*r.create(A.payload)}),F=s.fn("SessionHttpApi.createRaw")(function*(A){let ee=yield*s.orDie(A.request.text);if(ee.trim().length===0)return yield*ar({});let Tr=yield*qg(ee),rt=yield*o.decodeUnknownEffect(X.CreateInput)(Tr).pipe(s.mapError(()=>new D.BadRequest({}))),Ko=rt&&{...rt,permission:rt.permission?[...rt.permission]:void 0};return yield*ar({payload:Ko})}),ue=s.fn("SessionHttpApi.remove")(function*(A){return yield*ir(e.remove(A.params.sessionID)),!0}),ke=s.fn("SessionHttpApi.update")(function*(A){let ee=yield*C(A.params.sessionID);return A.payload.title!==void 0&&(yield*e.setTitle({sessionID:A.params.sessionID,title:A.payload.title})),A.payload.metadata!==void 0&&(yield*e.setMetadata({sessionID:A.params.sessionID,metadata:A.payload.metadata})),A.payload.permission!==void 0&&(yield*e.setPermission({sessionID:A.params.sessionID,permission:Cn.merge(ee.permission??[],A.payload.permission)})),A.payload.time?.archived!==void 0&&(yield*e.setArchived({sessionID:A.params.sessionID,time:A.payload.time.archived})),yield*C(A.params.sessionID)}),ne=s.fn("SessionHttpApi.fork")(function*(A){return yield*ir(e.fork({sessionID:A.params.sessionID,messageID:A.payload?.messageID}))}),Ve=s.fn("SessionHttpApi.forkRaw")(function*(A){let ee=yield*s.orDie(A.request.text);if(ee.trim().length===0)return yield*ne({params:A.params});let Tr=yield*qg(ee),rt=yield*o.decodeUnknownEffect(Np)(Tr).pipe(s.mapError(()=>new D.BadRequest({})));return yield*ne({params:A.params,payload:rt})}),nc=s.fn("SessionHttpApi.abort")(function*(A){return yield*n.cancel(A.params.sessionID),!0}),mh=s.fn("SessionHttpApi.init")(function*(A){return yield*C(A.params.sessionID),yield*n.command({sessionID:A.params.sessionID,messageID:A.payload.messageID,model:`${A.payload.providerID}/${A.payload.modelID}`,command:Jr.Default.INIT,arguments:""}).pipe(s.mapError(()=>new D.BadRequest({}))),!0}),lh=s.fn("SessionHttpApi.share")(function*(A){return yield*C(A.params.sessionID),yield*r.share(A.params.sessionID).pipe(s.mapError(()=>new D.InternalServerError({}))),yield*C(A.params.sessionID)}),fh=s.fn("SessionHttpApi.unshare")(function*(A){return yield*C(A.params.sessionID),yield*r.unshare(A.params.sessionID).pipe(s.mapError(()=>new D.InternalServerError({}))),yield*C(A.params.sessionID)}),yh=s.fn("SessionHttpApi.summarize")(function*(A){yield*a.cleanup(yield*C(A.params.sessionID));let ee=yield*ir(e.messages({sessionID:A.params.sessionID})),Tr=yield*f.defaultAgent(),rt=ee.findLast(Ko=>Ko.info.role==="user")?.info.agent??Tr;return yield*c.create({sessionID:A.params.sessionID,agent:rt,model:{providerID:A.payload.providerID,modelID:A.payload.modelID},auto:A.payload.auto??!1}),yield*n.loop({sessionID:A.params.sessionID}),!0}),gh=s.fn("SessionHttpApi.prompt")(function*(A){yield*C(A.params.sessionID);let ee=yield*n.prompt({...A.payload,sessionID:A.params.sessionID}).pipe(s.mapError(()=>new D.BadRequest({})));return q.stream(io(JSON.stringify(ee)).pipe(Ur),{contentType:"application/json"})}),hh=s.fn("SessionHttpApi.promptAsync")(function*(A){return yield*C(A.params.sessionID),yield*n.prompt({...A.payload,sessionID:A.params.sessionID}).pipe(s.catchCause(ee=>s.gen(function*(){yield*s.logError("prompt_async failed",{sessionID:A.params.sessionID,cause:ee}),yield*E.publish(X.Event.Error,{sessionID:A.params.sessionID,error:new ea.Unknown({message:_t.pretty(ee)}).toObject()})})),s.forkIn(v,{startImmediately:!0})),k.NoContent.make()}),Sh=s.fn("SessionHttpApi.command")(function*(A){return yield*C(A.params.sessionID),yield*n.command({...A.payload,sessionID:A.params.sessionID}).pipe(s.mapError(()=>new D.BadRequest({})))}),vh=s.fn("SessionHttpApi.shell")(function*(A){return yield*C(A.params.sessionID),yield*mi(n.shell({...A.payload,sessionID:A.params.sessionID}))}),Eh=s.fn("SessionHttpApi.revert")(function*(A){return yield*C(A.params.sessionID),yield*mi(a.revert({sessionID:A.params.sessionID,...A.payload}))}),Ah=s.fn("SessionHttpApi.unrevert")(function*(A){return yield*C(A.params.sessionID),yield*mi(a.unrevert({sessionID:A.params.sessionID}))}),Ih=s.fn("SessionHttpApi.permissionRespond")(function*(A){return yield*C(A.params.sessionID),yield*l.reply({requestID:A.params.permissionID,reply:A.payload.response}).pipe(s.catchTag("Permission.NotFoundError",ee=>s.fail(new sr({requestID:String(ee.requestID),message:`Permission request not found: ${ee.requestID}`})))),!0}),wh=s.fn("SessionHttpApi.deleteMessage")(function*(A){return yield*C(A.params.sessionID),yield*mi(p.assertNotBusy(A.params.sessionID)),yield*e.removeMessage(A.params),!0}),Dh=s.fn("SessionHttpApi.deletePart")(function*(A){return yield*C(A.params.sessionID),yield*e.removePart(A.params),!0}),Rh=s.fn("SessionHttpApi.updatePart")(function*(A){yield*C(A.params.sessionID);let ee=A.payload;return ee.id!==A.params.partID||ee.messageID!==A.params.messageID||ee.sessionID!==A.params.sessionID?yield*new D.BadRequest({}):yield*e.updatePart(ee)});return t.handle("list",h).handle("status",w).handle("get",R).handle("children",b).handle("todo",M).handle("diff",Z).handle("messages",Se).handle("message",De).handleRaw("create",F).handle("remove",ue).handle("update",ke).handleRaw("fork",Ve).handle("abort",nc).handle("init",mh).handle("share",lh).handle("unshare",fh).handle("summarize",yh).handle("prompt",gh).handle("promptAsync",hh).handle("command",Sh).handle("shell",vh).handle("revert",Eh).handle("unrevert",Ah).handle("permissionRespond",Ih).handle("deleteMessage",wh).handle("deletePart",Dh).handle("updatePart",Rh)}));var Og=x.group(Q,"sync",t=>s.gen(function*(){let e=yield*fe.Service,r=yield*X.Service,n=yield*xt.Scope,a=yield*Wt.Service,{db:c}=yield*Fr.Service,p=s.fn("SyncHttpApi.start")(function*(){return yield*e.startWorkspaceSyncing((yield*pe).project.id).pipe(s.ignore,s.forkIn(n)),!0}),f=s.fn("SyncHttpApi.replay")(function*(y){let g=y.payload.events.map(h=>({id:h.id,aggregateID:h.aggregateID,seq:h.seq,type:h.type,data:{...h.data}})),E=g[0].aggregateID;yield*s.logInfo("sync replay requested",{sessionID:E,events:g.length,first:g[0]?.seq,last:g.at(-1)?.seq,directory:y.payload.directory});let v=yield*Lc;return yield*a.replayAll(g,{ownerID:v,strictOwner:!0}),yield*s.logInfo("sync replay complete",{sessionID:E,events:g.length,first:g[0]?.seq,last:g.at(-1)?.seq}),{sessionID:E}}),l=s.fn("SyncHttpApi.steal")(function*(y){let g=yield*Lc;return g?(yield*r.setWorkspace({sessionID:y.payload.sessionID,workspaceID:g}),yield*s.logInfo("sync session stolen",{sessionID:y.payload.sessionID,workspaceID:g}),{sessionID:y.payload.sessionID}):yield*new D.BadRequest({})}),m=s.fn("SyncHttpApi.history")(function*(y){let g=Object.entries(y.payload);return yield*c.select().from(ls).where(g.length>0?Hu(ku(...g.map(([E,v])=>xu(Yi(ls.aggregate_id,E),Pu(ls.seq,v))))):void 0).orderBy(bu(ls.seq)).all().pipe(s.orDie)});return t.handle("start",p).handle("replay",f).handle("steal",l).handle("history",m)}));var DD={session_new:"session.new",session_share:"session.share",session_interrupt:"session.interrupt",session_compact:"session.compact",messages_page_up:"session.page.up",messages_page_down:"session.page.down",messages_line_up:"session.line.up",messages_line_down:"session.line.down",messages_half_page_up:"session.half.page.up",messages_half_page_down:"session.half.page.down",messages_first:"session.first",messages_last:"session.last",agent_cycle:"agent.cycle"},Lg=x.group(Q,"tui",t=>s.gen(function*(){let e=yield*Wt.Service,r=yield*X.Service,n=i(R=>e.publish(ie.CommandExecute,{command:R}),"publishCommand"),a=s.fn("TuiHttpApi.appendPrompt")(function*(R){return yield*e.publish(ie.PromptAppend,R.payload),!0}),c=s.fn("TuiHttpApi.openHelp")(function*(){return yield*n("help.show"),!0}),p=s.fn("TuiHttpApi.openSessions")(function*(){return yield*n("session.list"),!0}),f=s.fn("TuiHttpApi.openThemes")(function*(){return yield*n("session.list"),!0}),l=s.fn("TuiHttpApi.openModels")(function*(){return yield*n("model.list"),!0}),m=s.fn("TuiHttpApi.submitPrompt")(function*(){return yield*n("prompt.submit"),!0}),y=s.fn("TuiHttpApi.clearPrompt")(function*(){return yield*n("prompt.clear"),!0}),g=s.fn("TuiHttpApi.executeCommand")(function*(R){return yield*n(DD[R.payload.command]),!0}),E=s.fn("TuiHttpApi.showToast")(function*(R){return yield*e.publish(ie.ToastShow,R.payload),!0}),v=s.fn("TuiHttpApi.publish")(function*(R){return R.payload.type===ie.PromptAppend.type&&(yield*e.publish(ie.PromptAppend,R.payload.properties)),R.payload.type===ie.CommandExecute.type&&(yield*e.publish(ie.CommandExecute,R.payload.properties)),R.payload.type===ie.ToastShow.type&&(yield*e.publish(ie.ToastShow,R.payload.properties)),R.payload.type===ie.SessionSelect.type&&(yield*e.publish(ie.SessionSelect,R.payload.properties)),!0}),h=s.fn("TuiHttpApi.selectSession")(function*(R){return R.payload.sessionID.startsWith("ses")?(yield*ir(r.get(R.payload.sessionID)),yield*e.publish(ie.SessionSelect,R.payload),!0):yield*new D.BadRequest({})}),w=s.fn("TuiHttpApi.controlNext")(function*(){return yield*s.promise(()=>ly())}),C=s.fn("TuiHttpApi.controlResponse")(function*(R){return fy(R.payload),!0});return t.handle("appendPrompt",a).handle("openHelp",c).handle("openSessions",p).handle("openThemes",f).handle("openModels",l).handle("submitPrompt",m).handle("clearPrompt",y).handle("executeCommand",g).handle("showToast",E).handle("publish",v).handle("selectSession",h).handle("controlNext",w).handle("controlResponse",C)}));var RD=50,CD=o.Struct({id:zu.ID,order:o.Union([o.Literal("asc"),o.Literal("desc")]),direction:o.Union([o.Literal("previous"),o.Literal("next")])}),xD=o.decodeUnknownSync(CD),od={encode(t,e,r){return Buffer.from(JSON.stringify({id:t.id,order:e,direction:r})).toString("base64url")},decode(t){return xD(JSON.parse(Buffer.from(t,"base64url").toString("utf8")))}},Ug=x.group(V,"server.message",t=>s.gen(function*(){let e=yield*Et.Service;return t.handle("session.messages",s.fn(function*(r){if(r.query.cursor&&r.query.order!==void 0)return yield*new Lt({message:"Cursor cannot be combined with order"});let n=yield*s.try({try:i(()=>r.query.cursor?od.decode(r.query.cursor):void 0,"try"),catch:i(()=>new Lt({message:"Invalid cursor"}),"catch")}),a=n?.order??r.query.order??"desc",c=yield*e.messages({sessionID:r.params.sessionID,limit:r.query.limit??RD,order:a,cursor:n?{id:n.id,direction:n.direction}:void 0}).pipe(s.catchTag("Session.NotFoundError",l=>s.fail(new N({sessionID:l.sessionID,message:`Session not found: ${l.sessionID}`}))),s.catchTag("Session.MessageDecodeError",l=>{let m=`err_${crypto.randomUUID().slice(0,8)}`;return s.logError("failed to decode session message").pipe(s.annotateLogs({ref:m,sessionID:l.sessionID,messageID:l.messageID}),s.andThen(s.fail(new tt({message:"Unexpected server error. Check server logs for details.",ref:m}))))})),p=c[0],f=c.at(-1);return{data:c,cursor:{previous:p?od.encode(p,a,"previous"):void 0,next:f?od.encode(f,a,"next"):void 0}}}))}));var Ng=x.group(V,"server.model",t=>s.gen(function*(){return t.handle("model.list",s.fn(function*(){let e=yield*fs.Service;return yield*J(e.model.available())}))}));var _g=x.group(V,"server.provider",t=>s.gen(function*(){return t.handle("provider.list",s.fn(function*(){let e=yield*fs.Service;return yield*J(e.provider.available())})).handle("provider.get",s.fn(function*(e){let n=yield*(yield*fs.Service).provider.get(e.params.providerID);return n?yield*J(s.succeed(n)):yield*new Mo({providerID:e.params.providerID,message:`Provider not found: ${e.params.providerID}`})}))}));var kD=50,HD=50,Bg=x.group(V,"server.session",t=>s.gen(function*(){let e=yield*Et.Service;return t.handle("session.list",s.fn(function*(r){let n=r.query.cursor!==void 0?yield*Zn.parse(r.query.cursor).pipe(s.mapError(()=>new Lt({message:"Invalid cursor"}))):r.query,a=yield*e.list({...n,workspaceID:n.workspace,limit:r.query.limit??kD}),c=a[0],p=a.at(-1);return{data:a,cursor:{previous:c?Zn.make({...n,anchor:{id:c.id,time:ns.toEpochMillis(c.time.created),direction:"previous"}}):void 0,next:p?Zn.make({...n,anchor:{id:p.id,time:ns.toEpochMillis(p.time.created),direction:"next"}}):void 0}}})).handle("session.create",s.fn(function*(r){return{data:yield*e.create({id:r.payload.id,agent:r.payload.agent,model:r.payload.model,location:r.payload.location??{directory:Ie.make(process.cwd())}})}})).handle("session.active",s.fn(function*(){return{data:Object.fromEntries(Array.from(yield*e.active,r=>[r,{type:"running"}]))}})).handle("session.get",s.fn(function*(r){return{data:yield*e.get(r.params.sessionID).pipe(s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})))}})).handle("session.switchAgent",s.fn(function*(r){return yield*e.switchAgent({sessionID:r.params.sessionID,agent:r.payload.agent}).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})))),k.NoContent.make()})).handle("session.switchModel",s.fn(function*(r){return yield*e.switchModel({sessionID:r.params.sessionID,model:r.payload.model}).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})))),k.NoContent.make()})).handle("session.prompt",s.fn(function*(r){return{data:yield*e.prompt({sessionID:r.params.sessionID,id:r.payload.id,prompt:r.payload.prompt,delivery:r.payload.delivery,resume:r.payload.resume}).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`}))),s.catchTag("Session.PromptConflictError",n=>s.fail(new qo({message:`Prompt message ID conflicts with an existing durable record: ${n.messageID}`,resource:n.messageID}))))}})).handle("session.compact",s.fn(function*(r){return yield*e.compact({sessionID:r.params.sessionID}).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`}))),s.catchTag("Session.OperationUnavailableError",n=>s.fail(new mt({message:`Session ${n.operation} is not available yet`,service:`session.${n.operation}`})))),k.NoContent.make()})).handle("session.wait",s.fn(function*(r){return yield*e.wait(r.params.sessionID).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`}))),s.catchTag("Session.OperationUnavailableError",n=>s.fail(new mt({message:`Session ${n.operation} is not available yet`,service:`session.${n.operation}`})))),k.NoContent.make()})).handle("session.revert.stage",s.fn(function*(r){return{data:yield*e.revert.stage({...r.params,...r.payload}).pipe(s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})),s.catchTag("Session.MessageNotFoundError",n=>new sn({sessionID:n.sessionID,messageID:n.messageID,message:`Message not found: ${n.messageID}`})),s.catchTag("Snapshot.Error",n=>{let a=`err_${crypto.randomUUID().slice(0,8)}`;return s.logError("failed to stage session revert",{cause:n}).pipe(s.andThen(s.fail(new tt({message:"Unexpected server error. Check server logs for details.",ref:a}))))}))}})).handle("session.revert.clear",s.fn(function*(r){return yield*e.revert.clear(r.params.sessionID).pipe(s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})),s.catchTag("Snapshot.Error",n=>{let a=`err_${crypto.randomUUID().slice(0,8)}`;return s.logError("failed to clear session revert",{cause:n}).pipe(s.andThen(s.fail(new tt({message:"Unexpected server error. Check server logs for details.",ref:a}))))})),k.NoContent.make()})).handle("session.revert.commit",s.fn(function*(r){return yield*e.revert.commit(r.params.sessionID).pipe(s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`}))),k.NoContent.make()})).handle("session.context",s.fn(function*(r){return{data:yield*e.context(r.params.sessionID).pipe(s.catchTag("Session.NotFoundError",n=>s.fail(new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`}))),s.catchTag("Session.MessageDecodeError",n=>{let a=`err_${crypto.randomUUID().slice(0,8)}`;return s.logError("failed to decode session message").pipe(s.annotateLogs({ref:a,sessionID:n.sessionID,messageID:n.messageID}),s.andThen(s.fail(new tt({message:"Unexpected server error. Check server logs for details.",ref:a}))))}))}})).handle("session.history",s.fn(function*(r){return yield*e.history({sessionID:r.params.sessionID,after:r.query.after,limit:r.query.limit??HD}).pipe(s.map(n=>({data:n.events,hasMore:n.hasMore})),s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})))})).handle("session.events",s.fn(r=>s.succeed(e.events({sessionID:r.params.sessionID,after:r.query.after}).pipe(se.orDie)))).handle("session.interrupt",s.fn(function*(r){return yield*e.interrupt(r.params.sessionID),k.NoContent.make()})).handle("session.message",s.fn(function*(r){let n=yield*e.message(r.params);return n?{data:n}:yield*new sn({sessionID:r.params.sessionID,messageID:r.params.messageID,message:`Message not found: ${r.params.messageID}`})}))}));function sd(t){return new Wn({requestID:t,message:`Permission request not found: ${t}`})}i(sd,"missingRequest");var Fg=x.group(V,"server.permission",t=>s.gen(function*(){return t.handle("permission.request.list",s.fn(function*(){return yield*J((yield*fo.Service).list())})).handle("session.permission.create",s.fn(function*(e){return{data:yield*(yield*fo.Service).ask({id:e.payload.id,sessionID:e.params.sessionID,action:e.payload.action,resources:e.payload.resources,save:e.payload.save,metadata:e.payload.metadata,source:e.payload.source,agent:e.payload.agent}).pipe(s.catchTag("Session.NotFoundError",n=>new N({sessionID:n.sessionID,message:`Session not found: ${n.sessionID}`})))}})).handle("session.permission.list",s.fn(function*(e){return{data:yield*(yield*fo.Service).forSession(e.params.sessionID)}})).handle("session.permission.get",s.fn(function*(e){let r=yield*(yield*fo.Service).get(e.params.requestID);return!r||r.sessionID!==e.params.sessionID?yield*sd(e.params.requestID):{data:r}})).handle("session.permission.reply",s.fn(function*(e){let r=yield*fo.Service,n=yield*r.get(e.params.requestID);return!n||n.sessionID!==e.params.sessionID?yield*sd(e.params.requestID):(yield*r.reply({requestID:e.params.requestID,reply:e.payload.reply,message:e.payload.message}).pipe(s.catchTag("PermissionV2.NotFoundError",()=>sd(e.params.requestID))),k.NoContent.make())})).handle("permission.saved.list",s.fn(function*(e){let r=yield*ce.Service;return{data:yield*(yield*hs.Service).list({projectID:e.query.projectID??r.project.id})}})).handle("permission.saved.remove",s.fn(function*(e){return yield*(yield*hs.Service).remove(e.params.id),k.NoContent.make()}))}));var jg=x.group(V,"server.fs",t=>s.gen(function*(){return t.handleRaw("fs.read",e=>s.gen(function*(){let r=yield*(yield*Wr.Service).read({path:vt.make(decodeURIComponent(new URL(e.request.url,"http://localhost").pathname.slice(13)))});return q.uint8Array(r.content,{contentType:r.mime})})).handle("fs.list",e=>J(s.gen(function*(){return yield*(yield*Wr.Service).list(e.query)}))).handle("fs.find",e=>J(s.gen(function*(){return yield*(yield*Wr.Service).find(e.query)})))}));var Gg=x.group(V,"server.command",t=>t.handle("command.list",()=>J(Fu.Service.use(e=>e.list()))));var Wg=x.group(V,"server.skill",t=>t.handle("skill.list",()=>J(ra.Service.use(e=>e.list()))));var PD=256;function TD(t){return{_tag:"Event",event:"message",id:void 0,data:JSON.stringify(o.encodeUnknownSync(Ty)(t))}}i(TD,"eventData");var $g=x.group(V,"server.event",t=>s.gen(function*(){let e=yield*le.Service;return t.handleRaw("event.subscribe",()=>s.gen(function*(){let r={id:le.ID.create(),type:"server.connected",data:{}},n=se.unwrap(s.gen(function*(){let c=yield*le.allBounded(e,PD);return se.make(r).pipe(se.concat(c))})).pipe(se.map(TD),se.pipeThroughChannel(po())),a=se.tick("15 seconds").pipe(se.map(()=>`: heartbeat
|
|
20
|
+
|
|
21
|
+
`));return q.stream(n.pipe(se.merge(a,{haltStrategy:"left"}),se.encodeText),{contentType:"text/event-stream",headers:{"Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no","X-Content-Type-Options":"nosniff"}})}))}));var Vg=x.group(V,"server.agent",t=>t.handle("agent.list",()=>s.gen(function*(){return yield*J(Ru.Service.use(e=>e.all()))})));var zg=x.group(V,"server.health",t=>t.handle("health.get",()=>s.succeed({healthy:!0})));var Qg=s.gen(function*(){let t=yield*ce.Service;return{directory:t.directory,workspaceID:t.workspaceID}}),Yg=x.group(V,"server.pty",t=>s.gen(function*(){let e=yield*wt.Service,r=yield*Fn,n=yield*nr.Service;return t.handle("pty.list",s.fn(function*(){return yield*J((yield*he.Service).list())})).handle("pty.create",s.fn(function*(a){let c=yield*he.Service,p=yield*ce.Service,f=a.payload.cwd||p.directory;return yield*J(c.create({...a.payload,args:a.payload.args?[...a.payload.args]:void 0,cwd:f,env:{...a.payload.env,...yield*n.get({directory:p.directory,cwd:f})}}))})).handle("pty.get",s.fn(function*(a){let c=yield*he.Service;return yield*J(c.get(a.params.ptyID).pipe(s.catchTag("Pty.NotFoundError",()=>new lt({ptyID:a.params.ptyID,message:`PTY session not found: ${a.params.ptyID}`}))))})).handle("pty.update",s.fn(function*(a){let c=yield*he.Service;return yield*J(c.update(a.params.ptyID,{...a.payload,size:a.payload.size?{...a.payload.size}:void 0}).pipe(s.catchTag("Pty.NotFoundError",()=>new lt({ptyID:a.params.ptyID,message:`PTY session not found: ${a.params.ptyID}`}))))})).handle("pty.remove",s.fn(function*(a){return yield*(yield*he.Service).remove(a.params.ptyID).pipe(s.catchTag("Pty.NotFoundError",()=>new lt({ptyID:a.params.ptyID,message:`PTY session not found: ${a.params.ptyID}`}))),k.NoContent.make()})).handle("pty.connectToken",s.fn(function*(a){let c=yield*ge.HttpServerRequest;return c.headers[pf]!==df||!Zs(c.headers.origin,c.headers.host,r)?yield*new Vn({message:"Invalid PTY connect token request"}):(yield*(yield*he.Service).get(a.params.ptyID).pipe(s.catchTag("Pty.NotFoundError",()=>new lt({ptyID:a.params.ptyID,message:`PTY session not found: ${a.params.ptyID}`}))),yield*J(e.issue({ptyID:a.params.ptyID,...yield*Qg})))})).handleRaw("pty.connect",s.fn("PtyHandler.connect")(function*(a){let c=yield*he.Service;if(!(yield*c.get(a.params.ptyID).pipe(s.as(!0),s.catchTag("Pty.NotFoundError",()=>s.succeed(!1)))))return q.empty({status:404});let f=new URL(a.request.url,"http://localhost"),l=f.searchParams.get(Fa);if(l&&!(Zs(a.request.headers.origin,a.request.headers.host,r)?yield*e.consume({ticket:l,ptyID:a.params.ptyID,...yield*Qg}):!1))return q.empty({status:403});let m=f.searchParams.get("cursor"),y=m===null?void 0:Number(m),g=y!==void 0&&Number.isSafeInteger(y)&&y>=-1?y:void 0,E=yield*s.orDie(a.request.upgrade),v=yield*E.writer,h=i(b=>E.runRaw(()=>s.void,{onOpen:v(b).pipe(s.catch(()=>s.void))}).pipe(s.timeout("1 second"),s.catchReason("SocketError","SocketCloseError",()=>s.void),s.catch(()=>s.void)),"closeAccepted"),w=yield*Ee.unbounded(),C=yield*c.attach(a.params.ptyID,{cursor:g,onData:i(b=>Ee.offerUnsafe(w,b),"onData"),onEnd:i(()=>Ee.offerUnsafe(w,new Le(1e3)),"onEnd")}).pipe(s.catchTags({"Pty.NotFoundError":i(()=>h(new Le(4404,"session not found")).pipe(s.as(void 0)),"Pty.NotFoundError"),"Pty.ExitedError":i(()=>h(new Le(4404,"session exited")).pipe(s.as(void 0)),"Pty.ExitedError")}));if(!C)return q.empty();for(let b of Nt.chunks(C.replay))Ee.offerUnsafe(w,b);Ee.offerUnsafe(w,Nt.metaFrame(C.cursor)),C.activate();let R=s.gen(function*(){for(;;){let b=yield*Ee.take(w);if(yield*v(b),b instanceof Le)return}});return yield*s.race(R,E.runRaw(b=>{let M=Nt.decodeInput(b);M!==void 0&&C.write(M)})).pipe(s.catchReason("SocketError","SocketCloseError",()=>s.void),s.ensuring(s.sync(()=>C.detach())),s.orDie),q.empty()}))}));function id(t){return new $n({requestID:t,message:`Question request not found: ${t}`})}i(id,"missingRequest");var Kg=x.group(V,"server.question",t=>s.gen(function*(){let e=s.fnUntraced(function*(r,n,a){let c=yield*sa.Service,p=(yield*c.list()).find(f=>f.id===n);return!p||p.sessionID!==r?yield*id(n):yield*a(c)});return t.handle("question.request.list",s.fn(function*(){return yield*J((yield*sa.Service).list())})).handle("session.question.list",s.fn(function*(r){return{data:(yield*(yield*sa.Service).list()).filter(a=>a.sessionID===r.params.sessionID)}})).handle("session.question.reply",s.fn(function*(r){return yield*e(r.params.sessionID,r.params.requestID,n=>n.reply({requestID:r.params.requestID,answers:r.payload.answers}).pipe(s.catchTag("QuestionV2.NotFoundError",()=>id(r.params.requestID)))),k.NoContent.make()})).handle("session.question.reject",s.fn(function*(r){return yield*e(r.params.sessionID,r.params.requestID,n=>n.reject(r.params.requestID).pipe(s.catchTag("QuestionV2.NotFoundError",()=>id(r.params.requestID)))),k.NoContent.make()}))}));var Xg=x.group(V,"server.reference",t=>t.handle("reference.list",()=>J(Ju.Service.use(e=>e.list()))));var Jg=x.group(V,"server.location",t=>t.handle("location.get",s.fn(function*(){let e=yield*ce.Service;return new ce.Info({directory:e.directory,workspaceID:e.workspaceID,project:e.project})})));var Zg=i(t=>t.pipe(s.mapError(()=>new Pe({message:"Authentication failed",kind:"integration_authorization"}))),"authorize"),eh=x.group(V,"server.integration",t=>s.gen(function*(){return t.handle("integration.list",s.fn(function*(){let e=yield*je.Service;return yield*J(e.list())})).handle("integration.get",s.fn(function*(e){let r=yield*je.Service;return yield*J(r.get(e.params.integrationID))})).handle("integration.connect.key",s.fn(function*(e){let r=yield*je.Service;return yield*Zg(r.connection.key({integrationID:e.params.integrationID,key:e.payload.key,label:e.payload.label})),k.NoContent.make()})).handle("integration.connect.oauth",s.fn(function*(e){let r=yield*je.Service;return yield*J(Zg(r.connection.oauth({integrationID:e.params.integrationID,methodID:e.payload.methodID,inputs:e.payload.inputs,label:e.payload.label})))})).handle("integration.attempt.status",s.fn(function*(e){let r=yield*je.Service;return yield*J(r.attempt.status(e.params.attemptID))})).handle("integration.attempt.complete",s.fn(function*(e){return yield*(yield*je.Service).attempt.complete({attemptID:e.params.attemptID,code:e.payload.code}).pipe(s.mapError(n=>new Pe({message:n._tag==="Integration.CodeRequired"?"Authorization code is required":"Authentication failed",kind:n._tag==="Integration.CodeRequired"?"integration_code_required":"integration_authorization"}))),k.NoContent.make()})).handle("integration.attempt.cancel",s.fn(function*(e){return yield*(yield*je.Service).attempt.cancel(e.params.attemptID),k.NoContent.make()}))}));var th=x.group(V,"server.credential",t=>t.handle("credential.update",s.fn(function*(e){return yield*(yield*je.Service).connection.update(e.params.credentialID,{label:e.payload.label}),k.NoContent.make()})).handle("credential.remove",s.fn(function*(e){return yield*(yield*je.Service).connection.remove(e.params.credentialID),k.NoContent.make()})));var rh=x.group(V,"server.projectCopy",t=>s.succeed(t.handle("projectCopy.create",e=>s.gen(function*(){let r=yield*Pt.Service,n=yield*ce.Service;return yield*ad(r.create({...e.payload,projectID:e.params.projectID,sourceDirectory:n.project.directory}))})).handle("projectCopy.remove",e=>Pt.Service.use(r=>ad(r.remove({...e.payload,projectID:e.params.projectID})).pipe(s.as(k.NoContent.make())))).handle("projectCopy.refresh",e=>Pt.Service.use(r=>ad(r.refresh({projectID:e.params.projectID})).pipe(s.as(k.NoContent.make()))))));function ad(t){return t.pipe(s.mapError(e=>new eo({name:"ProjectCopyError",data:{message:bD(e),forceRequired:e instanceof uo.WorktreeError?e.forceRequired:void 0}})))}i(ad,"badRequest");function bD(t){return t instanceof Pt.SourceDirectoryNotFoundError?`Project copy source not found: ${t.directory}`:t instanceof Pt.DestinationExistsError?`Project copy destination already exists: ${t.directory}`:t instanceof Pt.DirectoryUnavailableError?`Project copy directory unavailable: ${t.directory}`:t instanceof Pt.InvalidDirectoryError?`Invalid project copy directory: ${t.directory}`:t instanceof Pt.StrategyUnavailableError?`Project copy strategy unavailable: ${t.strategy}`:t.message}i(bD,"message");var nh=P.mergeAll(zg,Jg,Vg,Bg,Ug,Ng,_g,eh,th,Fg,jg,Gg,Wg,$g,Yg,Kg,Xg,rh);var cd=1024;function qD(t){return t.length<=cd?t:t.slice(0,cd)+`... (${t.length-cd} more chars)`}i(qD,"truncateReason");var oh=ye.layerSchemaErrorTransform(Jn,t=>{let e=qD(t.cause.message);return s.logWarning("schema rejection").pipe(s.annotateLogs({kind:t.kind,reason:e}),s.andThen(s.fail(new Pe({message:e,kind:t.kind}))))});var sh=x.group(Q,"workspace",t=>s.gen(function*(){let e=yield*fe.Service,r=s.fn("WorkspaceHttpApi.adapters")(function*(){let m=yield*pe;return yield*s.sync(()=>qm(m.project.id))}),n=s.fn("WorkspaceHttpApi.list")(function*(){return yield*e.list((yield*pe).project)}),a=s.fn("WorkspaceHttpApi.create")(function*(m){let y=yield*pe;return yield*e.create({...m.payload,extra:m.payload.extra??null,projectID:y.project.id}).pipe(s.catchCause(g=>{let E=g.reasons.find(_t.isDieReason),v=g.reasons.find(_t.isFailReason),h=E?.defect??v?.error,w=h instanceof Error?h.message:"Workspace creation failed";return s.fail(new pi({name:"WorkspaceCreateError",data:{message:w}}))}))}),c=s.fn("WorkspaceHttpApi.syncList")(function*(){yield*e.syncList((yield*pe).project)}),p=s.fn("WorkspaceHttpApi.status")(function*(){let m=new Set((yield*e.list((yield*pe).project)).map(y=>y.id));return(yield*e.status()).filter(y=>m.has(y.workspaceID))}),f=s.fn("WorkspaceHttpApi.remove")(function*(m){return yield*e.remove(m.params.id)}),l=s.fn("WorkspaceHttpApi.warp")(function*(m){yield*e.sessionWarp({workspaceID:m.payload.id,sessionID:m.payload.sessionID,copyChanges:m.payload.copyChanges}).pipe(s.mapError(y=>y instanceof fe.WorkspaceNotFoundError?ja(y.message):y instanceof at.PatchApplyError?new kr({name:"VcsApplyError",data:{message:y.message,reason:y.reason}}):new ci({name:"WorkspaceWarpError",data:{message:y.message}})))});return t.handle("adapters",r).handle("list",n).handle("create",a).handle("syncList",c).handle("status",p).handle("remove",f).handle("warp",l)}));var ih=Ce.middleware(t=>s.gen(function*(){let e=yield*t,r=e.headers["access-control-allow-origin"];if(!r||r==="*")return e;let n=e.headers.vary;if(!n)return q.setHeader(e,"vary","Origin");let a=n.split(",").map(c=>c.trim().toLowerCase());return a.includes("origin")||a.includes("*")?e:q.setHeader(e,"vary",`${n}, Origin`)}),{global:!0});var ah=Ce.middleware()(t=>t.pipe(s.catchCause(e=>{let r=e.reasons.filter(_t.isDieReason).find(c=>!(q.isHttpServerResponse(c.defect)||au.isHttpServerError(c.defect)||Cc.isRespondable(c.defect)));if(!r)return s.failCause(e);let n=r.defect;if(go.JsonError.isInstance(n)||go.InvalidError.isInstance(n)||go.FrontmatterError.isInstance(n)||go.DirectoryTypoError.isInstance(n)||go.RemoteAuthError.isInstance(n))return s.succeed(q.jsonUnsafe(n.toObject(),{status:400}));let a=`err_${crypto.randomUUID().slice(0,8)}`;return s.logError("failed",{ref:a,error:n,cause:_t.pretty(e)}).pipe(s.as(q.jsonUnsafe(new ea.Unknown({message:"Unexpected server error. Check server logs for details.",ref:a}).toObject(),{status:500})))}))).layer;var MD=new Set(["GET","HEAD","OPTIONS"]),ch=Ce.middleware()(s.gen(function*(){let{db:t}=yield*Fr.Service;return e=>s.gen(function*(){let r=yield*ge.HttpServerRequest;if(!ms.OPENCODE_WORKSPACE_ID||MD.has(r.method))return yield*e;let n=yield*qp(t),a=yield*e,c=Af(n,yield*qp(t));return Object.keys(c).length===0?a:q.setHeader(a,bp,JSON.stringify(c))})})).layer;var OD=oe.makeUnsafe(new Map),LD=i(t=>Ce.middleware(yu.cors({allowedOrigins:i(e=>Dp(e,t),"allowedOrigins"),maxAge:86400}),{global:!0}),"cors"),ph=hf.layer.pipe(P.provide(Ne.Config.layer)),pd=Sf.pipe(P.provide(Ne.Config.layer)),UD=vf.pipe(P.provide(Ne.Config.layer)),ND=Hp.pipe(P.provide(Ne.Config.layer)),dd=Gf.pipe(P.provide(pu)),_D=x.layer(Hr).pipe(P.provide([og,sg,Sg]),P.provide(jp),P.provide(pd)),BD=x.layer(Bo).pipe(P.provide(Ky),P.provide([pd,dd,Ga])),FD=x.layer(jo).pipe(P.provide(Pg),P.provide([UD,dd,Ga])),jD=x.layer(Q).pipe(P.provide([ng,Zy,ig,hg,vg,Eg,Ig,Dg,Hg,Tg,Ag,Cg,Mg,Og,Lg,sh])),GD=jD.pipe(P.provide([pd,dd,Ga,jp])),WD=x.layer(V).pipe(P.provide(nh),P.provide(zs.layer),P.provide([ND,oh])),$D=Js(()=>q.jsonUnsafe(d.fromApi(Ya))),VD=Ce.use(t=>t.add("GET","/doc",()=>s.succeed($D()))).pipe(P.provide(ph)),zD=Ce.use(t=>s.gen(function*(){let e=yield*ur.Service,r=yield*Bi.HttpClient,n=yield*vs.Service;yield*t.add("*","/*",a=>Xl(a,{fs:e,client:r,disableEmbeddedWebUi:n.disableEmbeddedWebUi}))})).pipe(P.provide(ph)),QD=zi.group([rm.node,ur.node,Fr.node,Gt.node,ia.node,At.node,um.node,mm.node,Zi.node,fm.node,ua.node,wo.node,na.node,Me.node,Xe.node,zt.node,So.node,gm.node,$t.node,Cn.node,hs.node,vo.node,X.node,Yu.node,Kr.node,pa.node,vs.node,Wt.node,ma.node,Am.node,fa.node,Ao.node,Eo.node,Vt.node,wm.node,la.node,Xr.node,qe.node,vm.node,Jr.node,Dm.node,ya.node,Io.node,it.node,at.node,fe.node,lr.node,Es.node,Pm.node,Sa.node,It.node,Lu,le.node,Fe.node,Pt.node,wt.node]);function dh(t){let e=im();return P.mergeAll(_D,BD,FD,GD,WD,VD,zD).pipe(P.provide([ah,ih,ch,LD(t),ha.build(Ot.node,[[Ge.node,e]]),$i.layerServices]),P.provide(P.succeed(Fn)(t)),P.provide(Gy),P.provide(jy),P.provide(nr.layer),P.provide(ha.build(Et.node,[[Ge.node,e],[lo.node,Vl]])),P.provide(e),P.provide(ha.build(QD)),P.provideMerge(tm))}i(dh,"createRoutes");var uh=dh(),YD=Js(()=>Ce.toWebHandler(uh,{disableLogger:!0,memoMap:em,middleware:Xa}));globalThis.AI_SDK_LOG_WARNINGS=!1;var li=class extends oe.Service()("@opencode/ListenerServer"){static{i(this,"ListenerServerService")}},XD=Js(()=>{let t=fn.webHandler().handler,e={fetch:i(r=>t(r,fn.context),"fetch"),request(r,n){return e.fetch(r instanceof Request?r:new Request(new URL(r,"http://localhost"),n))}};return{app:e}});async function JD(){return d.fromApi(Ya)}i(JD,"openapi");var rc;async function ZD(t){let e=await s.runPromise(eR(t));return{hostname:e.hostname,port:e.port,url:e.url,stop:i(r=>s.runPromiseExit(e.stop(r)).then(()=>{}),"stop")}}i(ZD,"listen");var eR=s.fn("Server.listen")(function*(t){let e=yield*rR(t),r=yield*nR(e),n=oR(t.hostname,r.port),a=yield*sR(t,r.port,e.scope);return rc=n,{hostname:t.hostname,port:r.port,url:n,stop:yield*iR(e,a,n)}});function tR(t,e){return Ce.serve(fn.createRoutes(t),{middleware:Xa,disableLogger:!0,disableListenLog:!0}).pipe(P.provideMerge(am.build($e.node)),P.provideMerge(cR({port:e,hostname:t.hostname})),P.provide(Hc.layer(Hc.fromEnv())))}i(tR,"listenerLayer");function rR(t){return t.port!==0?ud(t,t.port):ud(t,4096).pipe(s.catch(()=>ud(t,0)))}i(rR,"startWithPortFallback");function ud(t,e){let r=xt.makeUnsafe();return P.buildWithMemoMap(tR(t,e),P.makeMemoMapUnsafe(),r).pipe(s.provide(fn.context),s.onError(()=>xt.close(r,ro.void).pipe(s.ignore)),s.map(n=>({scope:r,server:oe.get(n,$i.HttpServer),http:oe.get(n,li),websockets:oe.get(n,$e.Service)})))}i(ud,"startListener");function nR(t){return s.gen(function*(){return t.server.address._tag==="TcpAddress"?t.server.address:(yield*xt.close(t.scope,ro.void).pipe(s.ignore),yield*s.die(new Error(`Unexpected HttpServer address tag: ${t.server.address._tag}`)))})}i(nR,"tcpAddress");function oR(t,e){let r=new URL("http://localhost");return r.hostname=t,r.port=String(e),r}i(oR,"makeURL");function sR(t,e,r){return s.gen(function*(){if(t.mdns&&e&&t.hostname!=="127.0.0.1"&&t.hostname!=="localhost"&&t.hostname!=="::1"){let a=yield*s.cached(s.sync(()=>ko.unpublish()));return yield*s.sync(()=>ko.publish(e,t.mdnsDomain)),yield*xt.addFinalizer(r,a),a}return t.mdns&&(yield*s.logWarning("mDNS enabled but hostname is loopback; skipping mDNS publish")),s.void})}i(sR,"setupMdns");function iR(t,e,r){return s.gen(function*(){let n=yield*s.cached(aR(t).pipe(s.ignore)),a=yield*s.cached(xt.close(t.scope,ro.void).pipe(s.ignore,s.ensuring(s.sync(()=>{rc===r&&(rc=void 0)}))));return c=>s.gen(function*(){yield*e,c&&(yield*n),yield*a})})}i(iR,"makeStop");function aR(t){return s.all([t.http.closeAll,t.websockets.closeAll],{concurrency:"unbounded",discard:!0})}i(aR,"forceClose");function cR(t){let e=KD(),r={closeStarted:!1,forceStop:!1},n=e.close.bind(e);return e.close=(a=>{r.closeStarted=!0;let c=n(a);return r.forceStop&&e.closeAllConnections(),c}),P.mergeAll(Au.layer(()=>e,{port:t.port,host:t.hostname,gracefulShutdownTimeout:"1 second"}),P.succeed(li)(li.of({closeAll:s.sync(()=>{r.forceStop=!0,r.closeStarted&&e.closeAllConnections()})})))}i(cR,"serverLayer");export{XD as Default,md as Server,ZD as listen,JD as openapi,rc as url};
|