@cortex-agent/server 2026.10.28 → 2026.11.17
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/LICENSE +255 -21
- package/README.md +36 -7
- package/THIRD_PARTY_NOTICES.txt +1109 -278
- package/defaults/hooks/cortex-hook-api.mjs +2 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
- package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
- package/dist/chunks/{anthropic-messages-M3SMXACA.js → anthropic-messages-M732OMEE.js} +1 -1
- package/dist/chunks/{azure-openai-responses-76YWXHSB.js → azure-openai-responses-RAKTV6JY.js} +1 -1
- package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +62 -0
- package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
- package/dist/chunks/child-runner-MO5RT6FH.js +4 -0
- package/dist/chunks/chunk-2ATTYCRJ.js +4 -0
- package/dist/chunks/{chunk-PXS5SHOV.js → chunk-2ROGTDM2.js} +1 -1
- package/dist/chunks/chunk-2VVRTJQN.js +4 -0
- package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
- package/dist/chunks/chunk-3CPIMAYX.js +30 -0
- package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-3CZPBLB3.js} +1 -1
- package/dist/chunks/chunk-3ORG56I5.js +8 -0
- package/dist/chunks/{chunk-LEUENXI2.js → chunk-4YLAGSDM.js} +1 -1
- package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-53TQNK7Z.js} +1 -1
- package/dist/chunks/{chunk-4U7XXM4W.js → chunk-5A6CA5TM.js} +1 -1
- package/dist/chunks/{chunk-PBJ5MPPX.js → chunk-5DF5WJNM.js} +1 -1
- package/dist/chunks/chunk-5PAW3DEU.js +50 -0
- package/dist/chunks/{chunk-DXBSQXJL.js → chunk-7GAYFN52.js} +1 -1
- package/dist/chunks/chunk-7GEBDPTT.js +4 -0
- package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-AFTBQRPN.js} +1 -1
- package/dist/chunks/chunk-AVXDF7AG.js +4 -0
- package/dist/chunks/chunk-BDLKI2NT.js +4 -0
- package/dist/chunks/{chunk-P52RMIYX.js → chunk-BJGYGEZO.js} +1 -1
- package/dist/chunks/chunk-BUZQBTV2.js +10 -0
- package/dist/chunks/chunk-BZDIAI5M.js +125 -0
- package/dist/chunks/{chunk-A34TDMIC.js → chunk-CEGSDGYQ.js} +1 -1
- package/dist/chunks/{chunk-Q7CE3UIE.js → chunk-CK3P345X.js} +69 -69
- package/dist/chunks/{chunk-YAEVYJAR.js → chunk-EE3WT25T.js} +1 -1
- package/dist/chunks/chunk-ETIBCA2S.js +4 -0
- package/dist/chunks/{chunk-REBNWCKI.js → chunk-FP7ML72L.js} +1 -1
- package/dist/chunks/{chunk-H2FP6DG4.js → chunk-H4QZ2P3Z.js} +1 -1
- package/dist/chunks/chunk-IA6IODY3.js +4 -0
- package/dist/chunks/{chunk-D3NXKK2L.js → chunk-IKLTEWA3.js} +1 -1
- package/dist/chunks/chunk-IYVZHGUQ.js +5 -0
- package/dist/chunks/chunk-JJDEQ6N2.js +4 -0
- package/dist/chunks/chunk-JKL3AK5D.js +106 -0
- package/dist/chunks/chunk-KDPY2YA3.js +129 -0
- package/dist/chunks/{chunk-SUFW24P4.js → chunk-KUDK7GPS.js} +1 -1
- package/dist/chunks/chunk-LAWOWPZX.js +363 -0
- package/dist/chunks/chunk-LEAV3FFG.js +4 -0
- package/dist/chunks/chunk-LP72AF56.js +45 -0
- package/dist/chunks/{chunk-KENCMLRE.js → chunk-LP7T32PW.js} +1 -1
- package/dist/chunks/chunk-LQTFDC67.js +4 -0
- package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-MGYYSX7Y.js} +1 -1
- package/dist/chunks/chunk-NNBSSISP.js +4 -0
- package/dist/chunks/chunk-NNTQUHLO.js +877 -0
- package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-NRD57ICT.js} +1 -1
- package/dist/chunks/{chunk-QWAQHHRS.js → chunk-NXZS5PEW.js} +1 -1
- package/dist/chunks/chunk-OFEPDNRB.js +4 -0
- package/dist/chunks/{chunk-6LZK4DDH.js → chunk-P7TVR4GY.js} +1 -1
- package/dist/chunks/chunk-QEL6CMLE.js +4 -0
- package/dist/chunks/chunk-QMSSIDRQ.js +70 -0
- package/dist/chunks/chunk-QUXPMNFQ.js +4 -0
- package/dist/chunks/chunk-R52AVUQB.js +5 -0
- package/dist/chunks/chunk-R6CGBSTC.js +22 -0
- package/dist/chunks/chunk-RA2BUYI3.js +6 -0
- package/dist/chunks/chunk-RDW6FRF5.js +4 -0
- package/dist/chunks/chunk-RF4JLYBX.js +6 -0
- package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-ROVKOIHF.js} +1 -1
- package/dist/chunks/chunk-RYLSRII6.js +7 -0
- package/dist/chunks/{chunk-XNSSUVT6.js → chunk-S3MR37DL.js} +1 -1
- package/dist/chunks/chunk-SAJD4EKE.js +10 -0
- package/dist/chunks/chunk-SFX7V5O2.js +10 -0
- package/dist/chunks/chunk-STCNHXPJ.js +6 -0
- package/dist/chunks/{chunk-FOJQXLL2.js → chunk-SY2HV3V5.js} +1 -1
- package/dist/chunks/chunk-T73GHMFB.js +4 -0
- package/dist/chunks/chunk-TKFFQNAP.js +19 -0
- package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
- package/dist/chunks/chunk-TX46YMGI.js +5 -0
- package/dist/chunks/chunk-U23S37TT.js +6 -0
- package/dist/chunks/chunk-UT6DGZDO.js +4 -0
- package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
- package/dist/chunks/chunk-V6X7Y62J.js +7 -0
- package/dist/chunks/chunk-V7K3KNDM.js +4 -0
- package/dist/chunks/{chunk-NAA7GF6Q.js → chunk-VBN2JSER.js} +1 -1
- package/dist/chunks/chunk-VIMHSW6J.js +4 -0
- package/dist/chunks/chunk-VK5J556O.js +4 -0
- package/dist/chunks/chunk-VPVSKJGX.js +6 -0
- package/dist/chunks/chunk-VTL3Z2OP.js +23 -0
- package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
- package/dist/chunks/chunk-W34AK4SK.js +65 -0
- package/dist/chunks/chunk-W6AKCEYF.js +8 -0
- package/dist/chunks/chunk-WBSE3EF3.js +27 -0
- package/dist/chunks/chunk-WZYS2HAK.js +4 -0
- package/dist/chunks/{chunk-UNVEZI57.js → chunk-XEBEWR6Y.js} +1 -1
- package/dist/chunks/chunk-XPPZ6Y3X.js +8 -0
- package/dist/chunks/chunk-XYSXL3KX.js +4 -0
- package/dist/chunks/chunk-YAAKL3QS.js +80 -0
- package/dist/chunks/chunk-YB5LUJHS.js +65 -0
- package/dist/chunks/chunk-Z24SBRJK.js +4 -0
- package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +1 -1
- package/dist/chunks/context-GQKWKFRM.js +4 -0
- package/dist/chunks/cost-OOO32GLC.js +5 -0
- package/dist/chunks/dist-V5FRMUFH.js +4 -0
- package/dist/chunks/easter-egg-3d-CZH7AYZ7.js +4 -0
- package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
- package/dist/chunks/execution-repo-XXL4FXC6.js +4 -0
- package/dist/chunks/{executions-6ARGR3IO.js → executions-BN6OLLVM.js} +1 -1
- package/dist/chunks/file-H572PL2Z.js +4 -0
- package/dist/chunks/google-generative-ai-2G4ITOZL.js +4 -0
- package/dist/chunks/google-vertex-PACHCMRZ.js +4 -0
- package/dist/chunks/init-75F4V7SK.js +4 -0
- package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-ABBD7DO5.js} +1 -1
- package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-EE2UPR3Q.js} +1 -1
- package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-C446T2GZ.js} +1 -1
- package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-IA2F2H7A.js} +1 -1
- package/dist/chunks/local-client-stop-5YOLXGYT.js +4 -0
- package/dist/chunks/memory-cli-5SSF6YJM.js +11 -0
- package/dist/chunks/{mistral-conversations-34F66L3O.js → mistral-conversations-VHP63CDS.js} +1 -1
- package/dist/chunks/{model-resolver-N3DTAQ2S.js → model-resolver-FVJNZ6NA.js} +1 -1
- package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
- package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
- package/dist/chunks/{openai-codex-responses-ZBVHREB3.js → openai-codex-responses-EHJ4AZBE.js} +1 -1
- package/dist/chunks/{openai-completions-VVIB26SH.js → openai-completions-CRAGQFCE.js} +1 -1
- package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-P5UX7BWY.js} +1 -1
- package/dist/chunks/{openai-responses-735XA2ZX.js → openai-responses-IZ22NVQ7.js} +1 -1
- package/dist/chunks/{openrouter-images-3IKETHAC.js → openrouter-images-W2JAMSRH.js} +1 -1
- package/dist/chunks/{pi-messages-I3E4ZFHA.js → pi-messages-MJEEQU2R.js} +1 -1
- package/dist/chunks/{radius-HXRZVBDB.js → radius-ZM7ZRMXF.js} +1 -1
- package/dist/chunks/{remote-ops-BALZYKH6.js → remote-ops-O5CR4RGA.js} +1 -1
- package/dist/chunks/runner-S6R3US24.js +4 -0
- package/dist/chunks/schedule-cli-4T4YC5V5.js +4 -0
- package/dist/chunks/slack-2CGM4SMY.js +4 -0
- package/dist/chunks/start-ui-http-3D7QNHGB.js +43 -0
- package/dist/chunks/subagent-OZGUOV3J.js +4 -0
- package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
- package/dist/chunks/tool-shims-IA2WELXJ.js +4 -0
- package/dist/chunks/typesafe-system-one-6ULACYD4.js +1 -1
- package/dist/chunks/ui-board-H4INJD6C.js +5 -0
- package/dist/chunks/ui-decision-6HHNROIT.js +4 -0
- package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-6PLXHSTB.js} +1 -1
- package/dist/chunks/ui-view-6MDU4GXY.js +4 -0
- package/dist/chunks/virtual-modules-OFI7QKYH.js +4 -0
- package/dist/chunks/waitpoint-W5M3BE55.js +5 -0
- package/dist/chunks/workers-GTFP75MS.js +4 -0
- package/dist/client-bundle/client.mjs +44 -31
- package/dist/client-bundle/manifest.json +2 -2
- package/dist/core/pi-sdk.js +1 -1
- package/dist/domain/auth/cc-auth-cli.js +1 -1
- package/dist/domain/mcp/bundled-server.js +1 -1
- package/dist/domain/mcp/feishu/client.js +4 -0
- package/dist/entry/app.js +201 -191
- package/dist/entry/browser-cli.js +10 -10
- package/dist/entry/cli.js +1 -1
- package/dist/entry/cortex-cli.js +1 -1
- package/dist/entry/daemon.js +4 -4
- package/dist/entry/hook-cli.js +2 -2
- package/dist/entry/production-app-bootstrap.js +1 -1
- package/dist/entry/production-evidence-export-cli.js +1 -1
- package/dist/entry/signal-cli.js +2 -2
- package/dist/tui/index.js +41 -41
- package/package.json +3 -3
- package/vendor/pi/dist/core/extensions/loader.js +1 -1
- package/vendor/pi/dist/extensions/codemode/execute.js +1 -1
- package/vendor/pi-ai/bedrock.js +1 -1
- package/vendor/pi-ai/oauth-load.js +1 -1
- package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-BgIyUG-C.js} +1 -1
- package/web/dist/assets/index-9lyu2S6W.css +1 -0
- package/web/dist/assets/index-C-hpzey7.js +532 -0
- package/web/dist/assets/{index-WCm6wwmM.js → index-C2eMpcuI.js} +1 -1
- package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
- package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
- package/web/dist/index.html +2 -2
- package/web/dist/theme.css +22 -0
- package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
- package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
- package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
- package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
- package/dist/chunks/chunk-3F6WW7HR.js +0 -13
- package/dist/chunks/chunk-3OKHUVEM.js +0 -7
- package/dist/chunks/chunk-3THJYAEF.js +0 -4
- package/dist/chunks/chunk-3YHOCPQU.js +0 -10
- package/dist/chunks/chunk-4LLH5OWM.js +0 -10
- package/dist/chunks/chunk-52T37Y47.js +0 -8
- package/dist/chunks/chunk-7MU2AKNM.js +0 -4
- package/dist/chunks/chunk-AAA3UBIS.js +0 -4
- package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
- package/dist/chunks/chunk-BGVHA2D4.js +0 -4
- package/dist/chunks/chunk-BKHDWCRT.js +0 -79
- package/dist/chunks/chunk-CQLH4UVX.js +0 -4
- package/dist/chunks/chunk-D6UA4BZC.js +0 -19
- package/dist/chunks/chunk-DGMNI4AO.js +0 -4
- package/dist/chunks/chunk-DHSA5ACV.js +0 -125
- package/dist/chunks/chunk-DPQPXBTP.js +0 -68
- package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
- package/dist/chunks/chunk-EQITBTJC.js +0 -10
- package/dist/chunks/chunk-EXJA5RIX.js +0 -357
- package/dist/chunks/chunk-FH74NME3.js +0 -115
- package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
- package/dist/chunks/chunk-J5DVLUKY.js +0 -6
- package/dist/chunks/chunk-JW2HFMTF.js +0 -4
- package/dist/chunks/chunk-KIGMAATV.js +0 -23
- package/dist/chunks/chunk-KIU5FAPY.js +0 -5
- package/dist/chunks/chunk-KIWMQPH7.js +0 -739
- package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
- package/dist/chunks/chunk-MEPASGPP.js +0 -6
- package/dist/chunks/chunk-MFAEUHMV.js +0 -28
- package/dist/chunks/chunk-NKDMKRSB.js +0 -68
- package/dist/chunks/chunk-NKXV32S6.js +0 -4
- package/dist/chunks/chunk-NVX5IPRN.js +0 -4
- package/dist/chunks/chunk-O3JW2F7D.js +0 -8
- package/dist/chunks/chunk-OISO5JXB.js +0 -4
- package/dist/chunks/chunk-OPYXNSMY.js +0 -4
- package/dist/chunks/chunk-PZMXHA6X.js +0 -9
- package/dist/chunks/chunk-QEOFEETJ.js +0 -4
- package/dist/chunks/chunk-REPYBMQS.js +0 -4
- package/dist/chunks/chunk-TAWLERZA.js +0 -4
- package/dist/chunks/chunk-TWAEABGG.js +0 -52
- package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
- package/dist/chunks/chunk-UD3NMUHR.js +0 -12
- package/dist/chunks/chunk-W25TB3PU.js +0 -4
- package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
- package/dist/chunks/chunk-XAJLZR7C.js +0 -28
- package/dist/chunks/chunk-XH6FMP3N.js +0 -71
- package/dist/chunks/chunk-XSRZHN63.js +0 -4
- package/dist/chunks/chunk-YG7OEPR2.js +0 -6
- package/dist/chunks/chunk-YHIWOGVL.js +0 -4
- package/dist/chunks/chunk-YZSHTWNM.js +0 -92
- package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
- package/dist/chunks/client-XOGYH5UR.js +0 -4
- package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
- package/dist/chunks/context-VCQH5OB6.js +0 -4
- package/dist/chunks/cost-PGGFI7QJ.js +0 -5
- package/dist/chunks/dist-PUKMZ7GW.js +0 -4
- package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
- package/dist/chunks/es5-VNTQPCKX.js +0 -4
- package/dist/chunks/execution-repo-ZLJTBWFC.js +0 -4
- package/dist/chunks/file-7BN7RCAY.js +0 -4
- package/dist/chunks/gateway-UCRPMR75.js +0 -36
- package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
- package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
- package/dist/chunks/init-HA7FAQ73.js +0 -4
- package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
- package/dist/chunks/memory-cli-PYOILNN5.js +0 -11
- package/dist/chunks/models-L5VF4I5O-XXNJYQMQ.js +0 -4
- package/dist/chunks/runner-PLVZDGHB.js +0 -4
- package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
- package/dist/chunks/slack-WAGSPZUX.js +0 -4
- package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
- package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
- package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
- package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
- package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
- package/dist/chunks/ui-view-O7PLANT7.js +0 -4
- package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
- package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
- package/dist/chunks/workers-XN4PSTH6.js +0 -4
- package/vendor/aistatus/gateway-cli.js +0 -21
- package/web/dist/assets/index-BHZpFXhc.js +0 -525
- package/web/dist/assets/index-DqWMdMkh.css +0 -1
- package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
- package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{$ as Pn,$a as Ao,A as tn,Aa as to,Ab as qo,Ac as ps,B as rn,Ba as ro,Bc as ms,C as nn,Ca as no,Cc as ys,D as on,Da as oo,Dc as hs,E as sn,Ea as tt,Ec as gs,F as an,Fa as so,G as cn,Ga as io,H as un,Ha as ao,I as ln,Ia as co,Ic as Es,J as dn,Ja as uo,K as fn,Ka as lo,Kc as Ss,L as pn,La as fo,M as mn,Ma as po,N as yn,Na as mo,Nb as os,O as hn,Oa as yo,P as gn,Q as wn,Qa as Et,R as En,Ra as ho,S as Sn,Sa as go,T as vn,Ta as wo,U as bn,Ua as Eo,V as _n,Va as So,W as Tn,Wa as vo,X as Rn,Xa as bo,Y as An,Ya as _o,Z as On,Za as To,_ as In,_a as Ro,aa as Cn,ab as Oo,ba as xn,bb as Io,ca as Nn,cb as Po,d as Ur,da as Dn,db as Co,ea as Un,eb as xo,fa as kn,fb as No,g as kr,ga as Ln,gb as Do,h as Lr,ha as Mn,hb as Uo,i as Mr,ia as jn,ib as ko,j as jr,ja as Hn,jb as Lo,k as Hr,ka as Fn,kb as St,l as Fr,la as Jn,lb as Mo,m as Jr,ma as Wn,mb as jo,n as Wr,na as Bn,nb as Ho,o as Br,oa as $n,ob as Fo,oc as cs,p as $r,pa as Kn,pb as Jo,q as Kr,qa as zn,qb as Wo,r as zr,ra as Vn,rb as Bo,s as Vr,sa as Gn,sb as $o,sc as us,t as Gr,tb as Ko,tc as ls,u as Yr,ua as Yn,ub as zo,uc as ds,v as Qr,va as Qn,vb as Vo,vc as fs,w as Xr,wa as Xn,wb as Go,x as qr,xa as qn,xb as Yo,y as Zr,ya as Zn,yb as Qo,z as en,za as eo,zb as Xo}from"./chunk-QMSSIDRQ.js";import"./chunk-5A6CA5TM.js";import{a as vt}from"./chunk-TCAEECDI.js";import{e as qe,f as Ze}from"./chunk-LMDWRRX4.js";import{a as ss,b as is,c as as}from"./chunk-Y6ZEVVL5.js";import{a as ne,b as et}from"./chunk-2YTYYG4K.js";import"./chunk-SAJD4EKE.js";import"./chunk-ZFPMIQA3.js";import"./chunk-EE3WT25T.js";import"./chunk-IKLTEWA3.js";import{a as es,c as ts,d as rs}from"./chunk-FP7ML72L.js";import"./chunk-LEAV3FFG.js";import{b as vs}from"./chunk-2ATTYCRJ.js";import"./chunk-7GEBDPTT.js";import{a as ke,d as Z,e as Zo}from"./chunk-KUDK7GPS.js";import"./chunk-RA2BUYI3.js";import"./chunk-T73GHMFB.js";import"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-VK5J556O.js";import"./chunk-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import{b as ws}from"./chunk-QUXPMNFQ.js";import"./chunk-XPPZ6Y3X.js";import{f as Nr,l as Dr}from"./chunk-BUZQBTV2.js";import{e as Cr}from"./chunk-STCNHXPJ.js";import"./chunk-STUHNKQS.js";import{a as ns}from"./chunk-NRD57ICT.js";import"./chunk-KRXTI4JO.js";import{K as _e}from"./chunk-W34AK4SK.js";import"./chunk-TX46YMGI.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import{e as xr}from"./chunk-3CPIMAYX.js";import{e as N}from"./chunk-VBN2JSER.js";import"./chunk-NXZS5PEW.js";import{j as Xe,t as Ir,v as Pr}from"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";import*as te from"node:path";import*as xa from"node:fs";import{fileURLToPath as yf}from"node:url";function bs(e){let r=(Array.isArray(e)?e[0]:e)?.trim().toLowerCase();return Nr.includes(r??"")?r:null}function rt(e,...t){let r=Object.assign(Y(),e);for(let n of t)for(let o in n){if(o in r&&r[o]!==n[o])throw new Error(`Duplicate key ${o}`);r[o]=n[o]}return r}function F(e){return!!e&&!Array.isArray(e)&&typeof e=="object"}function nt(e){return typeof e=="function"}function Y(){return Object.create(null)}var Da=typeof Symbol=="function"&&!!Symbol.asyncIterator;function Le(e){return Da&&F(e)&&Symbol.asyncIterator in e}var oe=e=>e();function _s(e){return e}function Ts(e){if(typeof AbortSignal.any=="function")return AbortSignal.any(e);let t=new AbortController;for(let n of e){if(n.aborted){r();break}n.addEventListener("abort",r,{once:!0})}return t.signal;function r(){t.abort();for(let n of e)n.removeEventListener("abort",r)}}var Te={PARSE_ERROR:-32700,BAD_REQUEST:-32600,INTERNAL_SERVER_ERROR:-32603,NOT_IMPLEMENTED:-32603,BAD_GATEWAY:-32603,SERVICE_UNAVAILABLE:-32603,GATEWAY_TIMEOUT:-32603,UNAUTHORIZED:-32001,PAYMENT_REQUIRED:-32002,FORBIDDEN:-32003,NOT_FOUND:-32004,METHOD_NOT_SUPPORTED:-32005,TIMEOUT:-32008,CONFLICT:-32009,PRECONDITION_FAILED:-32012,PAYLOAD_TOO_LARGE:-32013,UNSUPPORTED_MEDIA_TYPE:-32015,UNPROCESSABLE_CONTENT:-32022,PRECONDITION_REQUIRED:-32028,TOO_MANY_REQUESTS:-32029,CLIENT_CLOSED_REQUEST:-32099},Rs={[-32700]:"PARSE_ERROR",[-32600]:"BAD_REQUEST",[-32603]:"INTERNAL_SERVER_ERROR",[-32001]:"UNAUTHORIZED",[-32002]:"PAYMENT_REQUIRED",[-32003]:"FORBIDDEN",[-32004]:"NOT_FOUND",[-32005]:"METHOD_NOT_SUPPORTED",[-32008]:"TIMEOUT",[-32009]:"CONFLICT",[-32012]:"PRECONDITION_FAILED",[-32013]:"PAYLOAD_TOO_LARGE",[-32015]:"UNSUPPORTED_MEDIA_TYPE",[-32022]:"UNPROCESSABLE_CONTENT",[-32028]:"PRECONDITION_REQUIRED",[-32029]:"TOO_MANY_REQUESTS",[-32099]:"CLIENT_CLOSED_REQUEST"},Af=[Te.BAD_GATEWAY,Te.SERVICE_UNAVAILABLE,Te.GATEWAY_TIMEOUT,Te.INTERNAL_SERVER_ERROR];var Ua=()=>{},As=e=>{Object.freeze&&Object.freeze(e)};function Is(e,t,r){var n;let o=t.join(".");return(n=r[o])!==null&&n!==void 0||(r[o]=new Proxy(Ua,{get(i,s){if(!(typeof s!="string"||s==="then"))return Is(e,[...t,s],r)},apply(i,s,a){let c=t[t.length-1];if(c==="valueOf"||c==="toString"||c==="toJSON")return`tRPC.proxy(${t.slice(0,-1).join(".")})`;let u={args:a,path:t};return c==="call"?u={args:a.length>=2?[a[1]]:[],path:t.slice(0,-1)}:c==="apply"&&(u={args:a.length>=2?a[1]:[],path:t.slice(0,-1)}),As(u.args),As(u.path),e(u)}})),r[o]}var Ps=e=>Is(e,[],Y());var ka={PARSE_ERROR:400,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_SUPPORTED:405,TIMEOUT:408,CONFLICT:409,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,UNSUPPORTED_MEDIA_TYPE:415,UNPROCESSABLE_CONTENT:422,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,CLIENT_CLOSED_REQUEST:499,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504};function Cs(e){var t;return(t=ka[e])!==null&&t!==void 0?t:500}function xs(e){let t=new Set((Array.isArray(e)?e:[e]).map(r=>{if("error"in r&&F(r.error.data)){var n;if(typeof((n=r.error.data)===null||n===void 0?void 0:n.httpStatus)=="number")return r.error.data.httpStatus;let o=Rs[r.error.code];return Cs(o)}return 200}));return t.size!==1?207:t.values().next().value}function La(e){return Cs(e.code)}function Me(e){"@babel/helpers - typeof";return Me=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Me(e)}function Ma(e,t){if(Me(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Me(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ja(e){var t=Ma(e,"string");return Me(t)=="symbol"?t:t+""}function X(e,t,r){return(t=ja(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Os(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),r.push.apply(r,n)}return r}function S(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Os(Object(r),!0).forEach(function(n){X(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Os(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function se(e){let{path:t,error:r,config:n}=e,{code:o}=e.error,i={message:r.message,code:Te[o],data:{code:o,httpStatus:La(r)}};return n.isDev&&typeof e.error.stack=="string"&&(i.data.stack=e.error.stack),typeof t=="string"&&(i.data.path=t),n.errorFormatter(S(S({},e),{},{shape:i}))}var Re=({shape:e})=>e,Ha=class extends Error{constructor(e){super(Fa(e)),Object.assign(this,e)}};function Fa(e){if("message"in e)return String(e.message)}function Ja(e){if(e instanceof Error)return e;let t=typeof e;if(!(t==="undefined"||t==="function"||e===null)){if(t!=="object")return new Error(String(e));if(F(e))return new Ha(e)}}function B(e){if(e instanceof O||e instanceof Error&&e.name==="TRPCError")return e;let t=new O({code:"INTERNAL_SERVER_ERROR",cause:e});return e instanceof Error&&e.stack&&(t.stack=e.stack),t}var O=class extends Error{constructor(e){var t,r,n;let o=Ja(e.cause),i=(t=(r=e.message)!==null&&r!==void 0?r:o?.message)!==null&&t!==void 0?t:e.code;super(i,{cause:o}),X(this,"cause",void 0),X(this,"code",void 0),this.code=e.code,this.name="TRPCError",(n=this.cause)!==null&&n!==void 0||(this.cause=o)}};function Ds(e){return"input"in e?e:{input:e,output:e}}var Ae={input:{serialize:e=>e,deserialize:e=>e},output:{serialize:e=>e,deserialize:e=>e}};function Ns(e,t){return"error"in t?S(S({},t),{},{error:e.transformer.output.serialize(t.error)}):"data"in t.result?S(S({},t),{},{result:S(S({},t.result),{},{data:e.transformer.output.serialize(t.result.data)})}):t}function me(e,t){return Array.isArray(t)?t.map(r=>Ns(e,r)):Ns(e,t)}var Wa="lazyMarker";function Ba(e){let t=Symbol(),r=t;return()=>(r===t&&(r=e()),r)}function $a(e){return typeof e=="function"&&Wa in e}function Ka(e){return F(e)&&F(e._def)&&"router"in e._def}var za={_ctx:null,_errorShape:null,_meta:null,queries:{},mutations:{},subscriptions:{},errorFormatter:Re,transformer:Ae},Va=["then","call","apply"];function bt(e){function t(r){let n=new Set(Object.keys(r).filter(l=>Va.includes(l)));if(n.size>0)throw new Error("Reserved words used in `router({})` call: "+Array.from(n).join(", "));let o=Y(),i=Y();function s(l){return{ref:l.ref,load:Ba(async()=>{let p=await l.ref(),m=[...l.path,l.key],y=m.join(".");l.aggregate[l.key]=a(p._def.record,m),delete i[y];for(let[d,f]of Object.entries(p._def.lazy)){let w=[...m,d].join(".");i[w]=s({ref:f.ref,path:m,key:d,aggregate:l.aggregate[l.key]})}})}}function a(l,p=[]){let m=Y();for(let[y,d]of Object.entries(l??{})){if($a(d)){i[[...p,y].join(".")]=s({path:p,ref:d,key:y,aggregate:m});continue}if(Ka(d)){m[y]=a(d._def.record,[...p,y]);continue}if(!Ga(d)){m[y]=a(d,[...p,y]);continue}let f=[...p,y].join(".");if(o[f])throw new Error(`Duplicate key: ${f}`);o[f]=d,m[y]=d}return m}let c=a(r),u=S(S({_config:e,router:!0,procedures:o,lazy:i},za),{},{record:c});return S(S({},c),{},{_def:u,createCaller:_t()({_def:u})})}return t}function Ga(e){return typeof e=="function"}async function je(e,t){let{_def:r}=e,n=r.procedures[t];for(;!n;){let o=Object.keys(r.lazy).find(i=>t===i||t.startsWith(i+"."));if(!o)return null;await r.lazy[o].load(),n=r.procedures[t]}return n}function _t(){return function(t){let{_def:r}=t;return function(o,i){return Ps(async s=>{let{path:a,args:c}=s,u=a.join(".");if(a.length===1&&a[0]==="_def")return r;let l=await je(t,u),p;try{if(!l)throw new O({code:"NOT_FOUND",message:`No procedure found on path "${a}"`});return p=nt(o)?await Promise.resolve(o()):o,await l({path:u,getRawInput:async()=>c[0],ctx:p,type:l._def.type,signal:i?.signal,batchIndex:0})}catch(d){var m,y;throw i==null||(m=i.onError)===null||m===void 0||m.call(i,{ctx:p,error:B(d),input:c[0],path:u,type:(y=l?._def.type)!==null&&y!==void 0?y:"unknown"}),d}})}}}function Us(...e){var t,r;let n=rt({},...e.map(o=>o._def.record));return bt({errorFormatter:e.reduce((o,i)=>{if(i._def._config.errorFormatter&&i._def._config.errorFormatter!==Re){if(o!==Re&&o!==i._def._config.errorFormatter)throw new Error("You seem to have several error formatters");return i._def._config.errorFormatter}return o},Re),transformer:e.reduce((o,i)=>{if(i._def._config.transformer&&i._def._config.transformer!==Ae){if(o!==Ae&&o!==i._def._config.transformer)throw new Error("You seem to have several transformers");return i._def._config.transformer}return o},Ae),isDev:e.every(o=>o._def._config.isDev),allowOutsideOfServer:e.every(o=>o._def._config.allowOutsideOfServer),isServer:e.every(o=>o._def._config.isServer),$types:(t=e[0])===null||t===void 0?void 0:t._def._config.$types,sse:(r=e[0])===null||r===void 0?void 0:r._def._config.sse})(n)}var Ya=Symbol();function Tt(e){return Array.isArray(e)&&e[2]===Ya}var Ms="middlewareMarker";function Qa(){function e(r){return{_middlewares:r,unstable_pipe(n){let o="_middlewares"in n?n._middlewares:[n];return e([...r,...o])}}}function t(r){return e([r])}return t}function Xa(e){let t=async function(n){let o,i=await n.getRawInput();try{o=await e(i)}catch(a){throw new O({code:"BAD_REQUEST",cause:a})}let s=F(n.input)&&F(o)?S(S({},n.input),o):o;return n.next({input:s})};return t._type="input",t}function qa(e){let t=async function({next:n}){let o=await n();if(!o.ok)return o;try{let i=await e(o.data);return S(S({},o),{},{data:i})}catch(i){throw new O({message:"Output validation failed",code:"INTERNAL_SERVER_ERROR",cause:i})}};return t._type="output",t}var js=class extends Error{constructor(e){var t;super((t=e[0])===null||t===void 0?void 0:t.message),X(this,"issues",void 0),this.name="SchemaError",this.issues=e}};function ks(e){let t=e,r="~standard"in t;if(typeof t=="function"&&typeof t.assert=="function")return t.assert.bind(t);if(typeof t=="function"&&!r)return t;if(typeof t.parseAsync=="function")return t.parseAsync.bind(t);if(typeof t.parse=="function")return t.parse.bind(t);if(typeof t.validateSync=="function")return t.validateSync.bind(t);if(typeof t.create=="function")return t.create.bind(t);if(typeof t.assert=="function")return n=>(t.assert(n),n);if(r)return async n=>{let o=await t["~standard"].validate(n);if(o.issues)throw new js(o.issues);return o.value};throw new Error("Could not find a validator fn")}function Za(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.includes(n))continue;r[n]=e[n]}return r}function ec(e,t){if(e==null)return{};var r,n,o=Za(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.includes(r)||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}var tc=["middlewares","inputs","meta"];function de(e,t){let{middlewares:r=[],inputs:n,meta:o}=t,i=ec(t,tc);return Hs(S(S({},rt(e,i)),{},{inputs:[...e.inputs,...n??[]],middlewares:[...e.middlewares,...r],meta:e.meta&&o?S(S({},e.meta),o):o??e.meta}))}function Hs(e={}){let t=S({procedure:!0,inputs:[],middlewares:[]},e);return{_def:t,input(r){let n=ks(r);return de(t,{inputs:[r],middlewares:[Xa(n)]})},output(r){let n=ks(r);return de(t,{output:r,middlewares:[qa(n)]})},meta(r){return de(t,{meta:r})},use(r){let n="_middlewares"in r?r._middlewares:[r];return de(t,{middlewares:n})},unstable_concat(r){return de(t,r._def)},concat(r){return de(t,r._def)},query(r){return Rt(S(S({},t),{},{type:"query"}),r)},mutation(r){return Rt(S(S({},t),{},{type:"mutation"}),r)},subscription(r){return Rt(S(S({},t),{},{type:"subscription"}),r)},experimental_caller(r){return de(t,{caller:r})}}}function Rt(e,t){let r=de(e,{resolver:t,middlewares:[async function(c){let u=await t(c);return{marker:Ms,ok:!0,data:u,ctx:c.ctx}}]}),n=S(S({},r._def),{},{type:e.type,experimental_caller:!!r._def.caller,meta:r._def.meta,$types:null}),o=nc(r._def),i=r._def.caller;if(!i)return o;let s=async(...a)=>await i({args:a,invoke:o,_def:n});return s._def=n,s}var rc=`
|
|
5
|
+
This is a client-only function.
|
|
6
|
+
If you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls
|
|
7
|
+
`.trim();async function Fs(e,t,r){try{let n=t.middlewares[e];return await n(S(S({},r),{},{meta:t.meta,input:r.input,next(o){var i;let s=o;return Fs(e+1,t,S(S({},r),{},{ctx:s?.ctx?S(S({},r.ctx),s.ctx):r.ctx,input:s&&"input"in s?s.input:r.input,getRawInput:(i=s?.getRawInput)!==null&&i!==void 0?i:r.getRawInput}))}}))}catch(n){return{ok:!1,error:B(n),marker:Ms}}}function nc(e){async function t(r){if(!r||!("getRawInput"in r))throw new Error(rc);let n=await Fs(0,e,r);if(!n)throw new O({code:"INTERNAL_SERVER_ERROR",message:"No result from middlewares - did you forget to `return next()`?"});if(!n.ok)throw n.error;return n.data}return t._def=e,t.procedure=!0,t.meta=e.meta,t}var Oe,Ie,Pe,Ls=typeof window>"u"||"Deno"in window||((Oe=globalThis.process)===null||Oe===void 0||(Oe=Oe.env)===null||Oe===void 0?void 0:Oe.NODE_ENV)==="test"||!!(!((Ie=globalThis.process)===null||Ie===void 0||(Ie=Ie.env)===null||Ie===void 0)&&Ie.JEST_WORKER_ID)||!!(!((Pe=globalThis.process)===null||Pe===void 0||(Pe=Pe.env)===null||Pe===void 0)&&Pe.VITEST_WORKER_ID),Ot=new class At{context(){return new At}meta(){return new At}create(t){var r,n,o,i,s,a;let c=S(S({},t),{},{transformer:Ds((r=t?.transformer)!==null&&r!==void 0?r:Ae),isDev:(n=t?.isDev)!==null&&n!==void 0?n:((o=globalThis.process)===null||o===void 0?void 0:o.env.NODE_ENV)!=="production",allowOutsideOfServer:(i=t?.allowOutsideOfServer)!==null&&i!==void 0?i:!1,errorFormatter:(s=t?.errorFormatter)!==null&&s!==void 0?s:Re,isServer:(a=t?.isServer)!==null&&a!==void 0?a:Ls,$types:null});var u;if(!((u=t?.isServer)!==null&&u!==void 0?u:Ls)&&t?.allowOutsideOfServer!==!0)throw new Error("You're trying to use @trpc/server in a non-server environment. This is not supported by default.");return{_config:c,procedure:Hs({meta:t?.defaultMeta}),middleware:Qa(),router:bt(c),mergeRouters:Us,createCallerFactory:_t()}}};var oc={ping:{enabled:!0,intervalMs:15e3},client:{reconnectAfterInactivityMs:45e3}},It=Ot.context().create({sse:oc,errorFormatter({shape:e,path:t}){return t!=="config.setPlatform"?e:{...e,message:xr("ui.platform.requestFailed"),data:{...e.data,stack:void 0}}}}),C=It.router,ot=It.procedure,Qf=It.createCallerFactory;var sc=_e.object({events:_e.array(_e.string()),projectId:_e.string().nullish(),sessionId:_e.string().nullish()}),ic={"not-found":"NOT_FOUND","invalid-args":"BAD_REQUEST","invalid-name":"BAD_REQUEST","invalid-notes-file":"BAD_REQUEST","already-terminal":"CONFLICT","already-exists":"CONFLICT",conflict:"CONFLICT","backend-locked":"CONFLICT","session-running":"CONFLICT","not-available":"BAD_REQUEST",not_manageable:"BAD_REQUEST",runtime_unavailable:"BAD_REQUEST",logout_failed:"INTERNAL_SERVER_ERROR",internal:"INTERNAL_SERVER_ERROR"};function ac(e){return new O({code:ic[e.code]??"INTERNAL_SERVER_ERROR",message:e.message,cause:e})}function Js(e){if(e.ok)return e.data;throw ac(e)}function _(e,t,r){return ot.input(r).query(async({input:n})=>Js(await e.query(t,n)))}function h(e,t,r){return ot.input(r).mutation(async({input:n,ctx:o})=>Js(await e.mutate(t,n,{client:o.client??null})))}function cc(e){return C({list:_(e,"projects.list",tn),create:h(e,"projects.create",jn),delete:h(e,"projects.delete",Hn)})}function uc(e){return C({list:_(e,"sessions.list",Mr),transcript:_(e,"sessions.transcript",jr),subagentTranscript:_(e,"sessions.subagentTranscript",Hr),debugDetails:_(e,"sessions.debugDetails",Fr),pendingInteraction:_(e,"sessions.pendingInteraction",Jr),create:h(e,"sessions.create",Jn),delete:h(e,"sessions.delete",Fn),send:h(e,"sessions.send",Wn),cancel:h(e,"sessions.cancel",Bn),resolveUnsent:h(e,"sessions.resolveUnsent",$n),compact:h(e,"sessions.compact",Kn),setAgent:h(e,"sessions.setAgent",Gn),setSelection:h(e,"sessions.setSelection",Yn),createAndSend:h(e,"sessions.createAndSend",ro),setStarred:h(e,"sessions.setStarred",kr),rename:h(e,"sessions.rename",Lr),markRead:h(e,"sessions.markRead",zn),markManyRead:h(e,"sessions.markManyRead",Vn),answerQuestion:h(e,"sessions.answerQuestion",Qn),respondPlan:h(e,"sessions.respondPlan",Xn),respondDecision:h(e,"sessions.respondDecision",qn),cancelResume:h(e,"sessions.cancelResume",eo),rewind:h(e,"sessions.rewind",to),resolveMedia:h(e,"sessions.resolveMedia",Zn)})}function lc(e){return C({list:_(e,"schedules.list",Wr),pause:h(e,"schedules.pause",tt),resume:h(e,"schedules.resume",tt),remove:h(e,"schedules.remove",tt),add:h(e,"schedules.add",so),update:h(e,"schedules.update",io)})}function dc(e){return C({list:_(e,"boards.list",Br),get:_(e,"boards.get",$r),decisions:_(e,"boards.decisions",Kr),style:_(e,"boards.style",zr)})}function fc(e){return C({list:_(e,"waitpoints.list",Vr),cancel:h(e,"waitpoints.cancel",no)})}function pc(e){return C({list:_(e,"executions.list",Gr),get:_(e,"executions.get",Yr),cancel:h(e,"executions.cancel",oo)})}function mc(e){return C({tree:_(e,"memory.tree",Qr),file:_(e,"memory.file",Xr)})}function yc(e){return C({list:_(e,"approvals.list",qr),approve:h(e,"approvals.approve",Lo),reject:h(e,"approvals.reject",Wo),request:h(e,"approvals.request",qo)})}function hc(e){return C({list:_(e,"issues.list",Zr),handle:h(e,"issues.handle",St),delete:h(e,"issues.delete",St)})}function gc(e){return C({list:_(e,"notes.list",en),add:h(e,"notes.add",Mo),update:h(e,"notes.update",jo),setCompleted:h(e,"notes.setCompleted",Ho),delete:h(e,"notes.delete",Fo),clearCompleted:h(e,"notes.clearCompleted",Jo)})}function wc(e){return C({list:_(e,"hooks.list",uo),create:h(e,"hooks.create",lo),update:h(e,"hooks.update",fo),setEnabled:h(e,"hooks.setEnabled",po),remove:h(e,"hooks.remove",mo),test:h(e,"hooks.test",yo)})}function Ec(e){return C({catalog:_(e,"models.catalog",mn),favorites:C({add:h(e,"models.favorites.add",Et),remove:h(e,"models.favorites.remove",Et)}),setDefault:h(e,"models.setDefault",go),setThinking:h(e,"models.setThinking",ho),setDelegation:h(e,"models.setDelegation",wo)})}function Sc(e){return C({status:_(e,"auth.status",cn),flowState:_(e,"auth.flowState",un),startLogin:h(e,"auth.startLogin",In),respondPrompt:h(e,"auth.respondPrompt",xn),cancelFlow:h(e,"auth.cancelFlow",Nn),logout:h(e,"auth.logout",Un),syncModels:h(e,"auth.syncModels",Dn),addAccount:h(e,"auth.addAccount",Pn),removeAccount:h(e,"auth.removeAccount",Cn)})}function vc(e){return C({list:_(e,"connections.list",kn),upsert:h(e,"connections.upsert",Ln),remove:h(e,"connections.remove",Mn)})}function bc(e){return C({get:_(e,"usageSharing.get",ln),set:h(e,"usageSharing.set",dn)})}function _c(e){return C({info:_(e,"telemetry.info",fn),report:h(e,"telemetry.report",pn)})}function Tc(e){return C({daemonStatus:_(e,"system.daemonStatus",vn),rateLimitStatus:_(e,"system.rateLimitStatus",bn),usageStatus:_(e,"system.usageStatus",_n),notices:_(e,"system.notices",Tn),restart:h(e,"system.restart",Bo),clearRateLimit:h(e,"system.clearRateLimit",$o),refreshUsage:h(e,"system.refreshUsage",Ko),redeemUsageReset:h(e,"system.redeemUsageReset",zo),updateStatus:_(e,"system.updateStatus",Rn),checkUpdate:h(e,"system.checkUpdate",Vo),applyUpdate:h(e,"system.applyUpdate",Go),skipUpdate:h(e,"system.skipUpdate",Yo),version:_(e,"system.version",An),claudeCode:_(e,"system.claudeCode",On),checkClaudeCode:h(e,"system.checkClaudeCode",Qo),updateClaudeCode:h(e,"system.updateClaudeCode",Xo)})}function Rc(e){return C({summary:_(e,"cost.summary",rn)})}function Ac(e){return C({usage:_(e,"stats.usage",nn),tools:_(e,"stats.tools",on),quotaWindows:_(e,"stats.quotaWindows",sn)})}function Oc(e){return C({get:_(e,"config.get",an),set:h(e,"config.set",ao),setPlatform:h(e,"config.setPlatform",Ur),setProviderRateLimitPolicy:h(e,"config.setProviderRateLimitPolicy",co)})}function Ic(e){return C({list:_(e,"machines.list",yn),detail:_(e,"machines.detail",hn)})}function Pc(e){return C({list:_(e,"skills.list",gn),session:_(e,"skills.session",wn)})}function Cc(e){return C({list:_(e,"plugins.list",En),assign:h(e,"plugins.assign",Eo),skillFile:_(e,"plugins.skillFile",So),skillWrite:h(e,"plugins.skillWrite",vo),skillCreate:h(e,"plugins.skillCreate",bo),skillMove:h(e,"plugins.skillMove",_o),skillRemove:h(e,"plugins.skillRemove",To),skillRevert:h(e,"plugins.skillRevert",Ro),create:h(e,"plugins.create",Ao),remove:h(e,"plugins.remove",Oo),convertToPortable:h(e,"plugins.convertToPortable",Io),mcpRead:_(e,"plugins.mcpRead",Po),mcpWrite:h(e,"plugins.mcpWrite",Co)})}function xc(e){return C({list:_(e,"environments.list",Sn),get:_(e,"environments.get",xo),validate:h(e,"environments.validate",No),save:h(e,"environments.save",Do),delete:h(e,"environments.delete",Uo),savePrompt:h(e,"environments.savePrompt",ko)})}function Nc(e){return ot.input(sc).subscription(async function*({input:t,signal:r}){let n=e.subscribe(t);r?.addEventListener("abort",()=>n.close());try{for await(let o of n)yield o}finally{n.close()}})}function Ws(e){return C({projects:cc(e),sessions:uc(e),schedules:lc(e),boards:dc(e),executions:pc(e),waitpoints:fc(e),memory:mc(e),approvals:yc(e),issues:hc(e),notes:gc(e),cost:Rc(e),stats:Ac(e),config:Oc(e),models:Ec(e),auth:Sc(e),connections:vc(e),usageSharing:bc(e),telemetry:_c(e),hooks:wc(e),machines:Ic(e),skills:Pc(e),plugins:Cc(e),environments:xc(e),system:Tc(e),subscribe:Nc(e)})}import*as _i from"http";import*as fe from"fs";import*as ge from"path";function st(e){return typeof e=="object"&&e!==null&&"subscribe"in e}function Dc(e,t){let r=null,n=()=>{r?.unsubscribe(),r=null,t.removeEventListener("abort",n)};return new ReadableStream({start(o){r=e.subscribe({next(i){o.enqueue({ok:!0,value:i})},error(i){o.enqueue({ok:!1,error:i}),o.close()},complete(){o.close()}}),t.aborted?n():t.addEventListener("abort",n,{once:!0})},cancel(){n()}})}function Pt(e,t){let r=Dc(e,t).getReader(),n={async next(){let o=await r.read();if(o.done)return{value:void 0,done:!0};let{value:i}=o;if(!i.ok)throw i.error;return{value:i.value,done:!1}},async return(){return await r.cancel(),{value:void 0,done:!0}}};return{[Symbol.asyncIterator](){return n}}}function Uc(e){try{if(e===null)return null;if(!F(e))throw new Error("Expected object");let t=Object.entries(e).filter(([r,n])=>typeof n!="string");if(t.length>0)throw new Error(`Expected connectionParams to be string values. Got ${t.map(([r,n])=>`${r}: ${typeof n}`).join(", ")}`);return e}catch(t){throw new O({code:"PARSE_ERROR",message:"Invalid connection params shape",cause:t})}}function kc(e){let t;try{t=JSON.parse(e)}catch(r){throw new O({code:"PARSE_ERROR",message:"Not JSON-parsable query params",cause:r})}return Uc(t)}function Qs(e){var t,r;return(t=e.get("trpc-accept"))!==null&&t!==void 0?t:!((r=e.get("accept"))===null||r===void 0)&&r.split(",").some(n=>n.trim()==="application/jsonl")?"application/jsonl":null}function Nt(e){let t=null,r=Symbol.for("@trpc/server/http/memo"),n=r;return{read:async()=>{var o;return n!==r||((o=t)!==null&&o!==void 0||(t=e().catch(i=>{throw i instanceof O?i:new O({code:"BAD_REQUEST",message:i instanceof Error?i.message:"Invalid input",cause:i})})),n=await t,t=null),n},result:()=>n!==r?n:void 0}}var Xs={isMatch(e){var t;return!!(!((t=e.headers.get("content-type"))===null||t===void 0)&&t.startsWith("application/json"))},async parse(e){var t;let{req:r}=e,n=e.searchParams.get("batch")==="1",o=e.maxBatchSize,i=n?e.path.split(","):[e.path];if(n&&typeof o=="number"&&i.length>o)throw new O({code:"BAD_REQUEST",message:"Batch call exceeds maximum size"});let s=Nt(async()=>{let p;if(r.method==="GET"){let y=e.searchParams.get("input");y&&(p=JSON.parse(y))}else p=await r.json();if(p===void 0)return Y();if(!n){let y=Y();return y[0]=e.router._def._config.transformer.input.deserialize(p),y}if(!F(p))throw new O({code:"BAD_REQUEST",message:'"input" needs to be an object when doing a batch call'});let m=Y();for(let y of i.keys()){let d=p[y];d!==void 0&&(m[y]=e.router._def._config.transformer.input.deserialize(d))}return m}),a=await Promise.all(i.map(async(p,m)=>{let y=await je(e.router,p);return{batchIndex:m,path:p,procedure:y,getRawInput:async()=>{let d=(await s.read())[m];if(y?._def.type==="subscription"){var f,w;let g=(f=(w=e.headers.get("last-event-id"))!==null&&w!==void 0?w:e.searchParams.get("lastEventId"))!==null&&f!==void 0?f:e.searchParams.get("Last-Event-Id");if(g)if(F(d))d=S(S({},d),{},{lastEventId:g});else{var b;(b=d)!==null&&b!==void 0||(d={lastEventId:g})}}return d},result:()=>{var d;return(d=s.result())===null||d===void 0?void 0:d[m]}}})),c=new Set(a.map(p=>{var m;return(m=p.procedure)===null||m===void 0?void 0:m._def.type}).filter(Boolean));if(c.size>1)throw new O({code:"BAD_REQUEST",message:`Cannot mix procedure types in call: ${Array.from(c).join(", ")}`});let u=(t=c.values().next().value)!==null&&t!==void 0?t:"unknown",l=e.searchParams.get("connectionParams");return{isBatchCall:n,accept:Qs(r.headers),calls:a,type:u,connectionParams:l===null?null:kc(l),signal:r.signal,url:e.url}}},Lc=[Xs,{isMatch(e){var t;return!!(!((t=e.headers.get("content-type"))===null||t===void 0)&&t.startsWith("multipart/form-data"))},async parse(e){let{req:t}=e;if(t.method!=="POST")throw new O({code:"METHOD_NOT_SUPPORTED",message:"Only POST requests are supported for multipart/form-data requests"});let r=Nt(async()=>await t.formData()),n=await je(e.router,e.path);return{accept:null,calls:[{batchIndex:0,path:e.path,getRawInput:r.read,result:r.result,procedure:n}],isBatchCall:!1,type:"mutation",connectionParams:null,signal:t.signal,url:e.url}}},{isMatch(e){var t;return!!(!((t=e.headers.get("content-type"))===null||t===void 0)&&t.startsWith("application/octet-stream"))},async parse(e){let{req:t}=e;if(t.method!=="POST")throw new O({code:"METHOD_NOT_SUPPORTED",message:"Only POST requests are supported for application/octet-stream requests"});let r=Nt(async()=>t.body);return{calls:[{batchIndex:0,path:e.path,getRawInput:r.read,result:r.result,procedure:await je(e.router,e.path)}],isBatchCall:!1,accept:null,type:"mutation",connectionParams:null,signal:t.signal,url:e.url}}}];function Mc(e){let t=Lc.find(r=>r.isMatch(e));if(t)return t;if(!t&&e.method==="GET")return Xs;throw new O({code:"UNSUPPORTED_MEDIA_TYPE",message:e.headers.has("content-type")?`Unsupported content-type "${e.headers.get("content-type")}`:"Missing content-type header"})}async function jc(e){return await Mc(e.req).parse(e)}function Mt(e){return F(e)&&e.name==="AbortError"}function Hc(e="AbortError"){throw new DOMException(e,"AbortError")}function Bs(e){return Object.prototype.toString.call(e)==="[object Object]"}function Fc(e){var t,r;return Bs(e)===!1?!1:(t=e.constructor,t===void 0?!0:(r=t.prototype,!(Bs(r)===!1||r.hasOwnProperty("isPrototypeOf")===!1)))}var qs,Ct=new WeakMap,Jc=()=>{};qs=Symbol.toStringTag;var jt=class ye{constructor(t){X(this,"promise",void 0),X(this,"subscribers",[]),X(this,"settlement",null),X(this,qs,"Unpromise"),typeof t=="function"?this.promise=new Promise(t):this.promise=t;let r=this.promise.then(n=>{let{subscribers:o}=this;this.subscribers=null,this.settlement={status:"fulfilled",value:n},o?.forEach(({resolve:i})=>{i(n)})});"catch"in r&&r.catch(n=>{let{subscribers:o}=this;this.subscribers=null,this.settlement={status:"rejected",reason:n},o?.forEach(({reject:i})=>{i(n)})})}subscribe(){let t,r,{settlement:n}=this;if(n===null){if(this.subscribers===null)throw new Error("Unpromise settled but still has subscribers");let o=Bc();this.subscribers=$c(this.subscribers,o),t=o.promise,r=()=>{this.subscribers!==null&&(this.subscribers=zc(this.subscribers,o))}}else{let{status:o}=n;o==="fulfilled"?t=Promise.resolve(n.value):t=Promise.reject(n.reason),r=Jc}return Object.assign(t,{unsubscribe:r})}then(t,r){let n=this.subscribe(),{unsubscribe:o}=n;return Object.assign(n.then(t,r),{unsubscribe:o})}catch(t){let r=this.subscribe(),{unsubscribe:n}=r;return Object.assign(r.catch(t),{unsubscribe:n})}finally(t){let r=this.subscribe(),{unsubscribe:n}=r;return Object.assign(r.finally(t),{unsubscribe:n})}static proxy(t){let r=ye.getSubscribablePromise(t);return typeof r<"u"?r:ye.createSubscribablePromise(t)}static createSubscribablePromise(t){let r=new ye(t);return Ct.set(t,r),Ct.set(r,r),r}static getSubscribablePromise(t){return Ct.get(t)}static resolve(t){let r=typeof t=="object"&&t!==null&&"then"in t&&typeof t.then=="function"?t:Promise.resolve(t);return ye.proxy(r).subscribe()}static async any(t){let r=(Array.isArray(t)?t:[...t]).map(ye.resolve);try{return await Promise.any(r)}finally{r.forEach(({unsubscribe:n})=>{n()})}}static async race(t){let r=(Array.isArray(t)?t:[...t]).map(ye.resolve);try{return await Promise.race(r)}finally{r.forEach(({unsubscribe:n})=>{n()})}}static async raceReferences(t){let r=t.map(Wc);try{return await Promise.race(r)}finally{for(let n of r)n.unsubscribe()}}};function Wc(e){return jt.proxy(e).then(()=>[e])}function Bc(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}function $c(e,t){return[...e,t]}function Kc(e,t){return[...e.slice(0,t),...e.slice(t+1)]}function zc(e,t){let r=e.indexOf(t);return r!==-1?Kc(e,r):e}var $s,Ks,zs,Vs;(Ks=($s=Symbol).dispose)!==null&&Ks!==void 0||($s.dispose=Symbol());(Vs=(zs=Symbol).asyncDispose)!==null&&Vs!==void 0||(zs.asyncDispose=Symbol());function Vc(e,t){let r=e,n=r[Symbol.dispose];return r[Symbol.dispose]=()=>{t(),n?.call(r)},r}function Zs(e,t){let r=e,n=r[Symbol.asyncDispose];return r[Symbol.asyncDispose]=async()=>{await t(),await n?.call(r)},r}var Ht=Symbol();function ei(e){let t=null;return Vc({start(){if(t)throw new Error("Timer already started");return new Promise(r=>{t=setTimeout(()=>r(Ht),e)})}},()=>{t&&clearTimeout(t)})}function We(){var e=typeof SuppressedError=="function"?SuppressedError:function(o,i){var s=Error();return s.name="SuppressedError",s.error=o,s.suppressed=i,s},t={},r=[];function n(o,i){if(i!=null){if(Object(i)!==i)throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");if(o)var s=i[Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose")];if(s===void 0&&(s=i[Symbol.dispose||Symbol.for("Symbol.dispose")],o))var a=s;if(typeof s!="function")throw new TypeError("Object is not disposable.");a&&(s=function(){try{a.call(i)}catch(u){return Promise.reject(u)}}),r.push({v:i,d:s,a:o})}else o&&r.push({d:i,a:o});return i}return{e:t,u:n.bind(null,!1),a:n.bind(null,!0),d:function(){var i,s=this.e,a=0;function c(){for(;i=r.pop();)try{if(!i.a&&a===1)return a=0,r.push(i),Promise.resolve().then(c);if(i.d){var l=i.d.call(i.v);if(i.a)return a|=2,Promise.resolve(l).then(c,u)}else a|=1}catch(p){return u(p)}if(a===1)return s!==t?Promise.reject(s):Promise.resolve();if(s!==t)throw s}function u(l){return s=s!==t?new e(l,s):l,c()}return c()}}}function Ft(e,t){this.v=e,this.k=t}function Q(e){return new Ft(e,0)}function ie(e){return function(){return new Fe(e.apply(this,arguments))}}function Fe(e){var t,r;function n(i,s){try{var a=e[i](s),c=a.value,u=c instanceof Ft;Promise.resolve(u?c.v:c).then(function(l){if(u){var p=i==="return"?"return":"next";if(!c.k||l.done)return n(p,l);l=e[p](l).value}o(a.done?"return":"normal",l)},function(l){n("throw",l)})}catch(l){o("throw",l)}}function o(i,s){switch(i){case"return":t.resolve({value:s,done:!0});break;case"throw":t.reject(s);break;default:t.resolve({value:s,done:!1})}(t=t.next)?n(t.key,t.arg):r=null}this._invoke=function(i,s){return new Promise(function(a,c){var u={key:i,arg:s,resolve:a,reject:c,next:null};r?r=r.next=u:(t=r=u,n(i,s))})},typeof e.return!="function"&&(this.return=void 0)}Fe.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Fe.prototype.next=function(e){return this._invoke("next",e)},Fe.prototype.throw=function(e){return this._invoke("throw",e)},Fe.prototype.return=function(e){return this._invoke("return",e)};function Jt(e){let t=e[Symbol.asyncIterator]();return t[Symbol.asyncDispose]?t:Zs(t,async()=>{var r;await((r=t.return)===null||r===void 0?void 0:r.call(t))})}function Gc(e,t){return Dt.apply(this,arguments)}function Dt(){return Dt=ie(function*(e,t){try{var r=We();let n=r.a(Jt(e)),o,i=r.u(ei(t.gracePeriodMs)),s=t.count,a=new Promise(()=>{});for(;;){if(o=yield Q(jt.race([n.next(),a])),o===Ht&&Hc(),o.done)return o.value;yield o.value,--s===0&&(a=i.start()),o=null}}catch(n){r.e=n}finally{yield Q(r.d())}}),Dt.apply(this,arguments)}function Gs(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}function Yc(e,t){let r=e[Symbol.asyncIterator](),n="idle";function o(){n="done",t=()=>{}}function i(){n==="idle"&&(n="pending",r.next().then(s=>{if(s.done){n="done",t({status:"return",value:s.value}),o();return}n="idle",t({status:"yield",value:s.value})}).catch(s=>{t({status:"error",error:s}),o()}))}return{pull:i,destroy:async()=>{var s;o(),await((s=r.return)===null||s===void 0?void 0:s.call(r))}}}function Qc(){let e="idle",t=Gs(),r=[],n=new Set,o=[];function i(s){if(e!=="pending")return;let a=Yc(s,c=>{if(e==="pending"){switch(c.status){case"yield":o.push([a,c]);break;case"return":n.delete(a);break;case"error":o.push([a,c]),n.delete(a)}t.resolve()}});n.add(a),a.pull()}return{add(s){switch(e){case"idle":r.push(s);break;case"pending":i(s)}},[Symbol.asyncIterator](){return ie(function*(){try{var s=We();if(e!=="idle")throw new Error("Cannot iterate twice");for(e="pending",s.a(Zs({},async()=>{e="done";let a=[];if(await Promise.all(Array.from(n.values()).map(async c=>{try{await c.destroy()}catch(u){a.push(u)}})),o.length=0,n.clear(),t.resolve(),a.length>0)throw new AggregateError(a)}));r.length>0;)i(r.shift());for(;n.size>0;){for(yield Q(t.promise);o.length>0;){let[a,c]=o.shift();switch(c.status){case"yield":yield c.value,a.pull();break;case"error":throw c.error}}t=Gs()}}catch(a){s.e=a}finally{yield Q(s.d())}})()}}}function ti(e){let t=e[Symbol.asyncIterator]();return new ReadableStream({async cancel(){var r;await((r=t.return)===null||r===void 0?void 0:r.call(t))},async pull(r){let n=await t.next();if(n.done){r.close();return}r.enqueue(n.value)}})}var Je=Symbol("ping");function ri(e,t){return Ut.apply(this,arguments)}function Ut(){return Ut=ie(function*(e,t){try{var r=We();let o=r.a(Jt(e)),i,s=o.next();for(;;)try{var n=We();let a=n.u(ei(t));if(i=yield Q(jt.race([s,a.start()])),i===Ht){yield Je;continue}if(i.done)return i.value;s=o.next(),yield i.value,i=null}catch(a){n.e=a}finally{n.d()}}catch(o){r.e=o}finally{yield Q(r.d())}}),Ut.apply(this,arguments)}function kt(e){var t,r,n,o=2;for(typeof Symbol<"u"&&(r=Symbol.asyncIterator,n=Symbol.iterator);o--;){if(r&&(t=e[r])!=null)return t.call(e);if(n&&(t=e[n])!=null)return new it(t.call(e));r="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function it(e){function t(r){if(Object(r)!==r)return Promise.reject(new TypeError(r+" is not an object."));var n=r.done;return Promise.resolve(r.value).then(function(o){return{value:o,done:n}})}return it=function(n){this.s=n,this.n=n.next},it.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(n){var o=this.s.return;return o===void 0?Promise.resolve({value:n,done:!0}):t(o.apply(this.s,arguments))},throw:function(n){var o=this.s.return;return o===void 0?Promise.reject(n):t(o.apply(this.s,arguments))}},new it(e)}var Xc=0,qc=1,Zc=0,eu=1,tu=0,ru=1,nu=2;function ni(e){return(F(e)||nt(e))&&typeof e?.then=="function"&&typeof e?.catch=="function"}var ou=class extends Error{constructor(e){super("Max depth reached at path: "+e.join(".")),this.path=e}};function su(e){return Lt.apply(this,arguments)}function Lt(){return Lt=ie(function*(e){let{data:t}=e,r=0,n=0,o=Qc();function i(g){let v=r++,T=g(v);return o.add(T),v}function s(g,v){return i((function(){var T=ie(function*(E){let P=c(v);P&&(g.catch(H=>{var re;(re=e.onError)===null||re===void 0||re.call(e,{error:H,path:v})}),g=Promise.reject(P));try{let H=yield Q(g);yield[E,Zc,l(H,v)]}catch(H){var L,K;(L=e.onError)===null||L===void 0||L.call(e,{error:H,path:v}),yield[E,eu,(K=e.formatError)===null||K===void 0?void 0:K.call(e,{error:H,path:v})]}});return function(E){return T.apply(this,arguments)}})())}function a(g,v){return i((function(){var T=ie(function*(E){try{var P=We();let H=c(v);if(H)throw H;let re=P.a(Jt(g));try{for(;;){let R=yield Q(re.next());if(R.done){yield[E,tu,l(R.value,v)];break}yield[E,ru,l(R.value,v)]}}catch(R){var L,K;(L=e.onError)===null||L===void 0||L.call(e,{error:R,path:v}),yield[E,nu,(K=e.formatError)===null||K===void 0?void 0:K.call(e,{error:R,path:v})]}}catch(H){P.e=H}finally{yield Q(P.d())}});return function(E){return T.apply(this,arguments)}})())}function c(g){return e.maxDepth&&g.length>e.maxDepth?new ou(g):null}function u(g,v){if(ni(g))return[Xc,s(g,v)];if(Le(g)){if(e.maxDepth&&v.length>=e.maxDepth)throw new Error("Max depth reached");return[qc,a(g,v)]}return null}function l(g,v){if(g===void 0)return[[]];let T=u(g,v);if(T)return[[n],[null,...T]];if(!Fc(g))return[[g]];let E=Y(),P=[];for(let[L,K]of Object.entries(g)){let H=u(K,[...v,L]);if(!H){E[L]=K;continue}E[L]=n,P.push([L,...H])}return[[E],...P]}let p=Y();for(let[g,v]of Object.entries(t))p[g]=l(v,[g]);yield p;let m=o;e.pingMs&&(m=ri(o,e.pingMs));var y=!1,d=!1,f;try{for(var w=kt(m),b;y=!(b=yield Q(w.next())).done;y=!1)yield b.value}catch(g){d=!0,f=g}finally{try{y&&w.return!=null&&(yield Q(w.return()))}finally{if(d)throw f}}}),Lt.apply(this,arguments)}function iu(e){let t=ti(su(e)),{serialize:r}=e;return r&&(t=t.pipeThrough(new TransformStream({transform(n,o){n===Je?o.enqueue(Je):o.enqueue(r(n))}}))),t.pipeThrough(new TransformStream({transform(n,o){n===Je?o.enqueue(" "):o.enqueue(JSON.stringify(n)+`
|
|
8
|
+
`)}})).pipeThrough(new TextEncoderStream)}function au(e){var t={},r=!1;function n(o,i){return r=!0,i=new Promise(function(s){s(e[o](i))}),{done:!1,value:new Ft(i,1)}}return t[typeof Symbol<"u"&&Symbol.iterator||"@@iterator"]=function(){return this},t.next=function(o){return r?(r=!1,o):n("next",o)},typeof e.throw=="function"&&(t.throw=function(o){if(r)throw r=!1,o;return n("throw",o)}),typeof e.return=="function"&&(t.return=function(o){return r?(r=!1,o):n("return",o)}),t}var cu="ping",uu="serialized-error",lu="connected",du="return";function fu(e){var t,r,n,o,i;let{serialize:s=_s}=e,a={enabled:(t=(r=e.ping)===null||r===void 0?void 0:r.enabled)!==null&&t!==void 0?t:!1,intervalMs:(n=(o=e.ping)===null||o===void 0?void 0:o.intervalMs)!==null&&n!==void 0?n:1e3},c=(i=e.client)!==null&&i!==void 0?i:{};if(a.enabled&&c.reconnectAfterInactivityMs&&a.intervalMs>c.reconnectAfterInactivityMs)throw new Error(`Ping interval must be less than client reconnect interval to prevent unnecessary reconnection - ping.intervalMs: ${a.intervalMs} client.reconnectAfterInactivityMs: ${c.reconnectAfterInactivityMs}`);function u(){return l.apply(this,arguments)}function l(){return l=ie(function*(){yield{event:lu,data:JSON.stringify(c)};let y=e.data;e.emitAndEndImmediately&&(y=Gc(y,{count:1,gracePeriodMs:1})),a.enabled&&a.intervalMs!==1/0&&a.intervalMs>0&&(y=ri(y,a.intervalMs));let d,f;var w=!1,b=!1,g;try{for(var v=kt(y),T;w=!(T=yield Q(v.next())).done;w=!1){if(d=T.value,d===Je){yield{event:cu,data:""};continue}f=Tt(d)?{id:d[0],data:d[1]}:{data:d},f.data=JSON.stringify(s(f.data)),yield f,d=null,f=null}}catch(E){b=!0,g=E}finally{try{w&&v.return!=null&&(yield Q(v.return()))}finally{if(b)throw g}}}),l.apply(this,arguments)}function p(){return m.apply(this,arguments)}function m(){return m=ie(function*(){try{yield*au(kt(u())),yield{event:du,data:""}}catch(f){var y,d;if(Mt(f))return;let w=B(f),b=(y=(d=e.formatError)===null||d===void 0?void 0:d.call(e,{error:w}))!==null&&y!==void 0?y:null;yield{event:uu,data:JSON.stringify(s(b))}}}),m.apply(this,arguments)}return ti(p()).pipeThrough(new TransformStream({transform(y,d){"event"in y&&d.enqueue(`event: ${y.event}
|
|
9
|
+
`),"data"in y&&d.enqueue(`data: ${y.data}
|
|
10
|
+
`),"id"in y&&d.enqueue(`id: ${y.id}
|
|
11
|
+
`),"comment"in y&&d.enqueue(`: ${y.comment}
|
|
12
|
+
`),d.enqueue(`
|
|
13
|
+
|
|
14
|
+
`)}})).pipeThrough(new TextEncoderStream)}var pu={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no",Connection:"keep-alive"};function xt(e){return oe(ie(function*(){throw e}))}function mu(e){let t=new AbortController;return{signal:Ts([e,t.signal]),controller:t}}var yu={mutation:["POST"],query:["GET"],subscription:["GET"]},hu={mutation:["POST"],query:["GET","POST"],subscription:["GET","POST"]};function He(e){var t,r,n;let{ctx:o,info:i,responseMeta:s,untransformedJSON:a,errors:c=[],headers:u}=e,l=a?xs(a):200,p=!a,m=p?[]:Array.isArray(a)?a:[a],y=(t=s?.({ctx:o,info:i,paths:i?.calls.map(d=>d.path),data:m,errors:c,eagerGeneration:p,type:(r=i==null||(n=i.calls.find(d=>{var f;return(f=d.procedure)===null||f===void 0?void 0:f._def.type}))===null||n===void 0||(n=n.procedure)===null||n===void 0?void 0:n._def.type)!==null&&r!==void 0?r:"unknown"}))!==null&&t!==void 0?t:{};if(y.headers)if(y.headers instanceof Headers)for(let[d,f]of y.headers.entries())u.append(d,f);else for(let[d,f]of Object.entries(y.headers))if(Array.isArray(f))for(let w of f)u.append(d,w);else typeof f=="string"&&u.set(d,f);return y.status&&(l=y.status),{status:l}}function gu(e,t){let{router:r,req:n,onError:o}=t.opts,i=B(e);o?.({error:i,path:t.path,input:t.input,ctx:t.ctx,type:t.type,req:n});let s={error:se({config:r._def._config,error:i,type:t.type,path:t.path,input:t.input,ctx:t.ctx})},a=me(r._def._config,s);return{error:i,untransformedJSON:s,body:JSON.stringify(a)}}function Ys(e){return F(e)?Le(e)?!0:Object.values(e).some(ni)||Object.values(e).some(Le):!1}async function oi(e){var t,r,n,o,i,s;let{router:a,req:c}=e,u=new Headers([["vary","trpc-accept, accept"]]),l=a._def._config,p=new URL(c.url);if(c.method==="HEAD")return new Response(null,{status:204});let m=(t=(r=e.allowBatching)!==null&&r!==void 0?r:(n=e.batching)===null||n===void 0?void 0:n.enabled)!==null&&t!==void 0?t:!0,y=((o=e.allowMethodOverride)!==null&&o!==void 0?o:!1)&&c.method==="POST",d=await oe(async()=>{try{return[void 0,await jc({req:c,path:decodeURIComponent(e.path),router:a,searchParams:p.searchParams,headers:e.req.headers,url:p,maxBatchSize:e.maxBatchSize})]}catch(T){return[B(T),void 0]}}),f=oe(()=>{let T;return{valueOrUndefined:()=>{if(T)return T[1]},value:()=>{let[E,P]=T;if(E)throw E;return P},create:async E=>{if(T)throw new Error("This should only be called once - report a bug in tRPC");try{T=[void 0,await e.createContext({info:E})]}catch(P){T=[B(P),void 0]}}}}),w=y?hu:yu,b=Qs(c.headers)==="application/jsonl",g=(i=(s=l.sse)===null||s===void 0?void 0:s.enabled)!==null&&i!==void 0?i:!0;try{let[T,E]=d;if(T)throw T;if(E.isBatchCall&&!m)throw new O({code:"BAD_REQUEST",message:"Batching is not enabled on the server"});if(b&&!E.isBatchCall)throw new O({message:"Streaming requests must be batched (you can do a batch of 1)",code:"BAD_REQUEST"});await f.create(E);let P=E.calls.map(async R=>{let M=R.procedure,I=mu(e.req.signal);try{if(e.error)throw e.error;if(!M)throw new O({code:"NOT_FOUND",message:`No procedure found on path "${R.path}"`});if(!w[M._def.type].includes(c.method))throw new O({code:"METHOD_NOT_SUPPORTED",message:`Unsupported ${c.method}-request to ${M._def.type} procedure at path "${R.path}"`});if(M._def.type==="subscription"){var k;if(E.isBatchCall)throw new O({code:"BAD_REQUEST",message:"Cannot batch subscription calls"});if(!((k=l.sse)===null||k===void 0)&&k.maxDurationMs){let G=function(){clearTimeout(j),I.signal.removeEventListener("abort",G),I.controller.abort()},j=setTimeout(G,l.sse.maxDurationMs);I.signal.addEventListener("abort",G)}}return[void 0,{data:await M({path:R.path,getRawInput:R.getRawInput,ctx:f.value(),type:M._def.type,signal:I.signal,batchIndex:R.batchIndex}),signal:M._def.type==="subscription"?I.signal:void 0}]}catch(G){var D,U,z;let j=B(G),W=R.result();return(D=e.onError)===null||D===void 0||D.call(e,{error:j,path:R.path,input:W,ctx:f.valueOrUndefined(),type:(U=(z=R.procedure)===null||z===void 0?void 0:z._def.type)!==null&&U!==void 0?U:"unknown",req:e.req}),[j,void 0]}});if(!E.isBatchCall){let[R]=E.calls,[M,I]=await P[0];switch(E.type){case"unknown":case"mutation":case"query":{if(u.set("content-type","application/json"),Ys(I?.data))throw new O({code:"UNSUPPORTED_MEDIA_TYPE",message:"Cannot use stream-like response in non-streaming request - use httpBatchStreamLink"});let k=M?{error:se({config:l,ctx:f.valueOrUndefined(),error:M,input:R.result(),path:R.path,type:E.type})}:{result:{data:I.data}},D=He({ctx:f.valueOrUndefined(),info:E,responseMeta:e.responseMeta,errors:M?[M]:[],headers:u,untransformedJSON:[k]});return new Response(JSON.stringify(me(l,k)),{status:D.status,headers:u})}case"subscription":{let k=oe(()=>M?xt(M):g?!st(I.data)&&!Le(I.data)?xt(new O({message:`Subscription ${R.path} did not return an observable or a AsyncGenerator`,code:"INTERNAL_SERVER_ERROR"})):st(I.data)?Pt(I.data,e.req.signal):I.data:xt(new O({code:"METHOD_NOT_SUPPORTED",message:'Missing experimental flag "sseSubscriptions"'}))),D=fu(S(S({},l.sse),{},{data:k,serialize:j=>l.transformer.output.serialize(j),formatError(j){var W,ve,be;let Tr=B(j.error),Rr=R?.result(),Ar=R?.path,Or=(W=R==null||(ve=R.procedure)===null||ve===void 0?void 0:ve._def.type)!==null&&W!==void 0?W:"unknown";return(be=e.onError)===null||be===void 0||be.call(e,{error:Tr,path:Ar,input:Rr,ctx:f.valueOrUndefined(),req:e.req,type:Or}),se({config:l,ctx:f.valueOrUndefined(),error:Tr,input:Rr,path:Ar,type:Or})}}));for(let[j,W]of Object.entries(pu))u.set(j,W);let U=He({ctx:f.valueOrUndefined(),info:E,responseMeta:e.responseMeta,errors:[],headers:u,untransformedJSON:null}),z=I?.signal,G=D;if(z){let j=D.getReader(),W=()=>{j.cancel()};z.aborted?W():z.addEventListener("abort",W,{once:!0}),G=new ReadableStream({async pull(ve){let be=await j.read();be.done?(z.removeEventListener("abort",W),ve.close()):ve.enqueue(be.value)},cancel(){return z.removeEventListener("abort",W),j.cancel()}})}return new Response(G,{headers:u,status:U.status})}}}if(E.accept==="application/jsonl"){u.set("content-type","application/json"),u.set("transfer-encoding","chunked");let R=He({ctx:f.valueOrUndefined(),info:E,responseMeta:e.responseMeta,errors:[],headers:u,untransformedJSON:null}),M=iu(S(S({},l.jsonl),{},{maxDepth:1/0,data:P.map(async(I,k)=>{let[D,U]=await I,z=E.calls[k];if(D){var G,j;return{error:se({config:l,ctx:f.valueOrUndefined(),error:D,input:z.result(),path:z.path,type:(G=(j=z.procedure)===null||j===void 0?void 0:j._def.type)!==null&&G!==void 0?G:"unknown"})}}let W=st(U.data)?Pt(U.data,e.req.signal):Promise.resolve(U.data);return{result:Promise.resolve({data:W})}}),serialize:I=>l.transformer.output.serialize(I),onError:I=>{var k,D;(k=e.onError)===null||k===void 0||k.call(e,{error:B(I.error),path:void 0,input:void 0,ctx:f.valueOrUndefined(),req:e.req,type:(D=E?.type)!==null&&D!==void 0?D:"unknown"})},formatError(I){var k,D;let U=E?.calls[I.path[0]],z=B(I.error),G=U?.result(),j=U?.path,W=(k=U==null||(D=U.procedure)===null||D===void 0?void 0:D._def.type)!==null&&k!==void 0?k:"unknown";return se({config:l,ctx:f.valueOrUndefined(),error:z,input:G,path:j,type:W})}}));return new Response(M,{headers:u,status:R.status})}u.set("content-type","application/json");let L=(await Promise.all(P)).map(R=>{let[M,I]=R;return M?R:Ys(I.data)?[new O({code:"UNSUPPORTED_MEDIA_TYPE",message:"Cannot use stream-like response in non-streaming request - use httpBatchStreamLink"}),void 0]:R}),K=L.map(([R,M],I)=>{let k=E.calls[I];if(R){var D,U;return{error:se({config:l,ctx:f.valueOrUndefined(),error:R,input:k.result(),path:k.path,type:(D=(U=k.procedure)===null||U===void 0?void 0:U._def.type)!==null&&D!==void 0?D:"unknown"})}}return{result:{data:M.data}}}),H=L.map(([R])=>R).filter(Boolean),re=He({ctx:f.valueOrUndefined(),info:E,responseMeta:e.responseMeta,untransformedJSON:K,errors:H,headers:u});return new Response(JSON.stringify(me(l,K)),{status:re.status,headers:u})}catch(T){var v;let[E,P]=d,L=f.valueOrUndefined(),{error:K,untransformedJSON:H,body:re}=gu(T,{opts:e,ctx:f.valueOrUndefined(),type:(v=P?.type)!==null&&v!==void 0?v:"unknown"}),R=He({ctx:L,info:P,responseMeta:e.responseMeta,untransformedJSON:H,errors:[K],headers:u});return new Response(re,{status:R.status,headers:u})}}import{IncomingMessage as wu}from"node:http";function Eu(e,t){if("body"in e)return e.body===void 0?void 0:typeof e.body=="string"||e.body instanceof wu?e.body:JSON.stringify(e.body);let r=0,n=!1;return new ReadableStream({start(o){let i=a=>{if(r+=a.length,!t.maxBodySize||r<=t.maxBodySize){o.enqueue(new Uint8Array(a.buffer,a.byteOffset,a.byteLength));return}o.error(new O({code:"PAYLOAD_TOO_LARGE"})),n=!0,e.off("data",i),e.off("end",s)},s=()=>{n||(n=!0,e.off("data",i),e.off("end",s),o.close())};e.on("data",i),e.on("end",s)},cancel(){e.destroy()}})}function Wt(e){try{var t,r;let n=e.headers[":scheme"]&&e.headers[":scheme"]==="https"||e.socket&&"encrypted"in e.socket&&e.socket.encrypted?"https:":"http:",o=(t=(r=e.headers.host)!==null&&r!==void 0?r:e.headers[":authority"])!==null&&t!==void 0?t:"localhost";return new URL(e.url,`${n}//${o}`)}catch(n){throw new O({code:"BAD_REQUEST",message:"Invalid URL",cause:n})}}function Su(e){let t=new Headers;for(let r in e){let n=e[r];if(!(typeof r=="string"&&r.startsWith(":")))if(Array.isArray(n))for(let o of n)t.append(r,o);else n!=null&&t.append(r,n)}return t}function vu(e,t,r){let n=new AbortController,o=()=>{t.off("close",o),e.off("aborted",o),n.abort()};t.once("close",o),e.once("aborted",o);let i=Wt(e),s={headers:Su(e.headers),method:e.method,signal:n.signal};return e.method!=="GET"&&e.method!=="HEAD"&&(s.body=Eu(e,r),s.duplex="half"),new Request(i,s)}async function bu(e,t){e.write(t)===!1&&await new Promise((r,n)=>{let o=a=>{n(a),s()},i=()=>{r(),s()},s=()=>{e.off("error",o),e.off("drain",i)};e.once("error",o),e.once("drain",i)})}async function _u(e){let{res:t}=e;try{let r=new WritableStream({async write(n){var o;await bu(t,n),(o=t.flush)===null||o===void 0||o.call(t)}});await e.body.pipeTo(r,{signal:e.signal})}catch(r){if(Mt(r))return;throw r}}async function Tu(e){let{response:t,rawResponse:r}=e;r.statusCode===200&&(r.statusCode=t.status);for(let[o,i]of t.headers)o.toLowerCase()!=="set-cookie"&&r.setHeader(o,i);let n=t.headers.getSetCookie();n.length>0&&r.setHeader("set-cookie",n);try{t.body&&await _u({res:r,signal:e.request.signal,body:t.body})}catch(o){throw r.headersSent||(r.statusCode=500),o}finally{r.end()}}function Bt(e){return t=>{var r;let{res:n,req:o}=e,i=B(t),s=se({config:e.router._def._config,error:i,type:"unknown",path:void 0,input:void 0,ctx:void 0});(r=e.onError)===null||r===void 0||r.call(e,{req:o,error:i,type:"unknown",path:void 0,input:void 0,ctx:void 0});let a=me(e.router._def._config,{error:s});n.statusCode=s.data.httpStatus,n.end(JSON.stringify(a))}}async function si(e){return new Promise(t=>{var r;let n=(r=e.middleware)!==null&&r!==void 0?r:((o,i,s)=>s());return e.res.once("finish",()=>{t()}),n(e.req,e.res,o=>{oe(async()=>{var i;let s=vu(e.req,e.res,{maxBodySize:(i=e.maxBodySize)!==null&&i!==void 0?i:null}),a=async c=>{var u;return await((u=e.createContext)===null||u===void 0?void 0:u.call(e,S(S({},e),c)))};await Tu({request:s,response:await oi(S(S({},e),{},{req:s,error:o?B(o):null,createContext:a,onError(c){var u;e==null||(u=e.onError)===null||u===void 0||u.call(e,S(S({},c),{},{req:e.req}))}})),rawResponse:e.res})}).catch(Bt(e))})})}function Ru(e){var t;let r=((t=e.basePath)!==null&&t!==void 0?t:"/").length;return(n,o)=>{let i="";oe(async()=>{i=Wt(n).pathname.slice(r),await si(S(S({},e),{},{req:n,res:o,path:i}))}).catch(Bt(S({req:n,res:o,path:i},e)))}}function ii(e){return Ru(e)}function x(e,t,r,n={}){if(e.headersSent)return;let o=Buffer.from(JSON.stringify(r),"utf8");e.writeHead(t,{"Content-Type":"application/json; charset=utf-8","Content-Length":String(o.length),...n}),e.end(o)}function A(e,t,r,n,o={}){x(e,t,{ok:!1,code:r,message:n},o)}function he(e,t,r){x(e,t,r,{"Cache-Control":"no-store"})}function V(e,t){A(e,405,"method-not-allowed",`Use ${t}`,{Allow:t})}function $t(e){let t=e.headers["content-length"];if(t===void 0)return null;let r=Number(t);return Number.isFinite(r)&&r>=0?r:null}function Kt(e,t,r,n,o,i){let s=0;e.on("data",a=>{s+=a.length,s>i&&e.socket.destroy()}),e.on("error",()=>{}),e.resume(),A(t,r,n,o)}async function ae(e,t){let r=()=>(Kt(e,t,413,"too-large","Body exceeds 8192 bytes",8192),null);if(($t(e)??0)>8192)return r();let n=await new Promise((i,s)=>{let a=[],c=0,u=y=>{if(c+=y.length,c<=8192){a.push(y);return}m(),i(null)},l=()=>{m(),i(Buffer.concat(a))},p=y=>{m(),s(y)},m=()=>{e.off("data",u),e.off("end",l),e.off("error",p)};e.on("data",u),e.on("end",l),e.on("error",p)});if(n===null)return r();if(n.length===0)return{};let o;try{o=JSON.parse(n.toString("utf8"))}catch{return A(t,400,"bad-json","Body is not valid JSON"),null}return o===null||typeof o!="object"||Array.isArray(o)?(A(t,400,"bad-json","Body must be a JSON object"),null):o}import*as ui from"net";import{execFile as Mu}from"child_process";import{promisify as ju}from"util";var ci="#--tasklist--#",Au=`netstat -ano; echo '${ci}'; MSYS_NO_PATHCONV=1 tasklist /FO CSV /NH`,Ou=new Set(["0.0.0.0:0","[::]:0","*:*"]),zt=new Set(["0.0.0.0","127.0.0.1","[::]","[::1]","*"]);function Iu(e){let t=new Map;for(let r of e.split(`
|
|
15
|
+
`)){let n=/^"([^"]*)","(\d+)"/.exec(r.trim());n&&t.set(Number(n[2]),n[1].replace(/\.exe$/i,""))}return t}function Pu(e){let[t,r]=e.split(ci),n=r?Iu(r):new Map,o=new Map;for(let i of t.split(`
|
|
16
|
+
`)){let s=i.trim().split(/\s+/);if(s.length<4||s[0]!=="TCP"||!Ou.has(s[2]))continue;let a=s[1],c=a.lastIndexOf(":");if(c<0)continue;let u=Number(a.slice(c+1));if(!Number.isInteger(u)||u<1024)continue;let l=a.slice(0,c);if(!zt.has(l))continue;let p=Number(s[s.length-1]),m=n.get(p)??null,y=o.get(u);(!y||!y.process&&m)&&o.set(u,{port:u,address:l,process:m})}return[...o.values()].sort((i,s)=>i.port-s.port)}function ai(e){let t=new Map;for(let r of e.split(`
|
|
17
|
+
`)){let n=r.trim().split(/\s+/);if(n.length<4)continue;let o=n[3],i=o.lastIndexOf(":");if(i<0)continue;let s=Number(o.slice(i+1));if(!Number.isInteger(s)||s<1024)continue;let a=o.slice(0,i);if(!zt.has(a))continue;let c=/users:\(\("([^"]+)"/.exec(r),u=t.get(s);(!u||!u.process&&c)&&t.set(s,{port:s,address:a,process:c?c[1]:null})}return[...t.values()].sort((r,n)=>r.port-n.port)}var Cu="lsof -nP -iTCP -sTCP:LISTEN -F cn";function xu(e){let t=new Map,r=null;for(let n of e.split(`
|
|
18
|
+
`)){let o=n.trim(),i=o[0],s=o.slice(1);if(i==="p")r=null;else if(i==="c")r=s||null;else if(i==="n"){let a=s.lastIndexOf(":");if(a<0)continue;let c=Number(s.slice(a+1));if(!Number.isInteger(c)||c<1024)continue;let u=s.slice(0,a);if(!zt.has(u))continue;let l=t.get(c);(!l||!l.process&&r)&&t.set(c,{port:c,address:u,process:r})}}return[...t.values()].sort((n,o)=>n.port-o.port)}var Nu="0A",Du=new Map([["00000000","0.0.0.0"],["0100007F","127.0.0.1"],["00000000000000000000000000000000","[::]"],["00000000000000000000000001000000","[::1]"]]);function Uu(e){let t=new Map;for(let r of e.split(`
|
|
19
|
+
`)){let n=r.trim().split(/\s+/);if(n.length<4||n[3]!==Nu)continue;let[o,i]=n[1].split(":"),s=Du.get(o?.toUpperCase()??"");if(!s)continue;let a=parseInt(i,16);!Number.isInteger(a)||a<1024||t.has(a)||t.set(a,{port:a,address:s,process:null})}return[...t.values()].sort((r,n)=>r.port-n.port)}var ku="cat /proc/net/tcp /proc/net/tcp6 2>/dev/null";function Lu(e){return e==="win32"?[{command:Au,parse:Pu}]:e==="darwin"?[{command:Cu,parse:xu}]:[{command:"ss -ltnpH",parse:ai},{command:"ss -ltnH",parse:ai},{command:ku,parse:Uu}]}async function at(e,t){let r="no probe produced output";for(let n of Lu(e))try{let o=await t(n.command);if(o.trim()!=="")return{ports:n.parse(o)}}catch(o){r=o.message}return{ports:[],error:r}}var ct=N("port-forward"),Hu=ju(Mu),li="/forward",Fu="/api/forward/ports",Ju=64,Wu=4004;function Bu(e){let t;try{t=new URL(e,"http://localhost")}catch{return null}let r=Number(t.searchParams.get("port"));if(!Number.isInteger(r)||r<1024||r>65535)return null;let n=t.searchParams.get("host")??"127.0.0.1";return n!=="127.0.0.1"&&n!=="localhost"&&n!=="::1"?null:{host:n,port:r}}async function $u(){if(process.platform==="win32")return ct.warn("port discovery is not implemented for a Windows-hosted daemon"),[];let{ports:e,error:t}=await at(process.platform,async r=>(await Hu("sh",["-c",r],{timeout:3e3})).stdout);return t&&ct.warn(`port discovery unavailable: ${t}`),e}function di(){return{[Fu]:async(e,t)=>{x(t,200,{ok:!0,data:{ports:await $u()}})}}}function fi(){let e=new et.default({noServer:!0}),t=0;return{handleUpgrade:(n,o,i)=>{let s=Bu(n.url??"");if(!s){o.destroy();return}if(t>=Ju){ct.warn(`forward refused (${t} already open): ${s.host}:${s.port}`),o.destroy();return}e.handleUpgrade(n,o,i,a=>{t+=1,Ku(a,s,()=>{t-=1})})},close:()=>e.close()}}function Ku(e,t,r){let n=ui.connect({host:t.host,port:t.port});n.setNoDelay(!0);let o=!1,i=(s,a)=>{if(!o){o=!0,n.destroy();try{e.close(s,a)}catch{}r()}};n.on("connect",()=>{ct.info(`forward open \u2192 ${t.host}:${t.port}`)}),n.on("error",s=>i(Wu,s.code??"error")),n.on("close",()=>i(1e3,"target closed")),n.on("data",s=>{n.pause(),e.send(s,{binary:!0},()=>n.resume())}),e.on("message",s=>{let a=Array.isArray(s)?Buffer.concat(s):Buffer.from(s);n.write(a)}),e.on("close",()=>i(1e3,"client closed")),e.on("error",()=>i(1011,"socket error"))}import*as pi from"crypto";import{readFileSync as zu,writeFileSync as Vu,mkdirSync as Gu,renameSync as Yu}from"fs";import*as mi from"path";var Qu=N("ui-http"),Gt=720*60*60*1e3;function yi(e,t){let r=Array.isArray(e)?e[0]:e;if(r)for(let n of r.split(";")){let o=n.indexOf("=");if(o<0||n.slice(0,o).trim()!==t)continue;let i=n.slice(o+1).trim();try{return decodeURIComponent(i)}catch{return i}}}function hi(e={}){let t=e.ttlMs&&e.ttlMs>0?e.ttlMs:Gt,r=e.now??(()=>Date.now()),n=e.file,o=new Map,i=()=>{if(!n)return;let c;try{c=JSON.parse(zu(n,"utf8"))}catch{return}if(!c||typeof c!="object")return;let u=r();for(let[l,p]of Object.entries(c))typeof p=="number"&&p>u&&o.set(l,p)},s=()=>{if(n)try{Gu(mi.dirname(n),{recursive:!0});let c=`${n}.tmp`;Vu(c,JSON.stringify(Object.fromEntries(o)),{mode:384}),Yu(c,n)}catch(c){Qu.warn(`could not persist UI sessions: ${c.message}`)}},a=()=>{let c=r(),u=!1;for(let[l,p]of o)p<=c&&(o.delete(l),u=!0);return u};return i(),{create(){a();let c=pi.randomBytes(32).toString("hex");return o.set(c,r()+t),s(),c},verify(c){if(!c)return!1;let u=r(),l=!1;for(let[p,m]of o)Z(p,c)&&m>u&&(l=!0);return l},revoke(c){if(!c)return;let u=o.delete(c),l=a();(u||l)&&s()},size(){return a(),o.size}}}var Yt=N("ui-http"),Si="cortex_ui",Qt="/api/ui/login",Xu="/api/ui/logout",Be="/api/ui/session",Xt=250;function gi(e){return Array.isArray(e)?e[0]:e}function wi(e){if(gi(e.headers["x-forwarded-proto"])?.split(",")[0].trim()==="https"||e.socket.encrypted)return!0;let t=(gi(e.headers.host)??"").replace(/:\d+$/,"").toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function Ei(e,t,r){let n=[`${Si}=${e}`,"Path=/","HttpOnly","SameSite=Strict",`Max-Age=${t}`];return r&&n.push("Secure"),n.join("; ")}function qt(e){return yi(e.headers.cookie,Si)}function qu(e,t){return e.redeemCode&&ts(t)?e.redeemCode(t):Z(e.getToken(),t)}function vi(e){let t=Math.floor(e.ttlMs/1e3);return{[Qt]:async(r,n)=>{if(r.method!=="POST")return V(n,"POST");let o=await ae(r,n);if(!o)return;let i=typeof o.token=="string"?o.token.trim():"";if(!qu(e,i))return await new Promise(c=>setTimeout(c,Xt)),Yt.warn("ui login rejected: wrong token or pairing code"),A(n,401,"invalid-token","Invalid token");let s=e.store.create(),a=wi(r);a||Yt.warn("ui login over plain HTTP to a non-loopback host \u2014 the session cookie is issued without Secure, so anyone on this network path can read it. Use HTTPS (a tunnel) for real use."),Yt.info("ui login accepted \u2014 session issued"),x(n,200,{ok:!0},{"Set-Cookie":Ei(s,t,a)})},[Xu]:async(r,n)=>{if(r.method!=="POST")return V(n,"POST");e.store.revoke(qt(r)),x(n,200,{ok:!0},{"Set-Cookie":Ei("",0,wi(r))})},[Be]:async(r,n)=>{x(n,200,{ok:!0,data:{authenticated:await e.authorize(r),tokenLogin:!0}})}}}function bi(e){return{[Be]:async(t,r)=>{x(r,200,{ok:!0,data:{authenticated:await e(t),tokenLogin:!1}})}}}var we=N("ui-http"),Zu="cf-access-jwt-assertion",Zt="/trpc/",el="GET, POST, OPTIONS",tl=`${ke}, content-type, x-session-id, x-file-name, x-cortex-client`,rl="86400",nl=16*1024*1024,ol=new Set(["GET","HEAD","OPTIONS"]);function Ti(e,t,r){let n=e.headers[ke],o=Array.isArray(n)?n[0]:n;return Z(t(),o)||r?.(o)===!0}async function sl(e,t){if(!t)return!1;let r=e.headers[Zu],n=Array.isArray(r)?r[0]:r;return n?t(n):!1}function Ri(e){return async t=>Ti(t,e.getToken,e.matchDeviceToken)||e.verifySession?.(qt(t))?!0:sl(t,e.verifyAccessJwt)}function $e(e){return Array.isArray(e)?e[0]:e}function Ai(e,t){let r=$e(e.headers.origin);if(r===void 0||t?.includes(r))return!0;try{return new URL(r).host===$e(e.headers.host)}catch{return!1}}function il(e,t,r){if(!r||r.length===0)return;let n=$e(e.headers.origin);if(!(!n||!r.includes(n)))return t.setHeader("Access-Control-Allow-Origin",n),t.setHeader("Vary","Origin"),t.setHeader("Access-Control-Allow-Methods",el),t.setHeader("Access-Control-Allow-Headers",tl),t.setHeader("Access-Control-Max-Age",rl),n}function al(e,t,r){if(!r||!fe.existsSync(r)){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("Cortex UI not built");return}let n;try{n=decodeURIComponent((e.url??"/").split("?")[0])}catch{t.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),t.end("Bad request");return}let o=ge.resolve(r),i=ge.resolve(o,"."+(n==="/"?"/index.html":n));if(i!==o&&!i.startsWith(o+ge.sep)){t.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),t.end("Forbidden");return}let s=ge.join(o,"index.html"),a=fe.existsSync(i)&&fe.statSync(i).isFile()?i:s;if(!fe.existsSync(a)){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("Not found");return}let c=fe.createReadStream(a);c.on("error",()=>{t.headersSent||t.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),t.end()}),t.writeHead(200,{"Content-Type":Ze(qe(a))}),c.pipe(t)}function Oi(e){return typeof e.corsOrigins=="function"?e.corsOrigins():e.corsOrigins}function Ii(e){e.writeHead(401,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Unauthorized")}function cl(e,t){let r=e.url??"/",n=r.split("?")[0],o=!!(t.customRoutes&&n in t.customRoutes);return{url:r,pathname:n,isCustomRoute:o,isApi:o||r.startsWith(Zt)}}function ul(e,t,r,n){return e.method==="OPTIONS"&&r.isApi?(t.writeHead(204),t.end(),!0):r.isApi&&!ol.has(e.method??"GET")&&!Ai(e,n)?(we.warn(`ui-http cross-origin request refused: ${e.method} ${r.pathname} from ${$e(e.headers.origin)}`),A(t,403,"cross-origin","Cross-origin request refused"),!0):!1}async function ll(e,t,r,n,o){if(!(o.has(n.pathname)||await r.authorize(e))){we.warn(`ui-http auth rejected (custom route): ${e.method} ${n.url}`),Ii(t);return}try{await r.customRoutes[n.pathname](e,t)}catch(s){we.error(`Custom route ${n.url} error:`,s.message),A(t,500,"internal","Internal server error")}}async function dl(e,t,r,n,o){if(!await n(e)){we.warn(`ui-http auth rejected: ${e.method} ${o}`),Ii(t);return}r()}function fl(e){let t=new Set(e.publicRoutes??[]);return async(r,n,o)=>{let i=Oi(e);il(r,n,i);let s=cl(r,e);if(!ul(r,n,s,i)){if(s.isCustomRoute)return ll(r,n,e,s,t);if(s.isApi)return dl(r,n,o,e.authorize,s.url);al(r,n,e.spaDir)}}}function pl(e,t,r,n,o){if(!Ti(e,n.getToken,n.matchDeviceToken)){we.warn(`forward auth rejected: ${e.url}`),t.write(`HTTP/1.1 401 Unauthorized\r
|
|
20
|
+
\r
|
|
21
|
+
`),t.destroy();return}o.handleUpgrade(e,t,r)}function ml(e,t,r,n,o){if(!Ai(e,Oi(n))){we.warn(`ui-http cross-origin upgrade refused: ${(e.url??"").split("?")[0]} from ${$e(e.headers.origin)}`),t.write(`HTTP/1.1 403 Forbidden\r
|
|
22
|
+
\r
|
|
23
|
+
`),t.destroy();return}o.handleUpgrade(e,t,r)}function er(e){let t=ii({router:e.router,basePath:Zt,createContext:({req:s})=>e.createContext?.(s)??{},maxBodySize:nl,middleware:fl(e)}),r=e.portForward===!1?null:fi(),n=e.upgradeRoutes??{};return{handleRequest:t,handleUpgrade:(s,a,c)=>{let u=(s.url??"").split("?")[0];if(r&&u===li)pl(s,a,c,e,r);else if(Object.hasOwn(n,u))ml(s,a,c,e,n[u]);else return!1;return!0},close:()=>{r?.close();for(let s of Object.values(n))s.close()}}}function Pi(e){let t=e.host??"127.0.0.1",r=er(e),n=_i.createServer(r.handleRequest);return n.on("upgrade",(i,s,a)=>{r.handleUpgrade(i,s,a)||s.destroy()}),n.listen(e.port,t,()=>{let i=n.address(),s=i&&typeof i!="string"?i.port:e.port;we.info(`Listening on ${t}:${s}${Zt}`)}),{server:n,close:()=>new Promise(i=>{r.close(),n.closeAllConnections?.(),n.close(()=>i())})}}var tr=N("ui-http"),rr="/api/ui/pair",yl="/api/ui/pairing-code",hl="/api/ui/devices",gl="/api/ui/devices/revoke";function wl(e){let t=e.headers[ke];return Array.isArray(t)?t[0]:t}function El(e,t){return async(r,n)=>{if(r.method!=="POST")return V(n,"POST");let o=await ae(r,n);if(!o)return;let i=typeof o.code=="string"?o.code:"";if(!t.redeem(i))return await new Promise(c=>setTimeout(c,Xt)),tr.warn("app pairing rejected: wrong or expired code"),A(n,401,"invalid-code","Invalid or expired pairing code");let{device:s,token:a}=e.issue(typeof o.name=="string"?o.name:"");tr.info(`app paired: ${s.name} (${s.id})`),x(n,200,{ok:!0,data:{token:a,device:s}})}}function Sl(e){return async(t,r)=>{if(t.method!=="POST")return V(r,"POST");x(r,200,{ok:!0,data:e.create()},{"Cache-Control":"no-store"})}}function vl(e){return async(t,r)=>{if(t.method!=="GET")return V(r,"GET");let n=e.devices.match(wl(t))?.id,o=e.devices.list().map(i=>({...i,current:i.id===n}));x(r,200,{ok:!0,data:{devices:o,pairing:!!e.pairing}},{"Cache-Control":"no-store"})}}function bl(e){return async(t,r)=>{if(t.method!=="POST")return V(r,"POST");let n=await ae(t,r);if(!n)return;let o=typeof n.id=="string"?n.id:"";if(!e.revoke(o))return A(r,404,"not-found","No such device");tr.info(`paired app revoked: ${o}`),x(r,200,{ok:!0})}}function Ci(e){return{...e.pairing?{[rr]:El(e.devices,e.pairing),[yl]:Sl(e.pairing)}:{},[hl]:vl(e),[gl]:bl(e.devices)}}import*as Ke from"crypto";import{mkdirSync as _l,readFileSync as Tl,renameSync as Rl,writeFileSync as Al}from"fs";import*as Ni from"path";var Ol=N("ui-http"),Il=600*1e3,Pl=60,Cl="App";function xi(e){return Ke.createHash("sha256").update(e).digest("hex")}function xl(e){return e.trim().slice(0,Pl)||Cl}function Nl(e){let t=e;return typeof t?.id=="string"&&typeof t.name=="string"&&typeof t.tokenHash=="string"&&typeof t.createdAt=="number"&&typeof t.lastSeenAt=="number"}function Dl(e){if(!e)return[];try{let t=JSON.parse(Tl(e,"utf8"));return Array.isArray(t?.devices)?t.devices.filter(Nl):[]}catch{return[]}}function nr(e){return{id:e.id,name:e.name,createdAt:e.createdAt,lastSeenAt:e.lastSeenAt}}function Di(e={}){let t=e.now??(()=>Date.now()),r=Dl(e.file),n=new Map(r.map(s=>[s.id,s.lastSeenAt])),o=()=>{if(e.file)try{_l(Ni.dirname(e.file),{recursive:!0});let s=`${e.file}.tmp`;Al(s,JSON.stringify({devices:r}),{mode:384}),Rl(s,e.file);for(let a of r)n.set(a.id,a.lastSeenAt)}catch(s){Ol.warn(`could not persist paired devices: ${s.message}`)}},i=s=>{let a=xi(s),c;for(let u of r)Z(u.tokenHash,a)&&(c=u);return c};return{issue(s){let a=t(),c=Ke.randomBytes(32).toString("hex"),u={id:Ke.randomBytes(6).toString("hex"),name:xl(s),createdAt:a,lastSeenAt:a,tokenHash:xi(c)};return r.push(u),o(),{device:nr(u),token:c}},match(s){if(!s)return;let a=i(s);if(a)return a.lastSeenAt=t(),a.lastSeenAt-(n.get(a.id)??0)>=Il&&o(),nr(a)},list(){return r.map(nr)},revoke(s){let a=r.findIndex(c=>c.id===s);return a<0?!1:(r.splice(a,1),n.delete(s),o(),!0)}}}import*as q from"node:fs";import*as ut from"node:path";import*as lt from"node:crypto";import*as Mi from"node:zlib";var Ul=67324752,kl=33639248,Ll=101010256,Ui=8,or=20,ki=33,Li=0,Ml=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();function jl(e){let t=4294967295;for(let r=0;r<e.length;r++)t=Ml[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function ji(e){let t=[...e].sort((c,u)=>c.name<u.name?-1:c.name>u.name?1:0),r=[],n=[],o=0;for(let c of t){let u=Buffer.from(c.name,"utf8"),l=jl(c.data),p=Mi.deflateRawSync(c.data),m=c.data.length,y=p.length,d=Buffer.alloc(30);d.writeUInt32LE(Ul,0),d.writeUInt16LE(or,4),d.writeUInt16LE(0,6),d.writeUInt16LE(Ui,8),d.writeUInt16LE(Li,10),d.writeUInt16LE(ki,12),d.writeUInt32LE(l,14),d.writeUInt32LE(y,18),d.writeUInt32LE(m,22),d.writeUInt16LE(u.length,26),d.writeUInt16LE(0,28),r.push(d,u,p);let f=Buffer.alloc(46);f.writeUInt32LE(kl,0),f.writeUInt16LE(or,4),f.writeUInt16LE(or,6),f.writeUInt16LE(0,8),f.writeUInt16LE(Ui,10),f.writeUInt16LE(Li,12),f.writeUInt16LE(ki,14),f.writeUInt32LE(l,16),f.writeUInt32LE(y,20),f.writeUInt32LE(m,24),f.writeUInt16LE(u.length,28),f.writeUInt16LE(0,30),f.writeUInt16LE(0,32),f.writeUInt16LE(0,34),f.writeUInt16LE(0,36),f.writeUInt32LE(0,38),f.writeUInt32LE(o,42),n.push(f,u),o+=d.length+u.length+p.length}let i=Buffer.concat(r),s=Buffer.concat(n),a=Buffer.alloc(22);return a.writeUInt32LE(Ll,0),a.writeUInt16LE(0,4),a.writeUInt16LE(0,6),a.writeUInt16LE(t.length,8),a.writeUInt16LE(t.length,10),a.writeUInt32LE(s.length,12),a.writeUInt32LE(i.length,16),a.writeUInt16LE(0,20),Buffer.concat([i,s,a])}var Hi=N("ui-ota"),Hl="/api/ui-ota/manifest.json",Ji="/api/ui-ota/bundle.zip";function Fl(e){let t=[],r=(n,o)=>{for(let i of q.readdirSync(n,{withFileTypes:!0})){let s=ut.join(n,i.name),a=o?`${o}/${i.name}`:i.name;i.isDirectory()?r(s,a):i.isFile()&&!i.name.endsWith(".map")&&t.push({name:a,data:q.readFileSync(s)})}};return r(e,""),t.sort((n,o)=>n.name<o.name?-1:n.name>o.name?1:0),t}function Jl(e){let t=lt.createHash("sha256");for(let r of e)t.update(r.name),t.update("\0"),t.update(lt.createHash("sha256").update(r.data).digest("hex")),t.update("\0");return t.digest("hex")}function Wl(e){let t=Fl(e),r=ji(t),n=lt.createHash("sha256").update(r).digest("hex"),o=Jl(t);return{zip:r,manifest:{version:o,sha256:n,size:r.length,url:`${Ji}?v=${o}`}}}var Bl=2e3;function Fi(e){let t=0,r=0,n=0,o=i=>{n=Math.max(n,q.statSync(i).mtimeMs);for(let s of q.readdirSync(i,{withFileTypes:!0})){let a=ut.join(i,s.name);if(s.isDirectory())o(a);else if(s.isFile()){let c=q.statSync(a);t+=1,r+=c.size,n=Math.max(n,c.mtimeMs)}}};try{o(e)}catch{n=Date.now()}return{key:`${t}:${r}:${n}`,newestMs:n,hasIndex:q.existsSync(ut.join(e,"index.html"))}}function Wi(e){if(!e||!q.existsSync(e))return{};let t,r=()=>{let i=Fi(e);if(t&&(t.key===i.key||!i.hasIndex||Date.now()-i.newestMs<Bl))return t.bundle;let s=Wl(e);return t={key:Fi(e).key===i.key?i.key:null,bundle:s},s},n=async(i,s)=>{if(i.method!=="GET"&&i.method!=="HEAD"){he(s,405,{ok:!1,code:"method-not-allowed",message:"Use GET"});return}let a=r().manifest;Hi.info(`manifest served: version=${a.version.slice(0,12)} size=${a.size} method=${i.method}`),he(s,200,a)},o=async(i,s)=>{if(i.method!=="GET"&&i.method!=="HEAD"){he(s,405,{ok:!1,code:"method-not-allowed",message:"Use GET"});return}let{zip:a}=r();Hi.info(`bundle served: size=${a.length} method=${i.method}`),s.writeHead(200,{"Content-Type":"application/zip","Content-Length":String(a.length),"Cache-Control":"no-store"}),s.end(i.method==="HEAD"?void 0:a)};return{[Hl]:n,[Ji]:o}}var Bi=N("app-update"),$l="/api/app-update/manifest.json",Kl="fangxm233",zl="cortex-agent",Vl=`https://api.github.com/repos/${Kl}/${zl}/releases?per_page=100`,Gl=360*60*1e3,Yl=8e3,Ql=/^Cortex-(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)-(Linux|Windows|macOS|Android)-([A-Za-z0-9_]+?)(?:-setup)?\.(AppImage|deb|rpm|exe|dmg|apk)$/,Xl={AppImage:"appimage",deb:"deb",rpm:"rpm",exe:"nsis",dmg:"dmg",apk:"apk"},ql={amd64:"x86_64",arm64:"aarch64"};function Zl(e){let t=Ql.exec(e);if(!t)return null;let[,r,n,o,i]=t;return{version:r,os:n.toLowerCase(),arch:ql[o]??o,kind:Xl[i]}}function ed(e){if(!e)return null;let t=/^sha256:([0-9a-fA-F]{64})$/.exec(e);return t?t[1].toLowerCase():null}function td(e){let t=/^server-v(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)$/.exec(e);return t?t[1]:null}function rd(e){let t=[];for(let r of e.assets){let n=Zl(r.name),o=ed(r.digest);!n||!o||t.push({name:r.name,os:n.os,arch:n.arch,kind:n.kind,url:r.browser_download_url,size:r.size,sha256:o})}return t}function nd(e,t){let r=null;for(let n of e){let o=td(n.tag_name);if(!o||vt(o,t)>0)continue;let i=rd(n);i.length!==0&&(!r||vt(o,r.version)>0)&&(r={version:o,release:n,assets:i})}return r?{version:r.version,releaseUrl:r.release.html_url,publishedAt:r.release.published_at,notes:(r.release.body??"").slice(0,Yl),assets:r.assets}:null}async function od(){let e=await fetch(Vl,{headers:{Accept:"application/vnd.github+json","User-Agent":"cortex-agent"}});if(!e.ok)throw new Error(`GitHub releases API ${e.status}`);return await e.json()}function $i(e={}){let t=e.serverVersion??ns,r=e.devMode??!1,n=e.fetchReleases??od,o=e.ttlMs??Gl,i=e.now??Date.now,s=null,a=null,c=async()=>{if(r)return null;if(a!==null&&i()-a<o)return s;a=i();try{s=nd(await n(),t)}catch(l){Bi.warn(`release fetch failed: ${l.message}`)}return s},u=async(l,p)=>{if(l.method!=="GET"&&l.method!=="HEAD"){he(p,405,{ok:!1,code:"method-not-allowed",message:"Use GET"});return}let m=await c();m&&Bi.info(`manifest served: version=${m.version} assets=${m.assets.length}`),he(p,200,m??{})};return{[$l]:u}}var sd=N("device-ports"),id="/api/forward/devices",ad="/api/forward/device-ports",cd="/api/forward/device-port",ud="/api/forward/device-port/close";async function ld(e,t){let r=e.listDevices().find(i=>i.device===t)?.platform??"",{ports:n,error:o}=await at(r,i=>e.runOnDevice(t,i));return o&&sd.warn(`port discovery on ${t} unavailable: ${o}`),n}async function Ki(e,t){if(e.method!=="POST")return V(t,"POST"),null;let r=await ae(e,t);if(!r)return null;let n=typeof r.device=="string"?r.device:"",o=Number(r.port);return n?!Number.isInteger(o)||o<1024||o>65535?(A(t,400,"bad-port","port must be an integer in 1024..65535"),null):{device:n,port:o}:(A(t,400,"missing-device","device is required"),null)}function zi(e){let t=new Map,r=(n,o)=>`${n}\0${o}`;return{[id]:async(n,o)=>{let i=e.listDevices().map(s=>({device:s.device,platform:s.platform}));x(o,200,{ok:!0,data:{devices:i}})},[ad]:async(n,o)=>{let i=new URL(n.url??"","http://localhost").searchParams.get("device");if(!i)return A(o,400,"missing-device","device is required");x(o,200,{ok:!0,data:{ports:await ld(e,i)}})},[cd]:async(n,o)=>{let i=await Ki(n,o);if(!i)return;let s=r(i.device,i.port),a=e.listDevicePorts().some(u=>u.device===i.device&&u.remotePort===i.port),c;try{c=await e.openDevicePort(i.device,i.port)}catch(u){return A(o,500,"open-failed",u.message)}t.has(s)?t.set(s,t.get(s)+1):a||t.set(s,1),x(o,200,{ok:!0,data:c})},[ud]:async(n,o)=>{let i=await Ki(n,o);if(!i)return;let s=r(i.device,i.port),a=t.get(s)??0;a>1?t.set(s,a-1):t.delete(s);let c=a===1&&e.closeDevicePort(i.device,i.port);x(o,200,{ok:!0,data:{closed:c}})}}}import*as ce from"node:path";import*as ue from"node:fs";var dd="/api/attachments/upload",fd="/api/files/download",pd="/api/boards/asset",md=100*1024*1024,yd=/^[A-Za-z0-9_-]{1,128}$/,hd=new Set(["text/html","application/xhtml+xml","image/svg+xml","application/xml"]),gd="sandbox allow-scripts";function sr(e,t){let r=e.headers[t];return(Array.isArray(r)?r[0]:r)?.trim()||void 0}function wd(e){try{return decodeURIComponent(e)}catch{return e}}function Ed(e){return e.startsWith("image/")?"image":e.startsWith("video/")?"video":"file"}async function Sd(e,t,r){let n;try{n=await ue.promises.open(t,"wx")}catch(i){return e.resume(),{kind:"failed",error:i}}let o=n.createWriteStream();return new Promise(i=>{let s=0,a=!1,c=p=>{if(!a){if(a=!0,e.off("data",u),e.off("end",l),p.kind==="stored")return i(p);o.destroy(),e.resume(),ue.promises.unlink(t).catch(()=>{}).then(()=>i(p))}},u=p=>{if(s+=p.length,s>r)return c({kind:"too-large"});o.write(p)||(e.pause(),o.once("drain",()=>{a||e.resume()}))},l=()=>{o.end()};e.on("data",u),e.on("end",l),e.on("error",p=>c({kind:"failed",error:p})),e.on("close",()=>{e.complete||c({kind:"failed",error:new Error("upload aborted")})}),o.on("error",p=>c({kind:"failed",error:p})),o.on("finish",()=>c({kind:"stored",size:s}))})}async function Vi(e,t,r){let n;try{let a=await ue.promises.stat(t);if(!a.isFile())throw new Error("not a file");n=a.size}catch{A(e,404,"not-found","File not found");return}let o=qe(t),i=ce.basename(t);e.writeHead(200,{"Content-Type":Ze(o),"Content-Length":String(n),"Content-Disposition":`${r}; filename="${i.replace(/"/g,"")}"`,"Cache-Control":"private, max-age=3600","X-Content-Type-Options":"nosniff",...hd.has(o)?{"Content-Security-Policy":gd}:{}});let s=ue.createReadStream(t);s.on("error",()=>{e.headersSent||e.writeHead(500),e.end()}),s.pipe(e)}function Gi(e,t){try{return new URL(e.url??"","http://localhost").searchParams}catch{return A(t,400,"bad-request","Malformed URL"),null}}function Yi(e){let t=e.maxUploadBytes??md,r=(s,a)=>Kt(s,a,413,"too-large",`File exceeds ${t/1024/1024}MB limit`,t),n=async(s,a)=>{if(s.method!=="POST")return V(a,"POST");let c=sr(s,"x-session-id"),u=sr(s,"x-file-name"),l=(sr(s,"content-type")??"application/octet-stream").split(";")[0].trim();if(!c)return A(a,400,"missing-session","X-Session-Id header required");if(!u)return A(a,400,"missing-name","X-File-Name header required");let p=ce.resolve(e.attachmentsDir),m=ce.resolve(p,c);if(!yd.test(c)||ce.dirname(m)!==p)return A(a,400,"bad-session","X-Session-Id is not a session id");if(($t(s)??0)>t)return r(s,a);let y=ss(wd(u));await ue.promises.mkdir(m,{recursive:!0});let{destPath:d,finalName:f}=await as(m,is(y)),w=await Sd(s,d,t);if(w.kind==="too-large")return r(s,a);if(w.kind==="failed")return A(a,500,"upload-failed",w.error.message);x(a,200,{ok:!0,data:{name:y,path:`workspace/attachments/${c}/${f}`,size:w.size,mimeType:l,type:Ed(l)}})},o=async(s,a)=>{let c=Gi(s,a);if(!c)return;let u=(c.get("path")??"").trim(),l=c.get("disposition")==="inline"?"inline":"attachment";if(!u)return A(a,400,"missing-path","path query param required");let p=e.resolveWorkspaceRelPath(u);if(!p)return A(a,403,"forbidden","Path escapes the workspace root");await Vi(a,p,l)},i=async(s,a)=>{let c=Gi(s,a);if(!c)return;let u=(c.get("projectId")??"").trim(),l=(c.get("path")??"").trim(),p=c.get("disposition")==="attachment"?"attachment":"inline";if(!u||!l)return A(a,400,"missing-params","projectId and path query params required");if(!l.startsWith("boards/"))return A(a,403,"forbidden","path must be under boards/");let m=e.projectContextDir(u),y;try{if(!m)throw new Error("unknown project");let d=ue.realpathSync(ce.join(m,"boards"));y=e.resolveMemoryFilePath(d,l.slice(7))}catch{return A(a,404,"not-found","File not found")}await Vi(a,y,p)};return{[dd]:n,[fd]:o,[pd]:i}}import*as ea from"crypto";var Ee=N("browser-stream"),vd="/api/browser/sessions",bd="/api/browser/stream-ticket",ta="/api/browser/stream",_d="/api/browser/takeover",Td="/api/browser/insert-text",ir=4004,Qi=4010,Rd=3e4,Ad=256,Od=32,Id=10,Pd=15,Cd=16*1024,Xi=4e3,xd=4*1024*1024,Nd=5e3,Dd=3e4,Ud=10*6e4,qi="cortex_takeover",kd=/^[A-Za-z0-9_-]{1,64}$/,Ld=new Set(["input_mouse","input_keyboard","input_touch"]);function Md(e,t){let r;try{r=JSON.parse(e)}catch{return null}if(!r||typeof r!="object")return null;let n=r.type;if(n==="ack"){let o=r.seq;return typeof o=="number"&&Number.isFinite(o)?{message:JSON.stringify({type:"ack",seq:o}),input:!1}:null}return typeof n=="string"&&Ld.has(n)&&t?{message:e,input:!0}:null}function Zi(e){return e==null||e===""?"":typeof e=="string"&&kd.test(e)?e:null}function jd(e){let t=Number(e);return!e||!Number.isFinite(t)||t<=0?Id:Math.min(Pd,Math.max(1,Math.round(t)))}function Hd(e){let t;try{t=new URL(e,"http://localhost")}catch{return null}let r=t.searchParams.get("session")??"",n=t.searchParams.get("ticket")??"";return!r||!n?null:{sessionId:r,ticket:n,fps:jd(t.searchParams.get("maxFps"))}}function Fd(e=Date.now){let t=new Map,r=()=>{let n=e();for(let[o,i]of t)i.expiresAt<=n&&t.delete(o)};return{mint(n,o=""){for(r();t.size>=Ad;)t.delete(t.keys().next().value);let i=ea.randomBytes(32).toString("hex");return t.set(i,{sessionId:n,client:o,expiresAt:e()+Rd}),i},redeem(n,o){r();let i=null;for(let a of t.keys())Z(a,n)&&(i=a);if(i===null)return null;let s=t.get(i);return t.delete(i),s.sessionId===o?{client:s.client}:null},size:()=>(r(),t.size)}}function Jd(e){let t=new Map,r=s=>{s.grace&&clearTimeout(s.grace),s.idle&&clearTimeout(s.idle),s.grace=null,s.idle=null},n=(s,a,c)=>{t.get(s)===a&&(r(a),t.delete(s),e.isTakenOver(s)&&e.release(s,c))},o=(s,a)=>{let c=Math.max(0,a.lastInputAt+e.idleMs-e.now());a.idle=setTimeout(()=>{a.idle=null,e.now()-a.lastInputAt>=e.idleMs?n(s,a,"idle"):o(s,a)},c),a.idle.unref?.()},i=(s,a)=>{a.grace||(a.grace=setTimeout(()=>{a.grace=null,n(s,a,"disconnected")},e.graceMs),a.grace.unref?.())};return{begin(s,a){let c=t.get(s);c&&r(c);let u={client:a,lastInputAt:e.now(),grace:null,idle:null};t.set(s,u),o(s,u),e.hasClient(s,a)||i(s,u)},end(s){let a=t.get(s);a&&(r(a),t.delete(s))},holder:s=>t.get(s)?.client??null,connected(s,a){let c=t.get(s);c?.client===a&&c.grace&&(clearTimeout(c.grace),c.grace=null)},disconnected(s,a){let c=t.get(s);c?.client===a&&!e.hasClient(s,a)&&i(s,c)},input(s){let a=t.get(s);a&&(a.lastInputAt=e.now())},close(){for(let s of t.values())r(s);t.clear()}}}function Wd(e){return{sessionId:e.sessionId,device:e.device,state:e.state,...e.error?{error:e.error}:{},...e.url?{url:e.url}:{},...e.title?{title:e.title}:{},takenOver:e.takenOver,lastUsedAt:e.lastUsedAt}}async function ar(e,t,r){if(e.method!=="POST")return V(t,"POST"),null;let n=await ae(e,t);if(!n)return null;let o=typeof n.session=="string"?n.session:"";return o?r.listSessions().some(i=>i.sessionId===o)?{sessionId:o,body:n}:(A(t,404,"no-browser","This session has no browser"),null):(A(t,400,"missing-session","session is required"),null)}function ra(e,t={}){let r=e.now??Date.now,n=Fd(r),o=new et.default({noServer:!0,maxPayload:Cd}),i=new Set,s=d=>[...i].filter(f=>f.sessionId===d),a=d=>d.client!==""&&e.isTakenOver(d.sessionId)&&u.holder(d.sessionId)===d.client,c=d=>{for(let f of s(d))f.ws.readyState===ne.default.OPEN&&f.ws.send(JSON.stringify({type:qi,takenOver:e.isTakenOver(d),mine:a(f)}))},u=Jd({isTakenOver:e.isTakenOver,hasClient:(d,f)=>f!==""&&s(d).some(w=>w.client===f),now:r,graceMs:t.graceMs??Dd,idleMs:t.idleMs??Ud,release:(d,f)=>{(async()=>{try{await e.setTakeover(d,!1)}catch(w){Ee.warn(`could not hand ${d} back: ${w.message}`);return}Ee.info(`browser handed back automatically (${f==="idle"?"no input":"window gone"}): ${d}`),c(d)})()}}),l={[vd]:async(d,f)=>{if(d.method!=="GET")return V(f,"GET");x(f,200,{ok:!0,data:{sessions:e.listSessions().map(Wd)}},{"Cache-Control":"no-store"})},[bd]:async(d,f)=>{let w=await ar(d,f,e);if(!w)return;let b=Zi(w.body.client);if(b===null)return A(f,400,"bad-client","client must be 1-64 letters, digits, _ or -");x(f,200,{ok:!0,data:{ticket:n.mint(w.sessionId,b)}},{"Cache-Control":"no-store"})},[_d]:async(d,f)=>{let w=await ar(d,f,e);if(!w)return;let b=w.body.on;if(typeof b!="boolean")return A(f,400,"bad-on","on must be a boolean");let g=Zi(w.body.client);if(g===null||b&&g==="")return A(f,400,"bad-client","client must be 1-64 letters, digits, _ or -");await e.setTakeover(w.sessionId,b),b?u.begin(w.sessionId,g):u.end(w.sessionId),Ee.info(`browser ${b?"taken over":"handed back"}: ${w.sessionId}`),c(w.sessionId),x(f,200,{ok:!0,data:{takenOver:e.isTakenOver(w.sessionId)}})},[Td]:async(d,f)=>{let w=await ar(d,f,e);if(!w)return;let b=typeof w.body.text=="string"?w.body.text:"";if(!b)return A(f,400,"missing-text","text is required");if(b.length>Xi)return A(f,400,"text-too-long",`text exceeds ${Xi} characters`);if(!e.isTakenOver(w.sessionId))return A(f,409,"not-taken-over","Take over the browser first");u.input(w.sessionId);try{await e.insertText(w.sessionId,b)}catch(g){return A(f,502,"insert-failed",g.message)}x(f,200,{ok:!0,data:{}})}},p=async(d,f)=>{let{ws:w}=d,b=null;try{b=await e.streamPort(f.sessionId)}catch(E){Ee.warn(`stream port lookup failed for ${f.sessionId}: ${E.message}`)}if(w.readyState!==ne.default.OPEN)return;if(b===null){w.close(ir,"no stream");return}let g=new ne.default(`ws://127.0.0.1:${b}/?maxFps=${f.fps}&pacing=ack`,{handshakeTimeout:Nd}),v=!1,T=(E,P)=>{(g.readyState===ne.default.OPEN||g.readyState===ne.default.CONNECTING)&&g.terminate(),w.readyState===ne.default.OPEN&&w.close(E,P)};g.on("open",()=>{v=!0}),g.on("message",(E,P)=>{w.readyState===ne.default.OPEN&&(w.bufferedAmount>xd||w.send(E,{binary:P}))}),g.on("close",()=>T(v?Qi:ir,v?"stream ended":"no stream")),g.on("error",E=>{Ee.warn(`upstream stream error for ${f.sessionId}: ${E.message}`),T(v?Qi:ir,v?"stream ended":"no stream")}),w.on("message",(E,P)=>{if(P||g.readyState!==ne.default.OPEN)return;let L=Md(E.toString(),a(d));L&&(L.input&&u.input(f.sessionId),g.send(L.message))}),w.on("close",()=>T(1e3,"viewer closed"))};return{routes:l,handleUpgrade:(d,f,w)=>{let b=Hd(d.url??""),g=b?n.redeem(b.ticket,b.sessionId):null;if(!b||!g){Ee.warn("browser stream refused: missing or invalid ticket"),f.write(`HTTP/1.1 401 Unauthorized\r
|
|
24
|
+
Connection: close\r
|
|
25
|
+
\r
|
|
26
|
+
`),f.destroy();return}if(i.size>=Od){Ee.warn(`browser stream refused (${i.size} already open)`),f.write(`HTTP/1.1 503 Service Unavailable\r
|
|
27
|
+
Connection: close\r
|
|
28
|
+
\r
|
|
29
|
+
`),f.destroy();return}o.handleUpgrade(d,f,w,v=>{let T={ws:v,sessionId:b.sessionId,client:g.client};i.add(T),u.connected(T.sessionId,T.client),v.on("close",()=>{i.delete(T),u.disconnected(T.sessionId,T.client)}),v.on("error",()=>v.terminate()),v.send(JSON.stringify({type:qi,takenOver:e.isTakenOver(T.sessionId),mine:a(T)})),p(T,b)})},close:()=>{u.close();for(let d of i)d.ws.terminate();i.clear(),o.close()}}}var dt=new TextEncoder,ft=new TextDecoder,pt=new TextDecoder("utf-8",{fatal:!0}),Am=2**32;function na(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}var Bd=/[^\x00-\x7f]/;function Ce(e){if(typeof e=="string"&&e.length>=128){if(Bd.test(e))throw new TypeError("non-ASCII string encountered in encode()");return dt.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function oa(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o);return n}var $=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},le=class extends ${static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},ze=class extends ${static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},mt=class extends ${static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},ee=class extends ${static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var J=class extends ${static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Se=class extends ${static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var xe=class extends ${static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Ne=class extends ${static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},yt=class extends ${[Symbol.asyncIterator]=async function*(){};static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}},ht=class extends ${static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(t="request timed out",r){super(t,r)}},Ve=class extends ${static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};var $d="The input to be decoded is not correctly encoded.";function Ge(e){try{return oa(typeof e=="string"?e:ft.decode(e),!0)}catch(t){throw new TypeError($d,{cause:t})}}function pe(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function gt(e){return pe(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(pe)}function sa(...e){let t=new Set;for(let r of e)if(r)for(let n of Object.keys(r)){if(t.has(n))return!1;t.add(n)}return!0}function cr(e,t,r){try{return Ge(e)}catch(n){throw new r(`Failed to base64url decode the ${t}`,{cause:n})}}function ia(e,t,r){try{return Ce(e)}catch(n){throw new r(`The ${t} is not a valid base64url string`,{cause:n})}}function aa(e,t,r){let n;try{n=JSON.parse(pt.decode(Ge(e)))}catch(o){throw new t(r,{cause:o})}if(!pe(n))throw new t(r);return n}var ca={__proto__:null,b64:!0};function ua(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function la(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return[];if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?t:{__proto__:null,...r,...t};for(let s of n.crit){if(!(s in i))throw new ee(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(o,s)||o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(n,s)||n[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return n.crit}function da(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new J('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}var Kd=e=>e[Symbol.toStringTag],zd=(e,t,r)=>{let{alg:n}=e;if(t.use!==void 0){let o=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==o)throw new TypeError(`Invalid key for this operation, its "use" must be "${o}" when present`)}if(t.alg!==void 0&&t.alg!==n)throw new TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){let o=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(o&&!t.key_ops.includes(o))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}};async function pa(e,t,r){let{alg:n,secret:o}=e,i=r==="decrypt"||r==="sign";if(o&&t instanceof Uint8Array)return t;let s,a;if(pe(t)){if(s=Zd(t),typeof s.kty!="string")throw fa(n,t,o);if(!(o?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(o?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(zd(e,s,r),s.kty==="oct")return Ge(s.k);if(!Object.isFrozen(t)){let{key_ops:l}=t;Array.isArray(l)&&Object.freeze(l),Object.freeze(t)}}else{if(!Yd(t))throw fa(n,t,o);let l=o?"secret":i?"private":"public";if(t.type!==l&&(o||["secret","public","private"].includes(t.type)))throw new TypeError(`${Kd(t)} instances must be of type "${l}" for the ${n} algorithm`);if(ma(t))return t;if(a=t,a.type==="secret")return a.export()}ur||=new WeakMap;let c=t,u=ur.get(c);if(u?.[n])return u[n];if(u||ur.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",p=Vd[a.asymmetricKeyDetails?.namedCurve],m=e.resolve?.({crv:p,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return u[n]=a.toCryptoKey(m,l,e.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=n,u[n]=await dr(e,s)}var ur,Vd={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};var ma=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Gd=e=>e?.[Symbol.toStringTag]==="KeyObject",Yd=e=>ma(e)||Gd(e);function Qd(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function fa(e,t,r){let n=["CryptoKey","KeyObject","JSON Web Key"];return r&&n.push("Uint8Array"),new TypeError(Qd(`Key for the ${e} algorithm must be `,t,...n))}var wt=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Xd(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ya(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function qd(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw wt(t.name);if(t.hash&&n.hash?.name!==t.hash)throw wt(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw wt(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw wt(t.length,"algorithm.length");Xd(e,r)}function lr(e){return{__proto__:null,...e}}function Zd(e){let t=lr(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,n=Array.isArray(r)?[...r]:void 0;if(!n||n.some(o=>typeof o!="string")||new Set(n).size!==n.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=n}return t}async function dr(e,t,r){if(!e.kty.includes(t.kty))throw new ee('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,o=!!(t.d||t.priv),i={...t,ext:r??t.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,n,i.ext??!o,t.key_ops??e.usages[o?1:0])}async function ha(e,t,r,n=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,n,[r])),qd(e,t,r),e}function ga(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var Ye=[["verify"],["sign"]];function fr(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:Ye}}function De(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:Ye,minRsaBits:2048}}function pr(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:Ye}}function wa(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:Ye}}function mr(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:Ye}}var yr=ga({HS256:fr(256),HS384:fr(384),HS512:fr(512),RS256:De(256),RS384:De(384),RS512:De(512),PS256:De(256,32),PS384:De(384,48),PS512:De(512,64),ES256:pr("P-256",256),ES384:pr("P-384",384),ES512:pr("P-521",512),EdDSA:wa(),Ed25519:wa(),"ML-DSA-44":mr(44),"ML-DSA-65":mr(65),"ML-DSA-87":mr(87)});function Ea(e){let t=typeof e=="string"?yr[e]:void 0;if(!t)throw new ee(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function Sa(e){return[e&&ua("algorithms",e.algorithms),e?.crit]}function ef(e){return e===void 0?{}:aa(e,J,"JWS Protected Header is invalid")}function tf(e){try{return Ce(e)}catch(t){throw new J("JWS Compact Serialization payload must use only ASCII characters",{cause:t})}}async function rf(e,t,r,n,o){let{protected:i,header:s,payload:a}=e,c=o??ef(i);if(!sa(c,s))throw new J("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=da(c,la(J,ca,t[1],c,u)),{alg:p}=u;if(typeof p!="string"||!p)throw new J('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(t[0]&&!t[0].has(p))throw new mt('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new J("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new J("JWS Payload must be a string or an Uint8Array instance");let m=l||typeof a!="string"?a:n(a),y=!1;typeof r=="function"&&(r=await r(c,e),y=!0);let d=Ea(p),f=na(i!==void 0?Ce(i):new Uint8Array,Ce("."),typeof m=="string"?t[2]??=ia(m,"payload",J):m),w=cr(e.signature,"signature",J),b=await pa(d,r,"verify"),g=await ha(b,d.subtle,"verify");d.minRsaBits&&ya(d.alg,g);let v=!1;try{v=await crypto.subtle.verify(d.signing,g,w,f)}catch(E){throw new Ve(void 0,{cause:E})}if(!v)throw new Ve;let T={payload:typeof m=="string"?cr(m,"payload",J):m};return i!==void 0&&(T.protectedHeader=c),s!==void 0&&(T.unprotectedHeader=s),y?[{...T,key:b},l]:[T,l]}async function va(e,t,r){if(e instanceof Uint8Array&&(e=ft.decode(e)),typeof e!="string")throw new J("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new J("Invalid Compact JWS");return rf({payload:o,protected:n,signature:i},t,r,tf)}var nf=e=>Math.floor(e.getTime()/1e3),of={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},sf=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ue="check_failed";function hr(){throw new TypeError("Invalid time period format")}function ba(e){typeof e!="string"&&hr();let t=sf.exec(e);(!t||t[4]&&t[1])&&hr();let r=parseFloat(t[2]),n=Math.round(r*of[t[3][0].toLowerCase()]);return Number.isFinite(n)||hr(),t[1]==="-"||t[4]==="ago"?-n:n}function gr(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var _a=e=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`},af=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(r=>e.includes(r)):!1;function wr(e,t,r=!1){let n=e[t];if(!(n===void 0&&!r)){if(typeof n!="number")throw new le(`"${t}" claim must be a number`,e,t,"invalid");return n}}function Er(e,t){throw new le(`unexpected "${t}" claim value`,e,t,Ue)}function Ta(e,t,r={}){let n;try{n=JSON.parse(pt.decode(t))}catch(g){throw new Se("JWT Claims Set must be a top-level JSON object",{cause:g})}if(!pe(n))throw new Se("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o!==void 0&&(typeof e.typ!="string"||_a(e.typ)!==_a(o)))throw new le('unexpected "typ" JWT header value',n,"typ",Ue);let{requiredClaims:i=[],issuer:s,subject:a,audience:c,maxTokenAge:u}=r,l=[...i];u!==void 0&&l.push("iat"),c!==void 0&&l.push("aud"),a!==void 0&&l.push("sub"),s!==void 0&&l.push("iss");for(let g of new Set(l.reverse()))if(!Object.hasOwn(n,g))throw new le(`missing required "${g}" claim`,n,g,"missing");s!==void 0&&!(Array.isArray(s)?s:[s]).includes(n.iss)&&Er(n,"iss"),a!==void 0&&n.sub!==a&&Er(n,"sub"),c!==void 0&&!af(n.aud,typeof c=="string"?[c]:c)&&Er(n,"aud");let{clockTolerance:p}=r,m=0;if(typeof p=="string")m=ba(p);else if(p!==void 0){if(typeof p!="number")throw new TypeError("Invalid clockTolerance option type");m=p}gr("clockTolerance option",m);let{currentDate:y}=r,d=gr("currentDate option",nf(y===void 0?new Date:y)),f=wr(n,"iat",u!==void 0),w=wr(n,"nbf");if(w!==void 0&&w>d+m)throw new le('"nbf" claim timestamp check failed',n,"nbf",Ue);let b=wr(n,"exp");if(b!==void 0&&b<=d-m)throw new ze('"exp" claim timestamp check failed',n,"exp",Ue);if(u!==void 0){let g=d-f,v=gr("maxTokenAge option",typeof u=="number"?u:ba(u));if(g-m>v)throw new ze('"iat" claim timestamp check failed (too far in the past)',n,"iat",Ue);if(g<-m)throw new le('"iat" claim timestamp check failed (it should be in the past)',n,"iat",Ue)}return n}async function Sr(e,t,r){let[n,o]=await va(e,Sa(r),t);if(!o)throw new Se("JWTs MUST NOT use unencoded payload");let i=Ta(n.protectedHeader,n.payload,r);return{...n,payload:i}}function cf(e,t,r,n){let{kty:o,key_ops:i,ext:s,kid:a,alg:c,use:u,crv:l}=e;return(s===void 0||typeof s=="boolean")&&(i===void 0||Array.isArray(i)&&i.every((p,m)=>typeof p=="string"&&i.indexOf(p)===m)&&i.includes("verify"))&&t.kty.includes(o)&&(n===void 0||typeof n=="string"&&n===a)&&(c===void 0?o!=="AKP":r===c)&&(u===void 0||u==="sig")&&(!t.crv||l===t.crv)}async function Ra(e,t,r){let n=e.get(t)||e.set(t,{}).get(t),{alg:o}=r;if(n[o]===void 0){let i=dr(r,t,!0).then(s=>{if(s.type!=="public")throw new xe("JSON Web Key Set members must be public keys");return n[o]=s,s}).catch(s=>{throw n[o]===i&&delete n[o],s});n[o]=i}return n[o]}function vr(e){let t;try{t=structuredClone(e)}catch(o){throw new xe("JSON Web Key Set malformed",{cause:o})}if(!gt(t))throw new xe("JSON Web Key Set malformed");let r=t.keys.map(o=>{let i=lr(o);return Array.isArray(i.key_ops)&&(i.key_ops=[...i.key_ops]),i}),n=new WeakMap;return Object.defineProperty(async(o,i)=>{let{alg:s,kid:a}={...o,...i?.header},c=typeof s=="string"?yr[s]:void 0;if(!c||c.secret)throw new ee('Unsupported "alg" value for a JSON Web Key Set');let u=t.keys.filter((m,y)=>cf(r[y],c,s,a)),{0:l,length:p}=u;if(!p)throw new Ne;if(p!==1){let m=new yt;throw m[Symbol.asyncIterator]=async function*(){for(let y of u)try{yield await Ra(n,y,c)}catch{}},m}return Ra(n,l,c)},"jwks",{value:()=>structuredClone(t)})}function uf(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var br;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(br="jose/v6.2.13");var Oa=Symbol();async function lf(e,t,r,n=fetch){let o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(i=>{throw i.name==="TimeoutError"?new ht(void 0,{cause:i}):i});if(o.status!==200)throw new $("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch(i){throw new $("Failed to parse the JSON Web Key Set HTTP response as JSON",{cause:i})}}var Ia=Symbol();function Qe(e,t){return Number.isFinite(e)&&Date.now()<e+t}function Aa(e,t,r){if(Number.isNaN(e))throw new TypeError(`"${r}" option must not be NaN`);return typeof e=="number"?e:t}function _r(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");let r=new URL(e.href).href,n=t??{},o=n.timeoutDuration;if(typeof o=="number"&&(!Number.isInteger(o)||o<0))throw new TypeError('"timeoutDuration" option must be a non-negative integer');let i=typeof o=="number"?o:5e3,s=Aa(n.cooldownDuration,3e4,"cooldownDuration"),a=Aa(n.cacheMaxAge,6e5,"cacheMaxAge"),c=new Headers(n.headers);br&&!c.has("User-Agent")&&c.set("User-Agent",br),c.has("accept")||c.set("accept","application/json, application/jwk-set+json");let u=n[Oa],l=n[Ia],p,m,y=0,d=0,f;if(l&&typeof l=="object"){let{uat:b,jwks:g}=l;Qe(b,a)&>(g)&&(p=b,f=vr(g))}let w=async()=>{if(m&&uf()&&(m=void 0),!m){let b=++y,g=m=lf(r,c,AbortSignal.timeout(i),u).then(v=>{let T=vr(v);if(b<=d)return;f=T;let E=Date.now();l&&(l.uat=E,l.jwks=v),p=E,d=b}).finally(()=>{m===g&&(m=void 0)})}await m};return Object.defineProperties(async(b,g)=>{(!f||!Qe(p,a))&&await w();try{return await f(b,g)}catch(v){if(v instanceof Ne&&!Qe(p,s))return await w(),f(b,g);throw v}},{coolingDown:{get:()=>Qe(p,s),enumerable:!0},fresh:{get:()=>Qe(p,a),enumerable:!0},reload:{value:w,enumerable:!0},reloading:{get:()=>!!m,enumerable:!0},jwks:{value:()=>f?.jwks(),enumerable:!0}})}var df=N("ui-http"),ff=["RS256","ES256"];function pf(e){let t=_r(new URL(e.jwksUrl));return async r=>{try{return await Sr(r,t,{audience:e.audience,issuer:e.issuer,algorithms:ff}),!0}catch{return!1}}}function mf(e){let t=e.trim().replace(/^https?:\/\//,"").replace(/\/+$/,"");return t.includes(".")?t:`${t}.cloudflareaccess.com`}function Pa(e){let t=(e.CORTEX_ACCESS_TEAM_DOMAIN||"").trim(),r=(e.CORTEX_ACCESS_AUD||"").trim();if(!t||!r)return;let o=`https://${mf(t)}`,i=(e.CORTEX_ACCESS_CERTS_URL||"").trim()||`${o}/cdn-cgi/access/certs`;return df.info(`Cloudflare Access JWT verification enabled (iss: ${o})`),pf({jwksUrl:i,audience:r,issuer:o})}var hf=N("ui-http"),gf=te.join(Xe,"ui-sessions.json"),wf=te.join(Xe,"ui-devices.json");function Ef(e){let t=(e.CORTEX_UI_TOKEN_LOGIN??"").trim().toLowerCase();return!(t==="0"||t==="false"||t==="off"||t==="no")}function Ca(e){let t=Number((e.CORTEX_UI_SESSION_TTL_DAYS??"").trim());return Number.isFinite(t)&&t>0?t*24*60*60*1e3:Gt}function Sf(){try{let e=te.dirname(yf(new URL("dist/entry/start-ui-http.js",__cortexPackageRoot).href));return[te.resolve(e,"../../web/dist"),te.resolve(e,"../../../web/dist")].find(r=>xa.existsSync(r))}catch{return}}function vf(e,t,r){let n=Ef(e),o=Di({file:wf}),i=p=>o.match(p)!==void 0,s=n?hi({file:gf,ttlMs:Ca(e)}):void 0,a=n?rs({file:te.join(Xe,es)}):void 0,u=Ri({getToken:t,matchDeviceToken:i,verifySession:s?p=>s.verify(p):void 0,verifyAccessJwt:r}),l=s&&a?vi({store:s,getToken:t,authorize:u,ttlMs:Ca(e),redeemCode:p=>a.redeem(p)}):bi(u);return{authorize:u,matchDeviceToken:i,tokenLogin:n,publicRoutes:n?[Qt,Be,rr]:[Be],routes:{...l,...Ci({devices:o,pairing:a})}}}function bf(e,t){return{...Yi({attachmentsDir:te.join(Ir,"attachments"),resolveWorkspaceRelPath:Pr,projectContextDir:r=>Es.get(r)?.contextDir,resolveMemoryFilePath:Ss}),...Wi(e),...$i({devMode:os()}),...di(),...zi({listDevices:cs,runOnDevice:async(r,n)=>{let o=await us(r,{action:"bash",params:{command:n},timeout:1e4});return typeof o?.stdout=="string"?o.stdout:""},openDevicePort:ls,closeDevicePort:ds,listDevicePorts:fs}),...t}}function _f(e,t,r,n,o){hf.info(`Web UI enabled \u2014 tRPC HTTP+SSE on ${e}`+(t?` (SPA: ${t})`:" (SPA: not built \u2014 non-tRPC paths 404)")+(r.length>0?` (CORS allow-list: ${r.join(", ")})`:"")+(n?" (Cloudflare Access JWT path enabled)":"")+(o?" (browser token login enabled)":" (browser token login disabled)"))}function Na(e,t){let r=e.env??process.env;if(!vs(r))return null;let n=e.corsOrigins??(()=>Cr().uiCorsOrigins),o=e.spaDir??r.CORTEX_UI_SPA_DIR??Sf(),i=Pa(r),s=e.getToken??Zo,a=vf(r,s,i),c=ra({listSessions:ps,streamPort:ms,setTakeover:ys,isTakenOver:hs,insertText:gs}),u=typeof n=="function"?n():n;return _f(t,o,u,!!i,a.tokenLogin),{router:Ws(e.uiService),getToken:s,matchDeviceToken:a.matchDeviceToken,spaDir:o,corsOrigins:n,authorize:a.authorize,createContext:l=>({client:bs(l.headers[Dr])}),publicRoutes:a.publicRoutes,customRoutes:{...a.routes,...bf(o,c.routes)},upgradeRoutes:{[ta]:c},portForward:r.CORTEX_PORT_FORWARD!=="0"}}function Gy(e,t){let r=Na(e,t);return r?er(r):null}function Yy(e){let t=e.env??process.env,r=parseInt(t.CORTEX_UI_PORT??"",10),n=Number.isNaN(r)?ws:r,o=Na(e,`127.0.0.1:${n}`);return o?Pi({...o,port:n,host:"127.0.0.1"}):null}export{Gy as createUiHttp,Yy as startUiHttpServer};
|
|
30
|
+
/*! Bundled license information:
|
|
31
|
+
|
|
32
|
+
@trpc/server/dist/resolveResponse-JtMyT9TQ.mjs:
|
|
33
|
+
(* istanbul ignore if -- @preserve *)
|
|
34
|
+
(*!
|
|
35
|
+
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
36
|
+
*
|
|
37
|
+
* Copyright (c) 2014-2017, Jon Schlinkert.
|
|
38
|
+
* Released under the MIT License.
|
|
39
|
+
*)
|
|
40
|
+
|
|
41
|
+
@trpc/server/dist/resolveResponse-JtMyT9TQ.mjs:
|
|
42
|
+
(* istanbul ignore if -- @preserve *)
|
|
43
|
+
*/
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{a as _,c as y}from"./chunk-UT6DGZDO.js";import{a as m,b,c as f,e as h,f as l,g as w}from"./chunk-ETIBCA2S.js";import{c as g}from"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-5M4PFLRW.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as r}from"./chunk-W34AK4SK.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";var $=40*1e3,F=1800*1e3,E=1500*1e3;function k(t){return{model:r.string().optional().describe(t.model),backend:r.enum(["claude","pi"]).optional().describe(t.backend),clean:r.boolean().optional().describe(b),files:r.array(r.string()).optional().describe(f)}}function I(t){let e=r.object({description:r.string().describe("Short description of the delegated task."),prompt:r.string().describe("Complete task prompt for the subagent."),subagent_type:r.string().describe(t.subagentType),...k(t)});return{description:r.string().optional().describe("Short description for single mode."),prompt:r.string().optional().describe("Complete prompt for single mode."),subagent_type:r.string().optional().describe(t.subagentTypeSingle),...k(t),parallel:r.array(e).min(1).max(8).optional().describe("Tasks to execute concurrently."),chain:r.array(e).min(1).max(8).optional().describe("Tasks to execute sequentially; {previous} inserts the prior output."),run_in_background:r.boolean().optional().describe("Return agent_id immediately; results arrive later. Default: wait for completion.")}}function R(t){let e=h(t);try{return l({roles:w(g()),models:e})}catch{return l({models:e})}}async function d(t,e,n,i){let{body:o}=await _("POST",`${t.webhookBaseUrl}/webhook/subagent`,{action:e,sessionId:t.sessionId,...n},y(t),i);if(!o?.success)throw new Error(o?.error||`subagent ${e} failed`);return o.data}async function N(t,e){try{await d(t,"detach",{runId:e})}catch{}}function u(t,e=!1){return{content:[{type:"text",text:t}],...e?{isError:!0}:{}}}function D(t,e){let n=t?._meta?.progressToken,i=t?.sendNotification;return n===void 0||!i?()=>{}:o=>{try{Promise.resolve(i({method:"notifications/progress",params:{progressToken:n,progress:o,message:`agent ${e} still running`}})).catch(()=>{})}catch{}}}async function C(t,e,n=()=>{}){let i=Date.now()+E;for(let o=1;;o++){let s=await d(t,"wait",{runId:e},$);if(s.status!=="running")return s;if(Date.now()>=i)return{...s,timedOut:!0};n(o)}}function U(t,e){if(t.timedOut){let n=Math.round(E/6e4);return{text:`Agent ${e} passed the ${n}-minute foreground limit and now runs in the background: it keeps going, and its result will be delivered to you when it lands. Stop it with agent_stop("${e}") if it is no longer useful.`,isError:!1}}return t.status==="completed"?{text:t.text??"(no output)",isError:!1}:t.status==="stopped"?{text:`Agent ${e} was stopped.`,isError:!0}:{text:`Agent ${e} failed: ${t.error??"unknown error"}`,isError:!0}}function G(t,e){let n=R(e),i=I(n);t.tool("agent",m+n.catalog,i,async(o,s)=>{try{let{run_in_background:c,...T}=o,a=await d(e,"start",{params:T,background:!!c,cwd:process.cwd(),selection:e.selection,project:e.project,channel:e.channel,backend:e.backend});if(c)return u(`Agent ${a.id} started in the background. Its result will be delivered to you when it is ready. Stop it early with agent_stop("${a.id}").`);let p=await C(e,a.id,D(s,a.id));p.timedOut&&await N(e,a.id);let{text:A,isError:O}=U(p,a.id);return u(A,O)}catch(c){return u(`agent error: ${c.message}`,!0)}}),t.tool("agent_stop","Stop a subagent and discard its output; not for collecting results.",{agent_id:r.string().describe("The agent_id returned when the subagent was started.")},async({agent_id:o})=>{try{let s=await d(e,"stop",{runId:o});return u(`Agent ${s.id} is now ${s.status}.`)}catch(s){return u(`agent_stop error: ${s.message}`,!0)}})}export{F as CLIENT_IDLE_FLOOR_MS,E as FOREGROUND_DEADLINE_MS,$ as WAIT_REQUEST_TIMEOUT_MS,G as registerSubagentTools};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
2
|
const require = __cortexCreateRequire(import.meta.url);
|
|
3
3
|
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import"./chunk-KRXTI4JO.js";import{
|
|
4
|
+
import"./chunk-KRXTI4JO.js";import{K as a}from"./chunk-W34AK4SK.js";import"./chunk-WHC7AYZD.js";function d(i,n){let o=new Intl.DateTimeFormat("en-CA",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,weekday:"short",timeZoneName:"shortOffset"}).formatToParts(i),e=c=>o.find(l=>l.type===c)?.value??"",t=`${e("year")}-${e("month")}-${e("day")}`,s=`${e("hour")==="24"?"00":e("hour")}:${e("minute")}:${e("second")}`,m=e("timeZoneName").replace(/^GMT/,"UTC");return{timezone:n,local:`${t} ${s}`,offset:m,weekday:e("weekday")}}function f(i){i.tool("current_time","Get current Unix milliseconds, UTC ISO date, and local date/time with UTC offset.",{timezone:a.string().optional().describe("IANA timezone, e.g. America/Denver or UTC. Default: server local timezone.")},{readOnlyHint:!0},async({timezone:n})=>{let o=new Date,e=n||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";try{let t=d(o,e),r={timezone:t.timezone,local:t.local,weekday:t.weekday,offset:t.offset,iso_utc:o.toISOString(),unix_ms:o.getTime()};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(t){return{content:[{type:"text",text:`Invalid timezone "${e}": ${t.message}. Use an IANA name like "Asia/Shanghai" or "UTC".`}],isError:!0}}})}export{f as registerTimeTools};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{p as a,q as b}from"./chunk-BZDIAI5M.js";import"./chunk-IA6IODY3.js";import"./chunk-IYVZHGUQ.js";import"./chunk-Y6ZEVVL5.js";import"./chunk-B3XBQEFM.js";import"./chunk-ETIBCA2S.js";import"./chunk-R6CGBSTC.js";import"./chunk-TMV2ZDOI.js";import"./chunk-V7K3KNDM.js";import"./chunk-RA2BUYI3.js";import"./chunk-U23S37TT.js";import"./chunk-T73GHMFB.js";import"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-VK5J556O.js";import"./chunk-5M4PFLRW.js";import"./chunk-STCNHXPJ.js";import"./chunk-STUHNKQS.js";import"./chunk-W34AK4SK.js";import"./chunk-TX46YMGI.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";export{a as childExtensions,b as installToolShims};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
2
|
const require = __cortexCreateRequire(import.meta.url);
|
|
3
3
|
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as s}from"./chunk-E6BYRULL.js";import{a as r}from"./chunk-KGJZAYQD.js";import"./chunk-
|
|
4
|
+
import{a as s}from"./chunk-E6BYRULL.js";import{a as r}from"./chunk-KGJZAYQD.js";import"./chunk-FF7UELTU.js";import"./chunk-23PRJECN.js";import"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import"./chunk-K4NTZEDJ.js";import"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var n={api:"typesafe-system-one",label:"System One API",detectCompat:e=>e.provider==="openrouter"||e.baseUrl.includes("openrouter.ai")?{imageInput:"state-image-urls",sendImageOptInHeader:!1}:{imageInput:"assets",sendImageOptInHeader:!0},url:e=>new URL("systemone",`${e.baseUrl.replace(/\/+$/u,"")}/`),payload:(e,t)=>({model:e.id,...t}),output:e=>{if(!r(e))throw new Error("System One API returned an unexpected response");return e}},m=(e,t,a)=>s(n,e,t,a);export{m as classify};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{b as c}from"./chunk-TURBFBYN.js";import{a as i,c as a,d}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as s}from"./chunk-W34AK4SK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";var b="Open a board: a live HTML status page shown in the Web UI, worth it when you dispatch several workers or the task spans many turns or hours. Give `title` to create one, or `board` (id or slug) to attach to an existing one. Binds this session, and your active workers that have no board yet if you lead a team. Returns the board directory.";async function l(o,e){let r=d(o);if(!r)throw new Error("No web session in context \u2014 boards are only available in Web UI sessions");let{body:t}=await i("POST",`${o.webhookBaseUrl}/webhook/board`,{sessionId:r,...e},a(o));if(!t?.success)throw new Error(t?.error||`board ${String(e.action)} failed`);return t.data}function h(o,e=!1){return{content:[{type:"text",text:o}],...e?{isError:!0}:{}}}function u(o){let e=o.bound.length-1;return[c(o),`Board directory: ${o.dir}`,`Edit ${o.dir}/board.html (body content only); put images in ${o.dir}/assets/.`,e>0?`Bound this session and ${e} worker(s).`:"Bound this session.","Write with the preset classes from the board skill; the scaffold has an example of every component."].join(`
|
|
5
|
+
`)}function y(o,e){o.tool("board_open",b,{title:s.string().optional().describe("Title of a new board."),board:s.string().optional().describe("Id or slug of an existing board.")},async({title:r,board:t})=>{try{if(!!r?.trim()==!!t?.trim())throw new Error("give exactly one of title or board");let n=await l(e,{action:"open",...r?.trim()?{title:r}:{board:t}});return h(u(n))}catch(n){return h(`board_open failed: ${n.message}`,!0)}})}export{u as openedText,y as registerUiBoardTools};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{a as r,c as a,d as c}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as e}from"./chunk-W34AK4SK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";var h="Record choices the user did not dictate: approach, plan/scope changes, tools, or parameters. Skip mechanical steps. Non-blocking; for approval before proceeding use cortex_ask_user. Batch related decisions. Explain what and why briefly in plain language for a reader new to the work, using the conversation language.",m=e.object({title:e.string().min(1).max(120).describe("Decision in one short line."),decision:e.string().min(1).max(1e3).describe("What you decided, in 1-2 plain sentences a non-expert can follow."),context:e.string().min(1).max(1e3).describe("Task and alternatives: why a choice was needed."),reasoning:e.string().min(1).max(1e3).describe("Decisive trade-off, in 1-2 sentences.")});function g(d,i){d.tool("send_decision",h,{decisions:e.array(m).min(1).max(10).describe("Decisions, one card each.")},async({decisions:s})=>{try{let n=c(i);if(!n)throw new Error("No web session in context \u2014 send_decision is only usable inside a Web UI chat session");let{body:o}=await r("POST",`${i.webhookBaseUrl}/webhook/ui-decision`,{sessionId:n,decisions:s},a(i));if(!o.success)throw new Error(o.error||"send_decision failed");let t=o.data?.titles??s.map(l=>l.title);return{content:[{type:"text",text:`Recorded ${t.length} decision(s) in the chat: ${t.join(" \xB7 ")}`}]}}catch(n){return{content:[{type:"text",text:`Failed to send decisions: ${n.message}`}],isError:!0}}})}export{g as registerUiDecisionTools};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
2
|
const require = __cortexCreateRequire(import.meta.url);
|
|
3
3
|
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as d}from"./chunk-
|
|
4
|
+
import{a as d}from"./chunk-S3MR37DL.js";import{a as l,c as f,d as c}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as r}from"./chunk-W34AK4SK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";import*as n from"fs";import*as a from"path";var h="File path: local absolute/working-directory-relative, or absolute on device.";function p(e){let o=!!e.files?.length;if(o===!!e.file_path)throw new Error("Pass either `file_path` or a non-empty `files`, not both");return o?e.files:[{file_path:e.file_path,file_name:e.file_name}]}function m(e,o){if(o){if(!d(e))throw new Error(`file_path must be absolute when \`device\` is set: ${e}`);return e}let i=a.isAbsolute(e)?e:a.resolve(process.cwd(),e);if(!n.existsSync(i))throw new Error(`File not found: ${i}`);if(!n.statSync(i).isFile())throw new Error(`Not a file: ${i}`);return i}function b(e,o){let i=p(o).map(s=>({filePath:m(s.file_path,o.device),fileName:s.file_name})),t={sessionId:e,caption:o.caption,device:o.device};return i.length===1?{...t,...i[0]}:{...t,files:i}}function u(e,o){let i=o?` from ${o}`:"";if(e.length===1)return`Sent file to the user${i}: ${e[0].name} (${e[0].size} bytes)`;let t=e.map(s=>`- ${s.name} (${s.size} bytes)`);return[`Sent ${e.length} files to the user${i}:`,...t].join(`
|
|
5
5
|
`)}async function w(e,o){let i=c(e);if(!i)throw new Error("No web session in context \u2014 send_file is only usable inside a Web UI chat session");let{body:t}=await l("POST",`${e.webhookBaseUrl}/webhook/ui-file`,b(i,o),f(e));if(!t.success)throw new Error(t.error||"send_file failed");return u(Array.isArray(t.data)?t.data:[t.data],o.device)}function $(e,o){e.tool("send_file","Share produced files as downloadable chat cards (images preview inline). Send one file or an ordered group with a shared caption. Supports local or remote-device files. Embed images or videos in reply text with , using a local absolute/~/relative path, workspace/... path, registered-device:/absolute/path (or device:C:/path on Windows), or https:// URL.",{file_path:r.string().optional().describe(`${h} Use this OR \`files\`.`),file_name:r.string().optional().describe("Display filename override for file_path."),files:r.array(r.object({file_path:r.string().describe(h),file_name:r.string().optional().describe("Display filename override.")})).optional().describe("Ordered file group. Use files OR file_path."),caption:r.string().optional().describe("Optional short message shown alongside the file(s)."),device:r.string().optional().describe("Connected device to read files from; omit for this server.")},async i=>{try{return{content:[{type:"text",text:await w(o,i)}]}}catch(t){return{content:[{type:"text",text:`Failed to send file: ${t.message}`}],isError:!0}}})}export{$ as registerUiFileTools};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{a as h,c as w,d as f}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as e}from"./chunk-W34AK4SK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";import*as i from"fs";import*as n from"path";var x="Render an interactive HTML card, not a download. Use when visuals convey more than Markdown; not for plain text, single numbers, or decoration. Sandboxed: no Cortex, parent DOM, credentials, storage, cookies, or same-origin requests. HTTPS resources allowed. Inline CSS/JS; relative paths fail.";function T(p,s){p.tool("send_view",x,{title:e.string().describe("Short card title."),html:e.string().optional().describe("Self-contained HTML, max 256KB. Use html OR file_path."),file_path:e.string().optional().describe("Existing .html file, max 2MB. Use file_path OR html."),caption:e.string().optional().describe("Optional one-line note shown above the view."),height:e.number().optional().describe("First-paint height in px (160-900, default 360). The view auto-resizes after load."),width:e.enum(["narrow","wide","full"]).optional().describe("Card width: narrow (default, text column), wide (~1.5x), or full chat pane.")},async({title:m,html:a,file_path:o,caption:u,height:b,width:g})=>{try{let r=f(s);if(!r)throw new Error("No web session in context \u2014 send_view is only usable inside a Web UI chat session");let v=typeof a=="string"&&a.length>0,d=typeof o=="string"&&o.length>0;if(v===d)throw new Error("Provide exactly one of `html` or `file_path`");let t;if(d){if(t=n.isAbsolute(o)?o:n.resolve(process.cwd(),o),!i.existsSync(t))throw new Error(`File not found: ${t}`);if(!i.statSync(t).isFile())throw new Error(`Not a file: ${t}`)}let{body:l}=await h("POST",`${s.webhookBaseUrl}/webhook/ui-view`,{sessionId:r,title:m,html:a,filePath:t,caption:u,height:b,width:g},w(s));if(!l.success)throw new Error(l.error||"send_view failed");let c=l.data;return{content:[{type:"text",text:`Rendered view in the chat: ${c.name} (${c.size} bytes)`}]}}catch(r){return{content:[{type:"text",text:`Failed to send view: ${r.message}`}],isError:!0}}})}export{T as registerUiViewTools};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{a as p,b as n,c as i,lb as m}from"./chunk-NNTQUHLO.js";import"./chunk-HGPBHTVD.js";import"./chunk-Y3GFB5XM.js";import"./chunk-3CZPBLB3.js";import{B as a,z as r}from"./chunk-LAWOWPZX.js";import"./chunk-EQIMHXC4.js";import"./chunk-VQUPKMDR.js";import"./chunk-WEZWKMYU.js";import"./chunk-YKKEI5GI.js";import"./chunk-ZNZFWSPH.js";import"./chunk-4EX2JJWB.js";import"./chunk-BJGYGEZO.js";import"./chunk-RA6HKFBV.js";import"./chunk-AFTBQRPN.js";import"./chunk-XEBEWR6Y.js";import"./chunk-5DF5WJNM.js";import"./chunk-FX6MOGLR.js";import{Z as d}from"./chunk-CK3P345X.js";import"./chunk-ZQ7LGTSN.js";import{oa as e}from"./chunk-LACGULCN.js";import"./chunk-3TGQSGG4.js";import"./chunk-QUUEQRIT.js";import"./chunk-KDYEGGMW.js";import"./chunk-SKHLZ6XY.js";import"./chunk-6R73ICDB.js";import{N as o}from"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import"./chunk-CXT5IR5T.js";import"./chunk-AWFUHWQK.js";import"./chunk-G2V65UBA.js";import"./chunk-NHD2ESHA.js";import"./chunk-B3XBQEFM.js";import"./chunk-WHC7AYZD.js";var l={};var t={typebox:e,"typebox/compile":a,"typebox/value":r,"@sinclair/typebox":e,"@sinclair/typebox/compile":a,"@sinclair/typebox/value":r,"@earendil-works/pi-agent-core":p,"@earendil-works/pi-tui":d,"@earendil-works/pi-ai":i,"@earendil-works/pi-ai/compat":i,"@earendil-works/pi-ai/models":o,"@earendil-works/pi-ai/oauth":l,"@earendil-works/pi-ai/providers/all":n,"@earendil-works/pi-coding-agent":m,"@mariozechner/pi-agent-core":p,"@mariozechner/pi-tui":d,"@mariozechner/pi-ai":i,"@mariozechner/pi-ai/compat":i,"@mariozechner/pi-ai/models":o,"@mariozechner/pi-ai/oauth":l,"@mariozechner/pi-ai/providers/all":n,"@mariozechner/pi-coding-agent":m};export{t as VIRTUAL_MODULES};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{a as h,c as p}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as i}from"./chunk-W34AK4SK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";async function l(t,o,e){let{body:n}=await h("POST",`${t.webhookBaseUrl}/webhook/waitpoint`,{action:o,sessionId:t.sessionId,channel:t.channel,project:t.project,...e},p(t));if(!n.success)throw new Error(n.error||`waitpoint ${o} failed`);return n.data}function c(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function d(t){return{content:[{type:"text",text:t}],isError:!0}}function _(t,o,e,n,s=[]){let a=s.length>0?"MEMBER":null,r=`export CORTEX_SIGNAL_ID=${t} CORTEX_SIGNAL_SECRET=${o}`,u=a?`--member ${a} `:"",m=a?`"member":"${a}",`:"",w=`cortex-signal ${u}--exit-code $?`,b=`curl -sS -XPOST http://127.0.0.1:${e}/webhook/signal -H 'content-type: application/json' -d '{"id":"${t}","secret":"${o}",${m}"status":"ok","message":"done"}'`,f=['s=$?; d=~/.cortex/tmp/signals; f="$d/$(date +%s%N)-$$-$RANDOM"; mkdir -p "$d"',`printf '{"id":"${t}","secret":"${o}",${m}"status":"%s","message":"exit=%s"}' "$([ $s -eq 0 ] && echo ok || echo fail)" "$s" > "$f.tmp" && mv "$f.tmp" "$f.json"`].join(`
|
|
5
|
+
`),g=`(while kill -0 PID 2>/dev/null; do sleep 5; done; cortex-signal ${u}--status ok --message "pid PID exited") &`;return{recommended:n?"shell":"cli",env:r,cli:w,curl:b,shell:f,attach_to_pid:g,...a?{member_note:`Replace MEMBER with the job's own name, one of: ${s.join(", ")}.`}:{}}}function x(t,o){t.tool("wait_create","Arm an external callback that wakes this session with a result. Returns an ID, secret, and cortex-signal commands. Cortex launches nothing and watches nothing: arm BEFORE starting the job and install the returned callback in its command (or attach_to_pid for an existing job). Then END YOUR TURN; do not poll. Unsignaled waits expire.",{label:i.string().describe("Short name shown on wake."),intent:i.string().describe("Briefly state what you are waiting for and what to do next."),members:i.array(i.string()).optional().describe("Expected job names. If set, each signal must name a listed member."),quorum:i.union([i.number(),i.literal("all")]).optional().describe('How many terminal signals resolve this waitpoint. Defaults to "all" when members are given, else 1.'),fail_fast:i.boolean().optional().describe("Wake on the first failure even if the quorum is unmet. Default true."),max_signals:i.number().optional().describe("Wake limit (default 1). Higher values allow repeated reports; cancel when done. Send --status progress to record without waking."),expires_in_hours:i.number().optional().describe("Expiry notification deadline in hours (default 168, max 720)."),device:i.string().optional().describe("Connected device running the job; required for remote jobs so signals are collected there.")},async e=>{try{let n=await l(o,"create",{label:e.label,intent:e.intent,quorum:{need:e.quorum,members:e.members},failFast:e.fail_fast,maxSignals:e.max_signals,ttlMs:typeof e.expires_in_hours=="number"?e.expires_in_hours*36e5:void 0,device:e.device}),s=Number(new URL(o.webhookBaseUrl).port),a=Array.isArray(n.quorum?.members)?n.quorum.members:[],r=_(n.id,n.secret,s,e.device??null,a);return c({...n,how_to_signal:r,next:"Nothing will signal this waitpoint unless you put one of the how_to_signal lines where the job runs it (start the job with it, or attach_to_pid if it is already running). Do that first, then end your turn \u2014 you will be woken."})}catch(n){return d(`wait_create failed: ${n.message}`)}}),t.tool("wait_check","Inspect session-owned waitpoints and member reports. Read-only; wakes arrive automatically, so do not poll.",{id:i.string().optional().describe("Waitpoint id (wp_\u2026). Omit to list all of this session's waitpoints.")},{readOnlyHint:!0},async e=>{try{return c(await l(o,"check",{id:e.id}))}catch(n){return d(`wait_check failed: ${n.message}`)}}),t.tool("wait_cancel","Disarm an unneeded waitpoint. Invalidates its secret and prevents future wakes; cancel abandoned waits.",{id:i.string().describe("Waitpoint id (wp_\u2026) to cancel.")},async e=>{try{return c(await l(o,"cancel",{id:e.id}))}catch(n){return d(`wait_cancel failed: ${n.message}`)}})}export{_ as buildSignalRecipe,x as registerWaitpointTools};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{a as l,c as d}from"./chunk-UT6DGZDO.js";import{e as a,l as i}from"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as o}from"./chunk-W34AK4SK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";var p=30*1e3;async function w(e,r,s){let{body:t}=await l("POST",`${e.webhookBaseUrl}/webhook/team`,{action:r,sessionId:e.sessionId,...s},d(e),p);if(!t?.success)throw new Error(t?.error||`${r} failed`);return t.data}function u(e,r=!1){return{content:[{type:"text",text:e}],...r?{isError:!0}:{}}}var c="Returns immediately; reports and questions arrive as messages. After dispatch, end your turn; do not wait or poll.",k={model:"Model override: pi provider/model[:thinking], claude model ID. Default: your model on the same backend, otherwise that backend's default.",backend:"Backend override. Default: your backend."};function m(e){try{return i(a(e))}catch{return""}}function n(e,r){return async s=>{try{let t=await w(e,r,s);return u(typeof t?.text=="string"?t.text:JSON.stringify(t,null,2))}catch(t){return u(`${r} error: ${t.message}`,!0)}}}function y(e,r){let s=k;e.tool("worker_spawn",`Start a persistent, isolated session with full tools for follow-up or long-running work. Use for multiple/splittable tasks or a new task; keep single tasks here. For bounded work whose result you need now, use agent. Provide a self-contained prompt; workers cannot see this conversation. The user can talk to them directly. Final replies report back except routine updates; questions and approvals route to you (worker_answer). ${c}${m(r)}`,{name:o.string().describe("Unique slug: lowercase letters, digits, hyphens; max 32 characters."),prompt:o.string().describe("Complete, self-contained task for the worker."),backend:o.enum(["claude","pi"]).optional().describe(s.backend),model:o.string().optional().describe(s.model)},n(r,"spawn")),e.tool("worker_send","Continue or redirect a worker; injects into a running turn or starts a new one. Reaches inactive workers too. Reuse a relevant worker rather than spawning another. "+c,{worker:o.string().describe("The worker name."),message:o.string().describe("The message to deliver.")},n(r,"send")),e.tool("worker_list","List your workers, or inspect one with its full last report. Completion reports arrive automatically.",{worker:o.string().optional().describe("A worker name for its detail view.")},n(r,"list")),e.tool("worker_stop","Stop a worker's current turn. worker_send continues it later.",{worker:o.string().describe("The worker name.")},n(r,"stop")),e.tool("worker_answer","Answer a worker question or approve/reject its plan. Ask cortex_ask_user first if unsure of user intent. The user may also answer; first answer wins.",{request_id:o.string().describe("The request_id from the worker notice."),answers:o.record(o.string(),o.string()).optional().describe("Exact question text \u2192 answer, for a question."),approved:o.boolean().optional().describe("Approve or reject a plan."),feedback:o.string().optional().describe("Feedback for the worker, mainly when rejecting a plan.")},n(r,"answer"))}function _(e,r){e.tool("mark_routine","Before your final reply, mark a no-change or duplicate update so it does not wake the lead. Never use for results, milestones, failures, blockers, or needed action. Ask for decisions with cortex_ask_user.",{},n(r,"routine"))}export{_ as registerWorkerReportTools,y as registerWorkerTools};
|