@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
|
@@ -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{
|
|
4
|
+
import{a as o}from"./chunk-Z24SBRJK.js";import{readFileSync as t}from"node:fs";import{join as r}from"node:path";var n=r(o,"package.json"),p=JSON.parse(t(n,"utf-8")),a=p.version,c="https://fangxm233.github.io/cortex-agent/";export{a,c as b};
|
|
@@ -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{
|
|
4
|
+
import{a as u}from"./chunk-Z24SBRJK.js";import*as a from"fs";import*as r from"path";import{fileURLToPath as l}from"url";function x(e){return r.dirname(l(e))}function $(e){if(!process.argv[1])return!1;let t=l(e),n=r.resolve(process.argv[1]);if(n===t)return!0;try{return a.realpathSync(n)===t}catch{return!1}}function v(){let e=new Date,t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}_${t(e.getHours())}-${t(e.getMinutes())}-${t(e.getSeconds())}`}function S(e){if(e<60)return`${Math.round(e)}s`;let t=Math.floor(e/60),n=Math.round(e%60);return n>0?`${t}m ${n}s`:`${t}m`}function f(e,t={}){let n=(t.override??process.env.CORTEX_NPM_PREFIX)?.trim();if(n)return n;let o=t.exists??a.existsSync,i=t.pathEnv??process.env.PATH??"";for(let s of i.split(r.delimiter)){if(!s||!o(r.join(s,e)))continue;let c=r.dirname(s);if(o(r.join(c,"lib","node_modules")))return c}return null}function p(e,t,n=process.platform){let o=n==="win32"?r.win32:r.posix,i=o.resolve(e);for(let c of t.split("/").reverse()){if(o.basename(i)!==c)return null;i=o.dirname(i)}if(o.basename(i)!=="node_modules")return null;let s=o.dirname(i);return n==="win32"?s:o.basename(s)==="lib"?o.dirname(s):null}function _(e,t=u){let n=process.env.CORTEX_NPM_PREFIX?.trim()||p(t,"@cortex-agent/server")||f("cortex");return n?[...e,"--prefix",n]:e}function w(e,t=process.platform,n=process.execPath,o=a.existsSync){if(t!=="win32")return{command:"npm",args:e,shell:!1};let i=r.win32.join(r.win32.dirname(n),"node_modules","npm","bin","npm-cli.js");return o(i)?{command:n,args:[i,...e],shell:!1}:{command:"npm.cmd",args:e.map(m),shell:!0}}function m(e){return`"${e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")}"`}export{x as a,$ as b,v as c,S as d,p as e,_ as f,w as g};
|
|
@@ -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{b as H}from"./chunk-UT6DGZDO.js";import{m as B}from"./chunk-ETIBCA2S.js";import{a as J,b as Y}from"./chunk-WZYS2HAK.js";import{C as v,E as P,H as C,K as x,U as L,V as Z,W as D,Z as p,_ as I,a as f,c as T,d as b,e as g,f as R,g as G,h as W,i as F,n as u,v as _,x as E,z as k}from"./chunk-TMV2ZDOI.js";import{a as U,b as z,d as X}from"./chunk-5T7IX5KN.js";import{i as V}from"./chunk-OE4KH3NJ.js";import{a as N}from"./chunk-NRD57ICT.js";import{D as j}from"./chunk-W34AK4SK.js";import{e as O}from"./chunk-VBN2JSER.js";import{b as q}from"./chunk-NXZS5PEW.js";var Q=Symbol.for("mcp.completable");function A(s){return!!s&&typeof s=="object"&&Q in s}function ee(s){return s[Q]?.complete}var K;(function(s){s.Completable="McpCompletable"})(K||(K={}));var ce=/^[A-Za-z0-9._-]{1,128}$/;function de(s){let e=[];if(s.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(s.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${s.length})`]};if(s.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),s.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(s.startsWith("-")||s.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(s.startsWith(".")||s.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!ce.test(s)){let t=s.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,a)=>a.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${t.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function ue(s,e){if(e.length>0){console.warn(`Tool name validation warning for "${s}":`);for(let t of e)console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function M(s){let e=de(s);return ue(s,e.warnings),e.isValid}var y=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let o={taskSupport:"required",...t.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,o,t._meta,r)}};function pe(s,e){let t=0,r=[s];for(;r.length>0;){let o=r.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let a of o){if(++t>e)return t;a!==null&&typeof a=="object"&&r.push(a)}else for(let a in o){if(!Object.prototype.hasOwnProperty.call(o,a))continue;if(++t>e)return t;let n=o[a];n!==null&&typeof n=="object"&&r.push(n)}}return t}function me(s){if(!(s===void 0||s===1/0)){if(typeof s!="number"||Number.isNaN(s)||s<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(s)}`);return s}}var S=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new J(e,t),this._maxToolInputElements=me(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new y(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(h(C)),this.server.assertCanSetRequestHandler(h(x)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(C,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let o=g(t.inputSchema);return o?I(o,{strictUnions:!0,pipeStrategy:"input"}):he})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let o=g(t.outputSchema);o&&(r.outputSchema=I(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(x,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new p(u.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,a=r.execution?.taskSupport,n="createTask"in r.handler;if((a==="required"||a==="optional")&&!n)throw new p(u.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!o)throw new p(u.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!o&&n)return await this.handleAutomaticTaskPolling(r,e,t);let i=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,i,t);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof p&&r.code===u.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(this._maxToolInputElements!==void 0&&pe(t,this._maxToolInputElements)>this._maxToolInputElements)throw new p(u.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let a=g(e.inputSchema)??e.inputSchema,n=await T(a,t??{});if(!n.success){let i="error"in n?n.error:"Unknown error",c=R(i);throw new p(u.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return n.data}async validateToolOutput(e,t,r){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new p(u.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=g(e.outputSchema),a=await T(o,t.structuredContent);if(!a.success){let n="error"in a?a.error:"Unknown error",i=R(n);throw new p(u.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${i}`)}}async executeToolHandler(e,t,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let n={...r,taskStore:r.taskStore};if(e.inputSchema){let i=o;return await Promise.resolve(i.createTask(t,n))}else{let i=o;return await Promise.resolve(i.createTask(n))}}if(e.inputSchema){let n=o;return await Promise.resolve(n(t,r))}else{let n=o;return await Promise.resolve(n(r))}}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,t.params.arguments,t.params.name),a=e.handler,n={...r,taskStore:r.taskStore},i=o?await Promise.resolve(a.createTask(o,n)):await Promise.resolve(a.createTask(n)),c=i.task.taskId,l=i.task,m=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(le=>setTimeout(le,m));let d=await r.taskStore.getTask(c);if(!d)throw new p(u.InternalError,`Task ${c} not found during polling`);l=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(h(L)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(L,async e=>{switch(e.params.ref.type){case"ref/prompt":return Z(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return D(e),this.handleResourceCompletion(e,e.params.ref);default:throw new p(u.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new p(u.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return w;let a=b(r.argsSchema)?.[e.params.argument.name];if(!A(a))return w;let n=ee(a);if(!n)return w;let i=await n(e.params.argument.value,e.params.context);return re(i)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(n=>n.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return w;throw new p(u.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return w;let a=await o(e.params.argument.value,e.params.context);return re(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(h(_)),this.server.assertCanSetRequestHandler(h(E)),this.server.assertCanSetRequestHandler(h(k)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([a,n])=>n.enabled).map(([a,n])=>({uri:a,name:n.name,...n.metadata})),o=[];for(let a of Object.values(this._registeredResourceTemplates)){if(!a.resourceTemplate.listCallback)continue;let n=await a.resourceTemplate.listCallback(t);for(let i of n.resources)o.push({...a.metadata,...i})}return{resources:[...r,...o]}}),this.server.setRequestHandler(E,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(k,async(e,t)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new p(u.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,t)}for(let a of Object.values(this._registeredResourceTemplates)){let n=a.resourceTemplate.uriTemplate.match(r.toString());if(n)return a.readCallback(r,n,t)}throw new p(u.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(h(v)),this.server.assertCanSetRequestHandler(h(P)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(v,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?fe(t.argsSchema):void 0}))})),this.server.setRequestHandler(P,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new p(u.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=g(r.argsSchema),a=await T(o,e.params.arguments??{});if(!a.success){let c="error"in a?a.error:"Unknown error",l=R(c);throw new p(u.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let n=a.data,i=r.callback;return await Promise.resolve(i(n,t))}else{let o=r.callback;return await Promise.resolve(o(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let o;typeof r[0]=="object"&&(o=r.shift());let a=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,o,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,o,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,r,o){if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,r.title,t,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,r.title,t,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,t,r,o,a){let n={name:e,title:t,metadata:o,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==r&&(delete this._registeredResources[r],i.uri&&(this._registeredResources[i.uri]=n)),typeof i.name<"u"&&(n.name=i.name),typeof i.title<"u"&&(n.title=i.title),typeof i.metadata<"u"&&(n.metadata=i.metadata),typeof i.callback<"u"&&(n.readCallback=i.callback),typeof i.enabled<"u"&&(n.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=n,n}_createRegisteredResourceTemplate(e,t,r,o,a){let n={resourceTemplate:r,title:t,metadata:o,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=n)),typeof l.title<"u"&&(n.title=l.title),typeof l.template<"u"&&(n.resourceTemplate=l.template),typeof l.metadata<"u"&&(n.metadata=l.metadata),typeof l.callback<"u"&&(n.readCallback=l.callback),typeof l.enabled<"u"&&(n.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=n;let i=r.uriTemplate.variableNames;return Array.isArray(i)&&i.some(l=>!!r.completeCallback(l))&&this.setCompletionRequestHandler(),n}_createRegisteredPrompt(e,t,r,o,a){let n={title:t,description:r,argsSchema:o===void 0?void 0:f(o),callback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=n)),typeof i.title<"u"&&(n.title=i.title),typeof i.description<"u"&&(n.description=i.description),typeof i.argsSchema<"u"&&(n.argsSchema=f(i.argsSchema)),typeof i.callback<"u"&&(n.callback=i.callback),typeof i.enabled<"u"&&(n.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=n,o&&Object.values(o).some(c=>{let l=c instanceof j?c._def?.innerType:c;return A(l)})&&this.setCompletionRequestHandler(),n}_createRegisteredTool(e,t,r,o,a,n,i,c,l){M(e);let m={title:t,description:r,inputSchema:te(o),outputSchema:te(a),annotations:n,execution:i,_meta:c,handler:l,enabled:!0,disable:()=>m.update({enabled:!1}),enable:()=>m.update({enabled:!0}),remove:()=>m.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&M(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=m)),typeof d.title<"u"&&(m.title=d.title),typeof d.description<"u"&&(m.description=d.description),typeof d.paramsSchema<"u"&&(m.inputSchema=f(d.paramsSchema)),typeof d.outputSchema<"u"&&(m.outputSchema=f(d.outputSchema)),typeof d.callback<"u"&&(m.handler=d.callback),typeof d.annotations<"u"&&(m.annotations=d.annotations),typeof d._meta<"u"&&(m._meta=d._meta),typeof d.enabled<"u"&&(m.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=m,this.setToolRequestHandlers(),this.sendToolListChanged(),m}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,a,n;if(typeof t[0]=="string"&&(r=t.shift()),t.length>1){let c=t[0];if($(c))o=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!$(t[0])&&(n=t.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);n=t.shift()}}let i=t[0];return this._createRegisteredTool(e,void 0,r,o,a,n,{taskSupport:"forbidden"},void 0,i)}registerTool(e,t,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:a,inputSchema:n,outputSchema:i,annotations:c,_meta:l}=t;return this._createRegisteredTool(e,o,a,n,i,c,{taskSupport:"forbidden"},l,r)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let o;t.length>1&&(o=t.shift());let a=t[0],n=this._createRegisteredPrompt(e,void 0,r,o,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),n}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:a,argsSchema:n}=t,i=this._createRegisteredPrompt(e,o,a,n,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var he={type:"object",properties:{}};function se(s){return s!==null&&typeof s=="object"&&"parse"in s&&typeof s.parse=="function"&&"safeParse"in s&&typeof s.safeParse=="function"}function oe(s){return"_def"in s||"_zod"in s||se(s)}function $(s){return typeof s!="object"||s===null||oe(s)?!1:Object.keys(s).length===0?!0:Object.values(s).some(se)}function te(s){if(s){if($(s))return f(s);if(!oe(s))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return s}}function fe(s){let e=b(s);return e?Object.entries(e).map(([t,r])=>{let o=G(r),a=W(r);return{name:t,description:o,required:!a}}):[]}function h(s){let t=b(s)?.method;if(!t)throw new Error("Schema is missing a method literal");let r=F(t);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function re(s){return{completion:{values:s.slice(0,100),total:s.length,hasMore:s.length>100}}}var w={completion:{values:[],hasMore:!1}};function ne(s,e){let t=s.tool,r=new Map;s.tool=((...n)=>{let i=t.apply(s,n);return i&&(n[0]==="agent"||n[0]==="worker_spawn")&&r.set(n[0],i),i});try{e()}finally{s.tool=t}let o=r.get("worker_spawn");r.get("agent")&&o&&o.update({description:B(o.description??"")})}var ae=O("mcp-bundled"),ge=async s=>{let[{registerRemoteOpsTools:e},{registerTimeTools:t},{registerSubagentTools:r}]=await Promise.all([import("./remote-ops-O5CR4RGA.js"),import("./time-P6PE52WL.js"),import("./subagent-OZGUOV3J.js")]);return o=>{e(o,s),t(o),r(o,s)}},we=async s=>{let[{registerCostTools:e},{registerExecutionTools:t},{registerContextTools:r},{registerWaitpointTools:o}]=await Promise.all([import("./cost-OOO32GLC.js"),import("./executions-BN6OLLVM.js"),import("./context-GQKWKFRM.js"),import("./waitpoint-W5M3BE55.js")]);return a=>{e(a),t(a),r(a,s),o(a,s)}},Te=async s=>{let[{registerInteractionPlanTools:e,interactionDepsFor:t},{registerInteractionAskTools:r}]=await Promise.all([import("./interaction-plan-C446T2GZ.js"),import("./interaction-ask-EE2UPR3Q.js")]),o=t(s);return a=>{e(a,o),r(a,o)}},be=async s=>{let{registerSlackTools:e,slackDepsFor:t}=await import("./slack-2CGM4SMY.js"),r=t(s);return o=>e(o,r)},Re=async s=>{let[{registerFileTools:e},{buildFeishuClientFromEnv:t}]=await Promise.all([import("./file-H572PL2Z.js"),import("../domain/mcp/feishu/client.js")]),r=t();return o=>e(o,{client:r,fallbackChannel:s.channel,ctx:s})},ye=async s=>{let[{registerUiFileTools:e},{registerUiViewTools:t},{registerUiDecisionTools:r},{registerUiBoardTools:o}]=await Promise.all([import("./ui-file-6PLXHSTB.js"),import("./ui-view-6MDU4GXY.js"),import("./ui-decision-6HHNROIT.js"),import("./ui-board-H4INJD6C.js")]);return a=>{e(a,s),t(a,s),r(a,s),o(a,s)}},Se=async s=>{let{registerWorkerTools:e}=await import("./workers-GTFP75MS.js");return t=>e(t,s)},_e=async s=>{let{registerWorkerReportTools:e}=await import("./workers-GTFP75MS.js");return t=>e(t,s)},Ee={"cortex-core":ge,"cortex-ext":we,"cortex-interaction-bridge":Te,"cortex-slack":be,"cortex-feishu":Re,"cortex-web":ye,"cortex-workers":Se,"cortex-worker-report":_e};function ke(s,e){let t=e instanceof Error?e.message:String(e);ae.error(`Skipping MCP bundle ${s}: ${t}`)}async function ve(s,e,t=(o,a)=>Ee[o](a),r=ke){return(await Promise.all(s.map(async a=>{try{let n=await t(a,e);return i=>{try{n(i)}catch(c){r(a,c)}}}catch(n){return r(a,n),null}}))).filter(a=>a!==null)}async function ie(s,e){let t=await ve(s,e),r=new S({name:z,version:N});return V(r,o=>ne(o,()=>t.forEach(a=>a(o))),e.toolAllowlist),r}async function Pe(){let s=process.env[U]??process.argv[2],e=X(s);if(e.includes("cortex-ext")){let{executionRepo:r}=await import("./execution-repo-XXL4FXC6.js");r.follow()}await(await ie(e,H())).connect(new Y)}q(new URL("dist/domain/mcp/bundled-server.js",__cortexPackageRoot).href)&&Pe().catch(s=>{ae.error(s),process.exit(1)});async function et(s,e){return ie(s,H(e))}export{ve as a,ie as b,Pe as c,et as d};
|
|
@@ -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{
|
|
4
|
+
import{i as m}from"./chunk-Z24SBRJK.js";import*as d from"path";import{readFileSync as y,writeFileSync as S,mkdirSync as v,existsSync as w,unlinkSync as b}from"fs";var h=class extends Error{constructor(t){super(t),this.name="FeishuUserTokenError"}};function u(e){return e==="lark"?{authorizeBase:"https://accounts.larksuite.com",tokenBase:"https://open.larksuite.com"}:{authorizeBase:"https://accounts.feishu.cn",tokenBase:"https://open.feishu.cn"}}var k="/open-apis/authen/v2/oauth/token",P="/open-apis/authen/v1/authorize",U="/oauth/v1/device_authorization",E="urn:ietf:params:oauth:grant-type:device_code",z="offline_access",N="docx:document sheets:spreadsheet bitable:app wiki:wiki space:document:delete im:resource";function f(){return d.join(m,"feishu-user-token.json")}function T(e){let t=new Set((e??"").split(/\s+/).filter(Boolean));return t.add(z),[...t].join(" ")}function B(e){let{authorizeBase:t}=u(e.domain),n=new URL(t+P);return n.searchParams.set("client_id",e.appId),n.searchParams.set("redirect_uri",e.redirectUri),n.searchParams.set("response_type","code"),n.searchParams.set("scope",T(e.scope)),e.state&&n.searchParams.set("state",e.state),n.toString()}function R(e){let t=(e??"").trim();if(!t)return null;if(/^https?:\/\//i.test(t))try{return new URL(t).searchParams.get("code")}catch{return null}return t}function p(e,t,n){let o=Number(e.expires_in??0)*1e3,r=Number(e.refresh_token_expires_in??0)*1e3;return{access_token:String(e.access_token??""),refresh_token:String(e.refresh_token??n??""),access_expires_at:t+o,refresh_expires_at:t+r,scope:e.scope,obtained_at:t}}async function x(e,t,n){let o=await n(e.tokenBase+k,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(t)}),r=await o.json().catch(()=>({}));if(!o.ok||typeof r.code=="number"&&r.code!==0||r.error){let i=r.error_description||r.error||r.msg||`HTTP ${o.status}`,c=r.code??r.error??o.status;throw new Error(`Feishu OAuth error ${c}: ${i}`)}return r}async function j(e){let t=e.fetchImpl??globalThis.fetch,n=(e.now??Date.now)(),o={grant_type:"authorization_code",client_id:e.appId,client_secret:e.appSecret,code:e.code};e.redirectUri&&(o.redirect_uri=e.redirectUri);let r=await x(u(e.domain),o,t);return p(r,n)}function O(e,t){return Buffer.from(`${e}:${t}`,"utf8").toString("base64")}function g(e){return Object.entries(e).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&")}async function H(e){let t=e.fetchImpl??globalThis.fetch,n=u(e.domain),o=await t(n.authorizeBase+U,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${O(e.appId,e.appSecret)}`},body:g({client_id:e.appId,scope:T(e.scope)})}),r=await o.json().catch(()=>({}));if(!o.ok||r.error||!r.device_code){let c=r.error_description||r.error||r.msg||`HTTP ${o.status}`;throw new Error(`Feishu device authorization failed: ${c}`)}let i=String(r.verification_uri??"");return{device_code:String(r.device_code),user_code:String(r.user_code??""),verification_uri:i,verification_uri_complete:String(r.verification_uri_complete||i),expires_in:Number(r.expires_in??300),interval:Number(r.interval??5)}}async function L(e){let t=e.fetchImpl??globalThis.fetch,n=e.sleep??(l=>new Promise(s=>setTimeout(s,l))),o=e.now??Date.now,r=u(e.domain),i=60,c=Math.max(1,e.interval??5),I=o()+(e.expiresIn??300)*1e3;for(;;){await n(c*1e3);let s=await(await t(r.tokenBase+k,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:g({grant_type:E,device_code:e.deviceCode,client_id:e.appId,client_secret:e.appSecret})})).json().catch(()=>({})),a=s.error;if(!a&&s.access_token)return p(s,o());if(a==="authorization_pending")e.onPending?.();else if(a==="slow_down")c=Math.min(i,c+5),e.onPending?.();else if(a)throw new Error(`Feishu device login failed: ${s.error_description||a}`);if(o()>=I)throw new Error("Feishu device login timed out before authorization completed.")}}async function C(e){let t=e.fetchImpl??globalThis.fetch,n=(e.now??Date.now)(),o=await x(u(e.domain),{grant_type:"refresh_token",client_id:e.appId,client_secret:e.appSecret,refresh_token:e.refreshToken},t);return p(o,n,e.refreshToken)}function A(e,t=f()){v(d.dirname(t),{recursive:!0}),S(t,JSON.stringify(e,null,2),{mode:384})}function F(e=f()){if(!w(e))return null;try{return JSON.parse(y(e,"utf8"))}catch{return null}}function G(e=f()){if(!w(e))return!1;try{return b(e),!0}catch{return!1}}var _="Run `cortex feishu login` to authorize a Feishu user account.";async function J(e){let t=e.file??f(),n=(e.now??Date.now)(),o=e.bufferMs??12e4,r=F(t);if(!r||!r.access_token)throw new h(`No Feishu user token found. ${_}`);if(n<r.access_expires_at-o)return r.access_token;if(!r.refresh_token||n>=r.refresh_expires_at)throw new h(`Feishu user token expired and cannot be refreshed. ${_}`);let i=await C({appId:e.appId,appSecret:e.appSecret,refreshToken:r.refresh_token,domain:e.domain,fetchImpl:e.fetchImpl,now:()=>n});return A(i,t),i.access_token}export{N as a,f as b,B as c,R as d,j as e,H as f,L as g,A as h,F as i,G as j,J as k};
|
|
@@ -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,b as i,c as s,e as c}from"./chunk-IA6IODY3.js";import{d as m,j as u}from"./chunk-RF4JLYBX.js";import{M as f}from"./chunk-JJDEQ6N2.js";var a=30;function v(e){return[e.default,...Array.isArray(e.favorites)?e.favorites:[]].filter(t=>{let r=t;return!!r&&typeof r.model=="string"&&!!r.model.trim()})}var y={policy:{allow:"all",deny:[]},favorites:[]};function d(){let e=null;try{e=m.readIfPresent()}catch{}return e?{policy:s(e.delegation),favorites:v(e).map(l)}:y}function p(e){return e.policy.allow==="all"&&e.policy.deny.length===0}function E(e=d()){return p(e)?()=>!0:o=>i(e.policy,l(o),e.favorites)}function b(e=d(),o=f.peek()){let r=[...o.routes.flatMap(n=>n.models.map(g=>l({backend:n.backend,provider:n.provider,model:g}))),...e.favorites].filter(n=>i(e.policy,n,e.favorites));return[...new Set(r)].sort()}function h(e,o){if(e==="claude")return o.model;if(o.provider)return`${o.provider}/${o.model}`;try{return l(u(o.model,"pi"))}catch{return o.model}}function M(e,o){let t=e.parent;return!t?.model||t.backend!==e.backend?!1:l(t)===o}function $(e,o){let t=b(o);if(!t.length)return`Model "${e}" is not available for delegation, and no model is; omit model to use the default.`;let r=t.slice(0,a).join(", "),n=t.length>a?`, and ${t.length-a} more`:"";return`Model "${e}" is not available for delegation. Choose one of: ${r}${n}; or omit model to use the default.`}function N(e){let o=c(e.model);if(!o.model)return;let t=d();if(p(t))return;let r=h(e.backend,{...o,model:o.model});if(!(M(e,r)||i(t.policy,r,t.favorites)))throw new Error($(r,t))}export{E as a,N as b};
|
|
@@ -0,0 +1,70 @@
|
|
|
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{e as Vt,g as rn,h as A,i as sn}from"./chunk-5A6CA5TM.js";import{a as Wt}from"./chunk-TCAEECDI.js";import{a as Mt,b as Lt}from"./chunk-2YTYYG4K.js";import{a as Xt,b as Yt,c as Zt,d as ee,e as Jt,f as Kt,g as Qt,i as en}from"./chunk-ZFPMIQA3.js";import{a as tn}from"./chunk-EE3WT25T.js";import{a as nn,c as on}from"./chunk-IKLTEWA3.js";import{a as Nt,b as je}from"./chunk-LEAV3FFG.js";import{a as an}from"./chunk-2ATTYCRJ.js";import{g as te}from"./chunk-7GEBDPTT.js";import{a as Ut,d as Ht,e as Bt}from"./chunk-KUDK7GPS.js";import{a as X}from"./chunk-LCKVYFMD.js";import{a as me,e as Xe}from"./chunk-XPPZ6Y3X.js";import{d as Te,k as Ft,v as qt,w as zt,x as ze,z as fe}from"./chunk-BUZQBTV2.js";import{a as Ot,e as pe}from"./chunk-STCNHXPJ.js";import{c as Dt}from"./chunk-STUHNKQS.js";import{a as F}from"./chunk-NRD57ICT.js";import{K as n}from"./chunk-W34AK4SK.js";import{e as jt}from"./chunk-AVXDF7AG.js";import{e as S}from"./chunk-3CPIMAYX.js";import{e as h}from"./chunk-VBN2JSER.js";import{f as Gt,g as qe}from"./chunk-NXZS5PEW.js";import{d as Rt,i as _t,j as At,s as Pt}from"./chunk-Z24SBRJK.js";var Bo=[["permission",/\b(EACCES|EPERM)\b|permission denied/i],["disk",/\bENOSPC\b|no space left/i],["timeout",/\bETIMEDOUT\b|timed? ?out|killed by SIG/i],["network",/\b(ENOTFOUND|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENETUNREACH)\b|network|fetch failed/i],["npm",/npm (ERR|error)|exited with code|could not start/i]];function Wo(e){return Bo.find(([,t])=>t.test(e))?.[0]??"other"}function cn(e,t){return Math.max(0,Math.round((t-e)/1e3))}function Re(e,t=new Date){return{type:"upgrade",at:t.toISOString(),...e}}function Go(e,t){let o=cn(Date.parse(e.startedAt),Date.now()),{from:r,to:i,method:a}=e;if(t===null){ze(l=>({...l,pendingUpgrade:e})),fe(Re({from:r,to:i,method:a,stage:"installed",durationS:o,failure:null}));return}let c={class:Wo(t),message:me(t)};fe(Re({from:r,to:i,method:a,stage:"failed",durationS:o,failure:c}),{urgent:!0})}function ln(e){return(t,o)=>{let r={from:F,to:t,startedAt:new Date().toISOString(),method:pe().serverAutoUpdate?"auto":"prompt"};e(t,i=>{try{Go(r,i)}catch{}o(i)})}}function Vo(e,t,o){if(e){let r=e.to===F?"confirmed":"unconfirmed",i=cn(Date.parse(e.startedAt),o);return Re({...e,stage:r,durationS:i,failure:null},new Date(o))}return!t||t===F?null:Re({from:t,to:F,method:"manual",stage:"version-changed",durationS:null,failure:null},new Date(o))}function zi(e=Date.now()){let t=zt(),o=Vo(t.pendingUpgrade,t.lastVersion,e);ze(r=>({...r,pendingUpgrade:null,lastVersion:F})),o&&fe(o)}function qo(e){let t=e?.code;return t==="EACCES"||t==="EPERM"?"permission":e instanceof SyntaxError?"parse":typeof t=="string"&&t.startsWith("E")?"io":"other"}function Xi(e){let t=e.error instanceof Error?e.error.message:String(e.error);fe({type:"migration_failure",at:new Date().toISOString(),migration:e.migration.replace(/[^A-Za-z0-9._:/@[\]-]/g,"_").slice(0,80),errorClass:qo(e.error),message:me(t)})}import*as Oe from"node:fs";import*as Qe from"node:os";import{spawn as nr}from"node:child_process";var Y=class extends Error{failure;detail;constructor(t,o){super(o?`${t}: ${o}`:t),this.failure=t,this.detail=o,this.name="UpdateLookupError"}};function ne(e,t){let o=t?.trim();return{status:"error",reason:"check_failed",failure:e,...o?{detail:me(o)}:{}}}function _e(e){return e instanceof Y?ne(e.failure,e.detail):e instanceof Error?ne(`exception:${e.name}`,e.message):ne(`exception:${typeof e}`,String(e))}var un={available:null,state:"idle"},E=un,N=null;function dn(){return E}function Ki(e,t){let o=N;N=null,o?.(null),N=t,E={available:e,state:"prompting"}}function pn(e){let t=N;return t?(N=null,t(e),!0):!1}function Qi(e){N=null,E=e==="apply"?{available:E.available,state:"waiting"}:un}function mn(e){let t=N;N=null,t?.(null),E={available:e,state:"waiting",auto:!0}}function fn(){return E.auto?{auto:!0}:{}}function hn(){E={available:E.available,state:"installing",...fn()}}function gn(){E={available:E.available,state:"restarting",...fn()}}function he(e){E={available:E.available,state:"failed",error:e}}var zo=15e3,bn=Symbol("timed out"),Xo=/^\d+\.\d+\.\d+(?:-\d+)?$/;function Ye(e){return{status:"available",update:{version:e}}}async function Yo(e){let t,o=new Promise(r=>{t=setTimeout(()=>r(bn),zo),t.unref?.()});try{return await Promise.race([Promise.resolve().then(e),o])}finally{clearTimeout(t)}}var Ae=class{deps;inFlight=null;pending=null;latestVersion=null;promptFailure=null;decision=Promise.resolve(null);constructor(t){this.deps=t}check(){return this.inFlight?this.inFlight:(this.inFlight=this.discover().catch(_e).finally(()=>{this.inFlight=null}),this.inFlight)}async checkAndWait(){return await this.check(),{action:await this.decision,latestVersion:this.latestVersion}}skipReason(){if(pe().serverUpdateDisable)return"disabled";if(this.deps.isDevMode())return"dev_mode";let{state:t}=dn();return t==="waiting"||t==="installing"||t==="restarting"?"update_in_progress":null}async discover(){let t=this.skipReason();return t?{status:"skipped",reason:t}:this.lookup()}async lookup(){let t=await Yo(this.deps.getLatest);if(t===bn)return ne("timeout");if(!t||!Xo.test(t))return ne("bad_version",t??void 0);let o=this.skipReason();return o?{status:"skipped",reason:o}:(this.latestVersion=t,this.resolveVersion(t))}resolveVersion(t){if(Wt(t,F)<=0)return this.current();let o=this.deps.loadState()??{};return o.skippedVersion===t?{status:"skipped",reason:"version_skipped"}:pe().serverAutoUpdate?this.autoInstall(t,o):this.pending?.version===t?Ye(t):this.openPrompt(t,o)}autoInstall(t,o){this.deps.saveState({...o,lastCheckedAt:this.deps.now()}),this.pending=null,mn(t);try{this.deps.installWhenIdle(t)}catch(r){return he(r instanceof Error?r.message:String(r)),this.decision=Promise.resolve(null),_e(r)}return this.decision=Promise.resolve("apply"),{...Ye(t),reason:"auto_install"}}current(){return this.pending&&(this.pending=null,pn("cancel"),this.decision=Promise.resolve(null)),{status:"current"}}async openPrompt(t,o){let r={...o,lastCheckedAt:this.deps.now(),lastPromptedVersion:t};this.deps.saveState(r);let i=this.deps.prompt.ask({latestVersion:t});return this.pending={version:t,answer:i},this.promptFailure=null,this.decision=this.handleDecision(this.pending,r),await Promise.resolve(),this.promptFailure??Ye(t)}async handleDecision(t,o){try{let r=await t.answer;return this.pending!==t?null:this.acceptChoice(r,t.version,o)}catch(r){return this.failDecision(t,r)}finally{this.pending===t&&(this.pending=null)}}failDecision(t,o){return this.pending!==t||(this.promptFailure=_e(o),he(o instanceof Error?o.message:String(o))),null}acceptChoice(t,o,r){return t==="apply"&&(this.deps.saveState({...r,skippedVersion:void 0}),this.deps.installWhenIdle(o)),t==="skip"&&this.deps.saveState({...r,skippedVersion:o}),t}};import{execFile as Zo}from"node:child_process";var Jo=1024*1024;function Ko(e,t,o,r,i){let a=t&&typeof t.code=="number"?t.code:t?null:0,c=t?.signal??null,l=!!t&&(t?.killed===!0||c==="SIGTERM")&&i!==void 0;e({ok:a===0,code:a,signal:c,timedOut:l,stdout:o,stderr:r,...t&&typeof t.code=="string"?{error:t.message}:{}})}function oe(e,t=[],o={}){return new Promise(r=>{let i=Zo(e,[...t],{cwd:o.cwd,shell:o.shell,env:o.env??process.env,timeout:o.timeoutMs,killSignal:"SIGTERM",maxBuffer:o.maxBuffer??Jo,encoding:"utf8",windowsHide:!0},(a,c,l)=>Ko(r,a,c,l,o.timeoutMs));o.stdin!==void 0?i.stdin?.end(o.stdin):i.stdin?.end()})}function ca(e,t={}){let o=process.platform==="win32"?process.env.ComSpec??"cmd.exe":"/bin/sh",r=process.platform==="win32"?"/c":"-c";return oe(o,[r,e],t)}import*as re from"fs";import*as Pe from"path";var Ze=Pe.join(At,"update-state.json");function wn(){try{return JSON.parse(re.readFileSync(Ze,"utf8"))}catch{return null}}function In(e){let t=Pe.dirname(Ze);re.mkdirSync(t,{recursive:!0}),re.writeFileSync(Ze,JSON.stringify(e,null,2))}var ge="server-update",Qo=5*6e4,se=null;function De(e){let t=e.now??Date.now();se={phase:e.phase??null,expiresAt:t+Qo}}function Je(){se=null}function Sn(e=Date.now()){return se?e>=se.expiresAt?(se=null,null):{phase:se.phase}:null}function ha(e=Date.now()){return Sn(e)!==null}var yn=160;function er(e){let t=e.replace(/\s+/g," ").trim();return t?t.length>yn?`${t.slice(0,yn)}\u2026`:t:"(no text)"}async function ga(e){let t=Sn()?.phase??"restart",o=t===ge;if(e.interactive){let i={type:"interactive-reply",conduit:e.channel,sessionId:""},a=o?S("startup.updateHold"):S("startup.rebuildHold",{phase:t});await e.adapter.postMessage(i,{text:`${X.warning} ${a}`}).catch(()=>{});return}let r={channel:e.channel,preview:er(e.text)};await Vt(e.adapter,{level:"warning",title:o?S("notice.serverUpdate.title"):S("notice.rebuild.title"),text:o?S("startup.updateHoldDropped",r):S("startup.rebuildHoldDropped",{phase:t,...r})}).catch(()=>{})}var tr=6e4,xn={isIdle:()=>!0,onIdle:()=>()=>{}};function vn(e,t,o={}){let r=o.supervised??(()=>!!process.send),i=o.renewMs??tr,a=null,c=!1,l=null,f=(w,g)=>{if(clearInterval(w),c=!1,g!==null){Je(),he(g);return}gn(),r()?De({phase:ge}):Je()},m=()=>{if(c||a===null||!e.isIdle())return;let w=a;a=null,l?.(),l=null,c=!0,De({phase:ge});let g=setInterval(()=>De({phase:ge}),i);g.unref?.(),hn();let z=!1,de=L=>{z||(z=!0,f(g,L))};try{t(w,de)}catch(L){de(L instanceof Error?L.message:String(L))}};return w=>{if(a=w,e.isIdle()){m();return}l??=e.onIdle(m)}}function or(){let e=process.env.CORTEX_REPO;if(!e)return!1;try{return Oe.existsSync(e)&&Oe.statSync(e).isDirectory()}catch{return!1}}async function rr(){let e=qe(["view","@cortex-agent/server","version"]),t=await oe(e.command,e.args,{shell:e.shell,timeoutMs:15e3,cwd:Qe.tmpdir()});if(!t.ok)throw sr(t);return t.stdout.trim()||null}function sr(e){return e.timedOut?new Y("timeout",Ke(e.stderr)):e.error?new Y("npm_spawn",e.error):new Y(`npm_exit:${e.code??e.signal}`,Ke(e.stderr))}var ir=2e3;function Ke(e){return e.trim().split(`
|
|
5
|
+
`).slice(-6).join(`
|
|
6
|
+
`).trim()}function ar(e,t,o){let r=t!==null?`killed by ${t}`:`exited with code ${e}`,i=Ke(o);return i?`npm install -g ${r}
|
|
7
|
+
${i}`:`npm install -g ${r}`}function cr(e,t){let o=qe(Gt(["install","-g",`@cortex-agent/server@${e}`])),r=nr(o.command,o.args,{shell:o.shell,detached:!0,stdio:["ignore","ignore","pipe"],cwd:Qe.tmpdir()}),i="";r.stderr?.on("data",a=>{i.length<ir&&(i+=String(a))}),r.stderr?.unref?.(),r.on("error",a=>t(`npm install -g could not start: ${a.message}`)),r.on("exit",(a,c)=>t(a===0?null:ar(a,c,i))),r.unref()}function lr(){return new Date().toISOString()}function ja(e){return new Ae({prompt:e.prompt,getLatest:e.getLatest??rr,installWhenIdle:e.installWhenIdle??vn(e.idle??xn,ln(cr)),loadState:e.loadState??wn,saveState:e.saveState??In,now:e.now??lr,isDevMode:or})}import{readFileSync as $n,existsSync as ur}from"fs";import*as kn from"path";var U=h("machine-registry"),ie=kn.join(_t,"machines.json"),be={},En=!1,Me=null,Z=null;function dr(e,t){if(typeof t.cortexPath!="string"||typeof t.gpuCount!="number")throw new Error(`Invalid machine entry "${e}": requires cortexPath (string) and gpuCount (number)`);let o=t.clientConnection??"direct";if(o!=="direct"&&o!=="ssh-reverse")throw new Error(`Invalid machine entry "${e}": clientConnection must be direct or ssh-reverse`);if(o==="ssh-reverse"&&!t.ssh?.trim())throw new Error(`Invalid machine entry "${e}": ssh-reverse requires ssh`);if(t.clientReversePort!==void 0){if(o!=="ssh-reverse")throw new Error(`Invalid machine entry "${e}": clientReversePort requires ssh-reverse`);if(!Number.isInteger(t.clientReversePort)||t.clientReversePort<1024||t.clientReversePort>65535)throw new Error(`Invalid machine entry "${e}": clientReversePort must be an integer in 1024..65535`)}}var we=null;function La(e){we=e}var Cn=null;function Fa(e){Cn=e}function pr(e,t,o){e!==t?(U.info(`Hot-reload: machines changed [${e}] \u2192 [${t}]`),we?.(`${X.refresh} \`machines.json\` hot-reloaded: [${e}] \u2192 [${t}]`)):(U.info(`Hot-reload: ${o} machines reloaded`),we?.(`${X.refresh} \`machines.json\` hot-reloaded (${o} machines)`)),Cn?.()}function Tn(e=!0){try{let t=$n(ie,"utf-8"),o=JSON.parse(t);for(let[c,l]of Object.entries(o))dr(c,l);let r=Object.keys(be).sort().join(","),i=Object.keys(o).sort().join(","),a=En;be=o,En=!0,a?pr(r,i,Object.keys(o).length):U.info(`Loaded ${Object.keys(o).length} machines: ${Object.keys(o).join(", ")}`)}catch(t){let o=`[machine-registry] Failed to load ${ie}: ${t.message}`;if(e)throw new Error(o);U.error(o+" \u2014 keeping previous config"),we?.(`${X.warning} \`machines.json\` hot-reload FAILED \u2014 keeping previous config`)}}function Le(){return be}var mr=64;function fr(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=mr}function hr(e,t){try{let o=JSON.parse($n(ie,"utf-8"));return o[e]?(o[e].gpuCount=t,jt(ie,`${JSON.stringify(o,null,2)}
|
|
8
|
+
`),!0):!1}catch(o){return U.error(`Failed to persist gpuCount for ${e}: ${o.message}`),!1}}function jn(e,t){let o=be[e];if(!o||!fr(t))return"skipped";if(o.gpuCount===t)return"unchanged";if(!hr(e,t))return"skipped";let r=o.gpuCount;return o.gpuCount=t,U.info(`${e}: gpuCount ${r} \u2192 ${t} (client-reported)`),we?.(`${X.refresh} \`${e}\` gpuCount ${r} \u2192 ${t} (reported by its client)`),"updated"}function Na(){return Object.keys(be)[0]||"local"}function gr(){Z&&clearTimeout(Z),Z=setTimeout(()=>{Z=null,Tn(!1)},300)}function Ua(){Me?.close(),Me=Dt({label:"machines.json",filePath:ie,onChange:gr,warn:e=>U.error(e)})}function Ha(){Me?.close(),Me=null,Z&&clearTimeout(Z),Z=null}if(ur(ie))try{Tn()}catch(e){U.error(`Auto-load failed: ${e.message}`)}var br=3e4,wr=h("hook-bus"),Rn=[],_n=null;function Ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yr(e,t){return e===void 0?!0:Ir(e)?Object.entries(e).every(([o,r])=>Object.hasOwn(t,o)&&t[o]===r):!1}function Sr(e,t){let o=e.run.script===void 0?void 0:on(e.run.script,_n??nn());return{id:e.id,command:o===void 0?e.run.command:"node",args:o,timeoutMs:e.run.timeout===void 0?t:e.run.timeout*1e3,result:e.result}}function xr(e,t,o){return Rn.filter(r=>r.enabled!==!1).filter(r=>r.event===e).filter(r=>yr(r.matcher,t)).map(r=>Sr(r,o))}function et(e,t){let o=t instanceof Error?t.message:String(t);return wr.error(`Hook ${e} failed: ${o}`),{id:e,error:o}}function vr(e,t){return e.result==="stdout-as-prompt"?{id:e.id,result:t.trim()}:{id:e.id}}function Er(e,t,o){let r=vr(e,t);return o?{...r,stderr:o}:r}async function $r(e,t,o){try{let r=await tn({command:e.command,args:e.args,timeoutMs:e.timeoutMs,stdinPayload:t,env:o,label:e.id});return r.error?et(e.id,r.error):Er(e,r.stdout,r.stderr)}catch(r){return et(e.id,r)}}function qa(e){Rn=[...e.entries],_n=e.scriptDirs??null}function kr(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("Hook payload is not JSON-serializable");return t}async function tt(e,t,o){let r=[...xr(e,t,o?.defaultTimeoutMs??br),...o?.scopedHooks??[]];if(r.length===0)return[];let i;try{i=kr(t)}catch(c){return r.map(l=>et(l.id,c))}let a=[];for(let c of r)a.push(await $r(c,i,o?.env));return a}var nt=null;function An(e){nt=e}function Ya(e,t){if(!(!nt||!qt()))try{nt(e,t)}catch{}}function Ie(e,t=1){t<=0||A(o=>{o.features[e]=(o.features[e]??0)+t})}function Cr(e){A(t=>{t.messagesByChannel[e]=(t.messagesByChannel[e]??0)+1}),te("first_session")}function nc(e){return e.startsWith("slack")?"slack":e.startsWith("feishu")?"feishu":e.startsWith("tui")?"tui":"other"}function Tr(e){A(t=>{t.uiOps[e]=(t.uiOps[e]??0)+1})}var jr=new Set(["sessions.send","sessions.createAndSend"]),Rr=new Set(["sessions.create","sessions.createAndSend"]);function oc(e,t,o){Tr(e),t&&(jr.has(e)&&Cr(o??"other"),Rr.has(e)&&(Ie("session_created"),te("first_session")))}var _r={"/webhook/subagent":{start:"subagent_run"},"/webhook/team":{spawn:"worker_spawned"},"/webhook/board":{open:"board_opened"},"/webhook/waitpoint":{create:"waitpoint_created"}},Fe={day:"",ids:new Set};function Ar(e){let t=rn(Date.now());Fe.day!==t&&Object.assign(Fe,{day:t,ids:new Set});let o=typeof e=="string"?e:"";Fe.ids.has(o)||(Fe.ids.add(o),Ie("browser_session"))}function rc(e,t){let o=t??{};if(e==="/webhook/browser"&&o.action==="lease")return Ar(o.sessionId);let r=_r[e??""]?.[String(o.action)];r&&(Ie(r),r==="worker_spawned"&&te("first_worker"))}function sc(e=1){e<=0||(Ie("schedule_created",e),te("first_schedule"))}function Pn(e,t=process.env.CORTEX_MACHINE){e!==t&&(Ie("remote_client_connected"),te("first_remote_client"))}function Dn(){A(e=>{e.perf.remoteClientDisconnects+=1})}function ic(e){A(t=>sn(t,e))}var On=[];function ac(e,t=performance.now()){On.push([e,t])}function cc(e,t=performance.now()){let o={imports:Math.round(e)},r=e;for(let[i,a]of On)o[i]=Math.max(0,Math.round(a-r)),r=a;o.total=Math.round(t),A(i=>{i.perf.startups.push(o),i.perf.startups.length>10&&i.perf.startups.shift()})}var Pr=/^(?::[A-Za-z][A-Za-z0-9_]{0,30}|\*|[a-z][a-z-]{0,23})$/;function Dr(e){return!e||e.length>80||!e.startsWith("/")?null:e.split("/").filter(o=>o!=="").every(o=>Pr.test(o))?e:null}function Or(e){A(({perf:{web:t}})=>{t.loads+=1,e.ttfbMs!==null&&(t.ttfbMs[Te("webLoadMs",e.ttfbMs)]+=1),e.firstRenderMs!==null&&(t.firstRenderMs[Te("webLoadMs",e.firstRenderMs)]+=1),e.interactiveMs!==null&&(t.interactiveMs[Te("webLoadMs",e.interactiveMs)]+=1)})}function Mr(e,t){if(e.kind==="crash"){let{crashKind:r,errorName:i,message:a,stack:c,buildStamp:l,uptimeS:f}=e;return Xe({component:"web",kind:r,errorName:i,message:a,stack:c,buildStamp:l,uptimeS:f,client:t,route:Dr(e.route)})}if(e.kind!=="native_crash")return;let o=new Date(e.at);Xe({component:e.component,kind:"panic",errorName:"panic",message:e.message,stack:e.stack,buildStamp:e.appVersion,client:t,at:Number.isNaN(o.getTime())?new Date:o})}function Lr(e,t){if(e.kind==="load")return Or(e);if(e.kind==="sse_reconnect")return A(o=>{o.perf.sseReconnects+=e.count});Mr(e,t)}function lc(){An(Lr)}import*as Wn from"http";import*as Gn from"crypto";import*as Ln from"crypto";var Fr=h("reverse-stream"),Nr="/reverse",Mn=1e4,Ur=64,H=new Map;function Fn(e){if(!e)return null;let t=new URL(e,"http://placeholder");if(t.pathname!==Nr)return null;let o=t.searchParams.get("stream");return o&&/^[0-9a-f]{32}$/.test(o)?o:null}function Nn(e,t){if(H.size>=Ur)throw new Error(`too many pending reverse streams (${H.size})`);let o=Ln.randomBytes(16).toString("hex"),r,i,a=new Promise((l,f)=>{r=l,i=f}),c=setTimeout(()=>{H.delete(o),i(new Error(`device ${e} did not open a stream to ${t} within ${Mn}ms`))},Mn);return c.unref?.(),H.set(o,{device:e,target:t,resolve:r,reject:i,timer:c}),{id:o,socket:a}}function Un(e,t,o){let{id:r,socket:i}=Nn(e,`${t}:${o}`);return{id:r,message:{type:"open-stream",streamId:r,host:t,port:o},socket:i}}function pc(e,t){let{id:o,socket:r}=Nn(e,t);return{id:o,message:{type:"open-file-stream",streamId:o,path:t},socket:r}}function Hn(e,t){let o=H.get(e);return o?(clearTimeout(o.timer),H.delete(e),Fr.info(`stream ${e.slice(0,8)} claimed by ${o.device} \u2192 ${o.target}`),o.resolve(t),!0):!1}function Bn(e){let t=0;for(let[o,r]of H)r.device===e&&(clearTimeout(r.timer),H.delete(o),r.reject(new Error(`device ${e} disconnected before opening the stream`)),t++);return t}var y=h("client-manager"),rt=null;function Sc(e){rt=e}var ye=null;function xc(e){ye=e}var $=new Map,P=new Map,J=null,Ne=null,st=null,ot=null,Vn="Server shutting down",Hr=15e3,Br=12e4,Wr=3e4;function qn(e,t){t!==Vn&&Dn(),tt("cortex:client.disconnected",t?{device:e,reason:t}:{device:e}).catch(()=>{})}function Gr(e,t){for(let[o,r]of P)r.device===e&&(clearTimeout(r.timer),r.reject(t),P.delete(o))}function it(e,t){$.delete(e),y.info(`Device disconnected: ${e}${t?` (${t})`:""}`),qn(e,t);let o=Bn(e);o>0&&y.info(`cancelled ${o} pending reverse stream(s) for ${e}`),Gr(e,new Error(`Device "${e}" disconnected${t?` (${t})`:""}`)),ye?.onDeviceGone(e)}function zn(e){let t=$.get(e);if(!t)throw new Error(`Device "${e}" is not online`);if(t.ws.readyState!==Mt.default.OPEN)throw it(e,"WebSocket is not open"),new Error(`Device "${e}" WebSocket is not open`);return t.ws}function Vr(e){return!!e&&(e==="::1"||/^(::ffff:)?127\./.test(e))}function qr(e,t){if(!t)return e.close(4001,"Missing device name"),!1;if(!Object.hasOwn(Le(),t))return e.close(4005,"Unknown device"),!1;let o=$.get(t);return o&&o.ws!==e?(y.info(`Device ${t} already connected, rejecting new connection`),e.close(4002,"Device already connected"),!1):!0}function zr(e,t,o){let r=t.device;if(!qr(e,r))return null;let i=typeof t.bundleHash=="string"&&t.bundleHash?t.bundleHash:null,a=t.platform||"unknown";$.set(r,{device:r,platform:a,capabilities:t.capabilities||[],connectedAt:new Date,lastHeartbeat:new Date,bundleHash:i,ws:e}),y.info(`Device connected: ${r} (${a})`),Pn(r),tt("cortex:client.connected",{device:r}).catch(()=>{}),jn(r,typeof t.gpuCount=="number"?t.gpuCount:null);try{rt?.onHello(r,i)}catch(l){y.warn(`onHello hook failed for ${r}: ${l.message}`)}let c=typeof t.pid=="number"&&Number.isInteger(t.pid)&&t.pid>0?t.pid:null;try{ye?.onHello?.(r,{pid:c,loopback:Vr(o)})}catch(l){y.warn(`lifecycle hello hook failed for ${r}: ${l.message}`)}return r}function Xr(e){try{let t=JSON.parse(e);return t&&typeof t.type=="string"?t:null}catch{return null}}function Yr(e){let t=e.commandId?P.get(e.commandId):void 0;t&&(P.delete(e.commandId),clearTimeout(t.timer),e.success?t.resolve(e.data):t.reject(new Error(e.error||"Command failed")))}function Zr(e,t){try{rt?.onUpdateResult(e,{ok:!!t.ok,hash:typeof t.hash=="string"?t.hash:void 0,error:typeof t.error=="string"?t.error:void 0})}catch(o){y.warn(`onUpdateResult hook failed for ${e}: ${o.message}`)}}function Jr(e,t){if(e.type==="result")return Yr(e);if(t)if(e.type==="heartbeat"){let o=$.get(t);o&&(o.lastHeartbeat=new Date)}else e.type==="update-result"&&Zr(t,e)}function Kr(e,t){let o=e.req.headers[Ut],r=Array.isArray(o)?o[0]:o;if(Ht(Bt(),r))return t(!0);let i=e.req.socket?.remoteAddress||"unknown";y.warn(`WS auth rejected from ${i}: ${r?"invalid token":"missing token"}`),t(!1,401,"Unauthorized")}function Qr(e,t){let o=null;e.on("message",r=>{let i=Xr(r.toString());i?.type==="hello"?o=zr(e,i,t):i&&Jr(i,o)}),e.on("close",(r,i)=>{o&&$.get(o)?.ws===e&&it(o,i.toString().trim()||void 0)}),e.on("error",r=>{y.error(`WebSocket error for ${o||"unknown"}: ${r.message}`)})}function es(e,t){let o=Fn(t.url);if(!o)return Qr(e,t.socket?.remoteAddress);Hn(o,e)||(y.warn("reverse callback with an unknown stream id \u2014 closing"),e.close(4004,"Unknown stream"))}function ts(){let e=Date.now(),t=[...$.values()].filter(o=>e-o.lastHeartbeat.getTime()>Hr);for(let o of t)if($.get(o.device)===o){try{o.ws.close(4003,"Heartbeat timeout")}catch{}it(o.device,"Heartbeat timeout")}}function ns(e,t,o){let r=J;if(!r){t.write(`HTTP/1.1 503 Service Unavailable\r
|
|
9
|
+
\r
|
|
10
|
+
`),t.destroy();return}r.handleUpgrade(e,t,o,i=>r.emit("connection",i,e))}function vc(e,t,o={listen:!0}){if(J){y.warn("Already running");return}st=e,ye?.onStart(),J=new Lt.default({noServer:!0,verifyClient:Kr}),J.on("connection",es),J.on("error",r=>{y.error(`Server error: ${r.message}`)}),o.listen!==!1?os(e,t):y.info(`Client hub started (clients connect on port ${e})`),Ne=setInterval(ts,5e3)}function os(e,t){let o=Wn.createServer((r,i)=>{i.writeHead(426),i.end("Upgrade Required")});o.on("upgrade",(r,i,a)=>ns(r,i,a)),o.on("error",r=>y.error(`Client listener on port ${e} failed: ${r.message}`)),o.listen(e,t,()=>y.info(`WebSocket server started on port ${e}`)),ot=o}async function Ec(){Ne&&clearInterval(Ne),Ne=null;for(let[t,o]of P)clearTimeout(o.timer),o.reject(new Error("Client manager shutting down")),P.delete(t);for(let[,t]of $){try{t.ws.close(1001,"Server shutting down")}catch{}qn(t.device,Vn)}$.clear();let e=J;J=null,e&&e.close(),ot?.close(),ot=null,await ye?.onStop(),st=null,e&&y.info("WebSocket server stopped")}function Ue(){let e=[];for(let[,t]of $)e.push({device:t.device,platform:t.platform,connectedAt:t.connectedAt,lastHeartbeat:t.lastHeartbeat,capabilities:t.capabilities,bundleHash:t.bundleHash});return e}function Xn(e){return $.has(e)}function $c(){return st}function Yn(e,t){zn(e).send(JSON.stringify(t))}function Zn(e,t){let o;try{o=zn(e)}catch(a){return Promise.reject(a)}let r=Gn.randomBytes(8).toString("hex"),i=t.timeout||(t.action==="bash"?Br:Wr);return new Promise((a,c)=>{let l=setTimeout(()=>{P.delete(r),c(new Error(`Command to "${e}" timed out after ${i/1e3}s`))},i);P.set(r,{resolve:a,reject:c,timer:l,device:e});try{let f={type:"command",commandId:r,action:t.action,params:t.params};o.send(JSON.stringify(f))}catch(f){P.delete(r),clearTimeout(l),c(new Error(`Failed to send command to "${e}": ${f.message}`))}})}import*as Kn from"net";var B=h("device-port"),Jn="127.0.0.1",Qn="127.0.0.1",rs=32,ss=64,W=new Map;function eo(e,t,o){return`${e}|${t}|${o}`}function is(e,t,o){let r=!1,i=a=>{if(!r){r=!0,B.debug(`${o} closed: ${a}`);try{t.close()}catch{}try{e.destroy()}catch{}}};t.on("message",a=>{let c=Array.isArray(a)?Buffer.concat(a):Buffer.from(a);e.write(c)||(t.pause?.(),e.once("drain",()=>t.resume?.()))}),t.on("error",a=>i(`ws error: ${a.message}`)),t.on("close",()=>i("ws closed")),e.on("data",a=>{e.pause(),t.send(a,c=>{c?i(`send failed: ${c.message}`):e.resume()})}),e.on("error",a=>i(`tcp error: ${a.message}`)),e.on("close",()=>i("tcp closed")),e.resume()}var as=Yn;async function cs(e,t){let{device:o,remoteHost:r,remotePort:i}=e.info;if(t.pause(),t.setNoDelay(!0),e.connections.add(t),t.once("close",()=>e.connections.delete(t)),e.connections.size>ss){B.warn(`${o}:${i} \u2014 connection cap reached, refusing`),t.destroy();return}let a;try{a=Un(o,r,i)}catch(l){B.warn(`${o}:${i} \u2014 ${l.message}`),t.destroy();return}a.socket.catch(()=>{});try{as(o,a.message)}catch(l){B.warn(`${o}:${i} \u2014 cannot ask device to open a stream: ${l.message}`),t.destroy();return}let c;try{c=await a.socket}catch(l){B.warn(`${o}:${i} \u2014 ${l.message}`),t.destroy();return}if(t.destroyed){try{c.close()}catch{}return}is(t,c,`${o}:${i} stream ${a.id.slice(0,8)}`)}async function to(e,t){let o=Qn,r=eo(e,o,t),i=W.get(r);if(i)return i.info;if(W.size>=rs)throw new Error(`too many device ports open (${W.size})`);let a=Kn.createServer(),c={info:{device:e,remoteHost:o,remotePort:t,localPort:0,openedAt:new Date},server:a,connections:new Set};await new Promise((f,m)=>{a.once("error",m),a.listen(0,Jn,()=>{a.removeListener("error",m),f()})});let l=a.address();if(!l||typeof l=="string")throw a.close(),new Error("failed to bind a local port");return c.info.localPort=l.port,a.on("connection",f=>{cs(c,f)}),a.on("error",f=>B.warn(`listener for ${e}:${t} failed: ${f.message}`)),W.set(r,c),B.info(`device port ${Jn}:${l.port} \u2192 ${e} ${o}:${t}`),c.info}function ae(e,t){let o=Qn,r=eo(e,o,t),i=W.get(r);if(!i)return!1;W.delete(r);for(let a of i.connections)a.destroy();return i.connections.clear(),i.server.close(),B.info(`closed device port ${i.info.localPort} \u2192 ${e} ${o}:${t}`),!0}function Rc(){return[...W.values()].map(e=>({...e.info}))}function _c(){for(let e of[...W.values()])ae(e.info.device,e.info.remotePort)}import*as ve from"fs";import*as uo from"net";import*as po from"path";import{spawn as mo}from"child_process";import*as ce from"fs";import*as at from"path";import{execFile as ls,spawn as us}from"child_process";import{promisify as ds}from"util";var ps=ds(ls),no=h("browser-display");function ms(e){if(e.override)return{mode:"attached",display:e.override,takeover:"remote-desktop",reason:`display pinned by configuration (${e.override})`};if(e.platform==="linux"){if(e.envDisplay&&e.usableDisplays.includes(e.envDisplay))return{mode:"attached",display:e.envDisplay,takeover:"remote-desktop",reason:`$DISPLAY ${e.envDisplay} is reachable`};if(e.usableDisplays.length>0){let t=e.usableDisplays[0];return{mode:"attached",display:t,takeover:"remote-desktop",reason:`graphical session ${t} belongs to this user and is reachable`}}return e.hasXvfb?{mode:"virtual",display:null,takeover:"vnc-required",reason:"no reachable session; a virtual display will be created (a VNC bridge is needed to watch it)"}:{mode:"headless",display:null,takeover:"none",reason:"no graphical session and no Xvfb \u2014 the agent can browse, but nobody can take over"}}return e.platform==="darwin"||e.platform==="win32"?e.interactiveSession?{mode:"attached",display:null,takeover:"remote-desktop",reason:"running inside an interactive desktop session"}:{mode:"headless",display:null,takeover:"none",reason:e.platform==="win32"?"service session (Session 0) cannot show a window \u2014 CDP still works, takeover cannot":"no Aqua session (daemon context) \u2014 CDP still works, takeover cannot"}:{mode:"headless",display:null,takeover:"none",reason:`unsupported platform ${e.platform}`}}async function fs(){let e;try{e=await ce.promises.readdir("/tmp/.X11-unix")}catch{return[]}let t=typeof process.getuid=="function"?process.getuid():-1;return(await Promise.all(e.filter(r=>/^X\d+$/.test(r)).map(async r=>{try{let a=await ce.promises.stat(`/tmp/.X11-unix/${r}`);if(t>=0&&a.uid!==t)return null}catch{return null}let i=`:${r.slice(1)}`;return await hs(i)?i:null}))).filter(r=>r!==null).sort((r,i)=>Number(r.slice(1))-Number(i.slice(1)))}async function hs(e){let t=[["xdpyinfo",["-display",e]],["xset",["-display",e,"q"]]];for(let[o,r]of t){let i=await oo(o,r,3e3);if(i!=="missing")return i===0}return no.warn("neither xdpyinfo nor xset is installed \u2014 trusting X socket ownership"),!0}function oo(e,t,o){return new Promise(r=>{let i=us(e,t,{stdio:"ignore",timeout:o});i.once("error",a=>r(a.code==="ENOENT"?"missing":-1)),i.once("exit",a=>r(a??-1))})}async function ct(e){return await oo("which",[e],2e3)===0}async function gs(e,t=process.env){if(e==="darwin")try{let{stdout:o}=await ps("launchctl",["managername"],{encoding:"utf8",timeout:2e3});return o.trim()==="Aqua"}catch{return!1}if(e==="win32"){let o=t.SESSIONNAME;return!!o&&o.toLowerCase()!=="services"}return!1}function ro(e,t="/tmp"){for(let o=e;o<e+100;o++)if(!(ce.existsSync(at.join(t,`.X${o}-lock`))||ce.existsSync(at.join(t,".X11-unix",`X${o}`))))return o;return null}async function so(e=process.env){let t=process.platform,o=e.CORTEX_BROWSER_DISPLAY,r=t==="linux"&&!o,[i,a,c]=await Promise.all([r?fs():[],r?ct("Xvfb"):!1,o?!1:gs(t,e)]),l=ms({platform:t,override:o,envDisplay:e.DISPLAY,usableDisplays:i,hasXvfb:a,interactiveSession:c});return no.info(`display \u2192 ${l.mode}${l.display?` (${l.display})`:""}: ${l.reason}`),l}var D=h("managed-browser"),io=po.join(Rt,"browser","profile"),bs=9222,ws=600*1e3,ao=3e4,co=1e4,Is=99,ys=3,lt="browser stopped while starting",Ss=6e4,xs=3,b=null,Se=null,le=null,j=0,T=null,xe=[],R="server";async function ut(){j++,T&&(clearTimeout(T),T=null);try{return await go()}catch(e){throw j>0&&j--,e}}function dt(){j!==0&&(j--,j===0&&vs())}function fo(){return{running:!!b,refs:j,browser:b?{cdpEndpoint:b.cdpEndpoint,port:b.port,display:b.display,pid:b.pid}:null}}function Hc(){T&&(clearTimeout(T),T=null),j=0,le&&(le.cancelled=!0,He(le.procs,"SIGTERM")),ho()}function vs(){T&&clearTimeout(T),T=setTimeout(()=>{T=null,j===0&&(D.info("no browser sessions left \u2014 reclaiming Chrome"),ho())},ws),T.unref?.()}function ho(){let e=b;b=null,e&&He([e.proc,...e.xvfb?[e.xvfb]:[]],"SIGTERM")}function He(e,t){for(let o of e)try{o.kill(t)}catch{}}async function go(){return b||Se||(Se=Es().finally(()=>{Se=null}),Se)}async function Es(){let e={cancelled:!1,procs:[]};le=e;try{return await $s(e)}catch(t){throw He(e.procs,"SIGKILL"),t}finally{le===e&&(le=null)}}async function $s(e){let t=()=>{if(e.cancelled)throw new Error(lt)},o=await js();if(!o)throw new Error("no Chrome/Chromium found \u2014 install Google Chrome, or set CORTEX_BROWSER_BINARY to its path");let r=await so();t(),ve.mkdirSync(io,{recursive:!0});let i=await Rs(bs);t();let a,c=r.display;if(r.mode==="virtual"){let g=await Cs(e);a=g.proc,c=g.display}let l=[`--remote-debugging-port=${i}`,`--user-data-dir=${io}`,"--no-first-run","--no-default-browser-check","--disable-features=Translate","--remote-debugging-address=127.0.0.1"];r.mode==="headless"&&l.push("--headless=new"),process.platform==="linux"&&l.push("--password-store=basic");let f={...process.env};c?f.DISPLAY=c:delete f.DISPLAY,D.info(`launching ${o} on port ${i} (${r.mode}${c?` ${c}`:""})`);let m=mo(o,l,{env:f,stdio:"ignore",detached:!1});e.procs.push(m);let w=null;return m.on("exit",(g,z)=>ks(m,g,z)),m.on("error",g=>{w=g.message,D.error(`Chrome failed to spawn: ${g.message}`)}),await _s(i,()=>e.cancelled?lt:w?`Chrome failed to spawn: ${w}`:m.exitCode!==null||m.signalCode!==null?`Chrome exited during startup (code=${m.exitCode} signal=${m.signalCode})`:null),t(),b={cdpEndpoint:`http://127.0.0.1:${i}`,port:i,display:{...r,display:c},pid:m.pid??-1,proc:m,xvfb:a},D.info(`Chrome ready at ${b.cdpEndpoint} (pid ${b.pid})`),b}function ks(e,t,o){if(!b||b.proc!==e||(D.warn(`Chrome exited (code=${t} signal=${o})`),b.xvfb?.kill("SIGTERM"),b=null,j===0))return;let r=Date.now();if(xe=xe.filter(i=>r-i<Ss),xe.length>=xs){D.error("Chrome crashed repeatedly \u2014 giving up until the next acquire"),xe=[];return}xe.push(r),D.info(`${j} session(s) still need a browser \u2014 restarting`),go().catch(i=>D.error(`restart failed: ${String(i)}`))}async function Cs(e){let t=Is,o="no free display number";for(let r=0;r<ys;r++){let i=ro(t);if(i===null)break;let a=`:${i}`,c=mo("Xvfb",[a,"-screen","0","1920x1080x24","-nolisten","tcp","-displayfd","3"],{stdio:["ignore","ignore","ignore","pipe"]});e.procs.push(c);let l=await Ts(c);if(e.cancelled)throw new Error(lt);if(!l)return{proc:c,display:a};o=`${a}: ${l}`,D.warn(`Xvfb ${o}`),He([c],"SIGKILL"),t=i+1}throw new Error(`Xvfb could not start a virtual display (${o})`)}function Ts(e){return new Promise(t=>{let o=!1,r="",i=l=>{o||(o=!0,clearTimeout(a),t(l))},a=setTimeout(()=>i(`not ready within ${co}ms`),co),c=e.stdio[3];c?.on("data",l=>{r+=String(l),r.includes(`
|
|
11
|
+
`)&&i(null)}),c?.on("error",()=>{}),e.once("exit",(l,f)=>i(`exited (code=${l} signal=${f})`)),e.once("error",l=>i(l.message))})}async function js(e=process.env){if(e.CORTEX_BROWSER_BINARY)return ve.existsSync(e.CORTEX_BROWSER_BINARY)?e.CORTEX_BROWSER_BINARY:null;let t=process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:process.platform==="win32"?[`${e.ProgramFiles??"C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,`${e["ProgramFiles(x86)"]??"C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,`${e.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`]:[];for(let o of t)try{if(ve.existsSync(o))return o}catch{}for(let o of["google-chrome","google-chrome-stable","chromium","chromium-browser","chrome"])if(await ct(o))return o;return null}async function Rs(e){if(await lo(e))return e;for(let t=e+1;t<e+20;t++)if(await lo(t))return t;throw new Error(`no free CDP port near ${e}`)}function lo(e){return new Promise(t=>{let o=uo.createServer();o.once("error",()=>t(!1)),o.once("listening",()=>o.close(()=>t(!0))),o.listen(e,"127.0.0.1")})}async function _s(e,t){let o=Date.now()+ao,r="";for(;Date.now()<o;){let i=t();if(i)throw new Error(i);try{let a=await fetch(`http://127.0.0.1:${e}/json/version`,{signal:AbortSignal.timeout(2e3)});if(a.ok)return;r=`HTTP ${a.status}`}catch(a){r=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,250))}throw new Error(`Chrome did not expose CDP on ${e} within ${ao}ms (${r})`)}var bo=".cortex/browser/profile",Be="DevToolsActivePort";function As(e){return e==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:[]}var Ps=["google-chrome","google-chrome-stable","chromium","chromium-browser","chrome"],pt="Cortex Managed Browser",Ds=`
|
|
12
|
+
$ErrorActionPreference = "Stop"
|
|
13
|
+
$profile = Join-Path $env:USERPROFILE ".cortex\\browser\\profile"
|
|
14
|
+
$portFile = Join-Path $profile "${Be}"
|
|
15
|
+
New-Item -ItemType Directory -Force -Path $profile | Out-Null
|
|
16
|
+
if ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0) {
|
|
17
|
+
Get-Content -LiteralPath $portFile -TotalCount 1
|
|
18
|
+
exit 0
|
|
19
|
+
}
|
|
20
|
+
$candidates = @(
|
|
21
|
+
(Join-Path $env:ProgramFiles "Google\\Chrome\\Application\\chrome.exe"),
|
|
22
|
+
(Join-Path ([Environment]::GetEnvironmentVariable("ProgramFiles(x86)")) "Google\\Chrome\\Application\\chrome.exe"),
|
|
23
|
+
(Join-Path $env:LOCALAPPDATA "Google\\Chrome\\Application\\chrome.exe")
|
|
24
|
+
)
|
|
25
|
+
$chrome = $candidates | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
|
|
26
|
+
if (-not $chrome) {
|
|
27
|
+
foreach ($name in @("google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome")) {
|
|
28
|
+
$found = Get-Command $name -ErrorAction SilentlyContinue
|
|
29
|
+
if ($found) { $chrome = $found.Source; break }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (-not $chrome) { [Console]::Error.WriteLine("chrome-not-found"); exit 3 }
|
|
33
|
+
$user = (Get-CimInstance Win32_ComputerSystem).UserName
|
|
34
|
+
if (-not $user) { [Console]::Error.WriteLine("no-interactive-user"); exit 5 }
|
|
35
|
+
$current = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
|
36
|
+
if ($user -ine $current) { [Console]::Error.WriteLine("interactive-user-mismatch"); exit 6 }
|
|
37
|
+
$quote = [char]34
|
|
38
|
+
$arguments = "--remote-debugging-port=0 --remote-debugging-address=127.0.0.1 --user-data-dir=$quote$profile$quote --no-first-run --no-default-browser-check about:blank"
|
|
39
|
+
$action = New-ScheduledTaskAction -Execute $chrome -Argument $arguments
|
|
40
|
+
$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
|
|
41
|
+
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew
|
|
42
|
+
Register-ScheduledTask -TaskName "${pt}" -Action $action -Principal $principal -Settings $settings -Force | Out-Null
|
|
43
|
+
Start-ScheduledTask -TaskName "${pt}"
|
|
44
|
+
for ($i = 0; $i -lt 60; $i++) {
|
|
45
|
+
if ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0) { break }
|
|
46
|
+
Start-Sleep -Milliseconds 500
|
|
47
|
+
}
|
|
48
|
+
if (-not ((Test-Path -LiteralPath $portFile) -and (Get-Item -LiteralPath $portFile).Length -gt 0)) {
|
|
49
|
+
[Console]::Error.WriteLine("chrome-did-not-listen")
|
|
50
|
+
exit 4
|
|
51
|
+
}
|
|
52
|
+
Get-Content -LiteralPath $portFile -TotalCount 1
|
|
53
|
+
`.trim();function Os(e){let t=As(e).map(o=>` [ -f "${o}" ] && { CHROME="${o}"; }`).join(`
|
|
54
|
+
`);return[`PROFILE="$HOME/${bo}"`,`PORTFILE="$PROFILE/${Be}"`,'mkdir -p "$PROFILE"','if [ -s "$PORTFILE" ]; then head -1 "$PORTFILE"; exit 0; fi','CHROME=""',...t?[`if [ -z "$CHROME" ]; then :
|
|
55
|
+
${t}
|
|
56
|
+
fi`]:[],`for b in ${Ps.join(" ")}; do`,' [ -n "$CHROME" ] && break',' p=$(command -v "$b" 2>/dev/null) && CHROME="$p"',"done",'[ -n "$CHROME" ] || { echo "chrome-not-found" >&2; exit 3; }','nohup "$CHROME" --remote-debugging-port=0 --remote-debugging-address=127.0.0.1 --user-data-dir="$PROFILE" --no-first-run --no-default-browser-check --password-store=basic about:blank >/dev/null 2>&1 &','for _ in $(seq 1 60); do [ -s "$PORTFILE" ] && break; sleep 0.5; done','[ -s "$PORTFILE" ] || { echo "chrome-did-not-listen" >&2; exit 4; }','head -1 "$PORTFILE"'].join(`
|
|
57
|
+
`)}function wo(e){return e==="win32"?`powershell.exe -NoProfile -Command '${Ds}' </dev/null`:Os(e)}function mt(e){let t=`"$HOME/${bo}"`;return e==="win32"?[`powershell.exe -NoProfile -Command '${['$ErrorActionPreference = "SilentlyContinue"',`Stop-ScheduledTask -TaskName "${pt}" -ErrorAction SilentlyContinue`,"Get-CimInstance Win32_Process | Where-Object {",' $_.Name -eq "chrome.exe" -and $_.CommandLine -like "*.cortex*browser*profile*"',"} | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"].join(`
|
|
58
|
+
`)}' </dev/null >/dev/null 2>&1 || true`,`rm -f ${t}/${Be}`].join(`
|
|
59
|
+
`):[`pkill -f -- ${t} >/dev/null 2>&1 || true`,`rm -f ${t}/${Be}`].join(`
|
|
60
|
+
`)}var Ee=h("device-browser"),Ms=9e4,Ls=5e3,Fs=10*6e4,G=new Map;async function ht(e,t,o){let r=await Zn(e,{action:"bash",params:{command:t},timeout:o});if(r?.exitCode!==void 0&&r.exitCode!==0){let i=String(r.stderr??"").trim()||`exit ${r.exitCode}`;throw new Error(i)}return typeof r?.stdout=="string"?r.stdout:""}function Ns(e){let t=e.split(`
|
|
61
|
+
`).map(r=>r.trim()).filter(r=>/^\d+$/.test(r));if(t.length===0)return null;let o=Number(t[t.length-1]);return o>0&&o<=65535?o:null}function yo(e){return Ue().find(t=>t.device===e)?.platform??""}async function ft(e){try{return(await fetch(`${e}/json/version`,{signal:AbortSignal.timeout(Ls)})).ok}catch{return!1}}async function Io(e,t){let o=await ht(e,wo(t),Ms),r=Ns(o);if(r===null)throw new Error(`device ${e} reported no debugging port`);let i=await to(e,r);return{device:e,remotePort:r,cdpEndpoint:`http://127.0.0.1:${i.localPort}`,refs:0,idleTimer:null}}async function gt(e){let t=yo(e),o=G.get(e);if(o){if(o.idleTimer&&(clearTimeout(o.idleTimer),o.idleTimer=null),await ft(o.cdpEndpoint))return o.refs++,{device:e,remotePort:o.remotePort,cdpEndpoint:o.cdpEndpoint};Ee.info(`${e}: mapped browser no longer answers \u2014 relaunching`),ae(e,o.remotePort),G.delete(e)}let r=await Io(e,t);if(!await ft(r.cdpEndpoint)&&(Ee.info(`${e}: adopted debugging port ${r.remotePort} is dead \u2014 stopping and relaunching`),ae(e,r.remotePort),await ht(e,mt(t),3e4),r=await Io(e,t),!await ft(r.cdpEndpoint)))throw ae(e,r.remotePort),new Error(`device ${e} launched Chrome but its debugging port is unreachable`);return r.refs=1,G.set(e,r),Ee.info(`${e}: browser on device port ${r.remotePort} \u2192 ${r.cdpEndpoint}`),{device:e,remotePort:r.remotePort,cdpEndpoint:r.cdpEndpoint}}function Us(e){e.idleTimer=setTimeout(()=>{e.refs>0||(Ee.info(`${e.device}: no browser sessions left \u2014 reclaiming Chrome`),Hs(e.device).catch(t=>Ee.warn(`${e.device}: could not stop Chrome: ${t.message}`)))},Fs),e.idleTimer.unref?.()}function So(e){let t=G.get(e);t&&(t.refs=Math.max(0,t.refs-1),t.refs===0&&!t.idleTimer&&Us(t))}async function Hs(e){let t=G.get(e);t?.idleTimer&&clearTimeout(t.idleTimer),G.delete(e),t&&ae(e,t.remotePort),await ht(e,mt(yo(e)),3e4)}function Xc(){for(let e of G.values())e.idleTimer&&clearTimeout(e.idleTimer);G.clear()}var V=h("browser-broker"),Bs=10*6e4,Ws=15e3,Gs=5e3,k=class extends Error{code;hint;constructor(t,o,r){super(o),this.name="BrowserLeaseError",this.code=t,this.hint=r}};function We(e){return typeof e=="string"?e.trim():""}function Vs(e,t){let o=t.trim(),r="or run without --device to use the server's browser";return o.includes("chrome-not-found")?{message:`Chrome is not installed on ${e}`,hint:`install Google Chrome on ${e}, ${r}`}:o.includes("no-interactive-user")?{message:`nobody is logged in to the desktop on ${e}`,hint:`log in on ${e}, ${r}`}:o.includes("interactive-user-mismatch")?{message:`the Cortex client on ${e} runs as a different user than the desktop session`,hint:`run the Cortex client as the logged-in user on ${e}`}:o.includes("chrome-did-not-listen")?{message:`Chrome on ${e} did not open its debugging port in time`,hint:`close any Chrome window still using the Cortex profile on ${e} and retry`}:/timed out/i.test(o)?{message:`${e} did not answer while starting Chrome (${o})`,hint:`check that ${e} is awake and its Cortex client is connected`}:{message:`could not start Chrome on ${e}: ${o||"unknown error"}`}}function qs(e){let t=new Map,o=new Map,r=new Map,i=new Map,a=new Set,c=null;function l(){for(let s of a)try{s()}catch(u){V.warn(`listener failed: ${u.message}`)}}function f(s,u,d){let I=(s.get(u)??Promise.resolve()).catch(()=>{}).then(d),v=I.catch(()=>{});return s.set(u,v),v.then(()=>{s.get(u)===v&&s.delete(u)}),I}function m(){if(c)return c;try{c={bin:e.resolveBin(),env:e.baseEnv()}}catch(s){throw s instanceof Xt?new k("engine-missing",s.message,s.hint):s}return c}function w(s){s.idleTimer&&clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{if(s.idleTimer=null,s.takenOver){w(s);return}t.get(s.sessionId)===s&&(V.info(`${s.sessionId}: browser idle for ${Math.round(e.idleMs/6e4)} min \u2014 releasing`),f(o,s.sessionId,async()=>{t.get(s.sessionId)===s&&!s.takenOver&&await z(s)}))},e.idleMs),s.idleTimer.unref?.()}function g(s){s.lastUsedAt=e.now(),w(s)}async function z(s){if(s.idleTimer&&clearTimeout(s.idleTimer),s.idleTimer=null,t.get(s.sessionId)===s&&t.delete(s.sessionId),i.delete(s),s.holdsRef&&(s.holdsRef=!1,e.release(s.device)),l(),!(!s.cdpEndpoint||!c))for(let u of[["tab","close"],["close"]])await e.run(c.bin,ee(s.cdpEndpoint,s.abSession,u),c.env).catch(()=>{})}function de(s,u){return s.holdsRef&&(s.holdsRef=!1,e.release(s.device)),i.delete(s),s.state="error",s.error=u.hint?`${u.message} \u2014 ${u.hint}`:u.message,s.cdpEndpoint=null,l(),u}function L(s){if(s===R)return;let{state:u,online:d}=e.availability(s);if(u==="online")return;let p=d.length?`online devices: ${["server",...d].join(", ")}`:"no devices are online";throw u==="offline"?new k("device-offline",`device "${s}" is offline`,`start its Cortex client, or pick another device (${p})`):new k("unknown-device",`unknown device "${s}"`,`use one of: server${d.length?`, ${d.join(", ")}`:""}`)}function vt(s,u){if(u instanceof k)return u;let d=u?.message??String(u);if(s===R)return new k("chrome-failed",`could not start Chrome on the server: ${d}`);let{message:p,hint:I}=Vs(s,d);return new k("chrome-failed",p,I)}function Lo(s){return s===R?e.acquire(s):f(r,s,()=>e.acquire(s))}async function Fo(s){try{L(s.device),m(),s.cdpEndpoint=await Lo(s.device),s.holdsRef=!0,await kt(s),s.state="ready",s.error=void 0,i.set(s,e.now()),V.info(`${s.sessionId}: browser ready on ${s.device} (${s.abSession})`)}catch(u){throw de(s,vt(s.device,u))}l()}async function No(s){if(!(!(s.device===R||e.now()-(i.get(s)??0)>=Ws)||!s.cdpEndpoint))try{L(s.device);let d=await(s.device===R?e.refresh(s.device,s.cdpEndpoint):f(r,s.device,()=>e.refresh(s.device,s.cdpEndpoint)));i.set(s,e.now()),d!==s.cdpEndpoint&&(V.info(`${s.sessionId}: ${s.device} browser moved to ${d}`),s.cdpEndpoint=d,l())}catch(d){throw de(s,vt(s.device,d))}}function Et(s,u,d){return f(o,s,async()=>{let p=t.get(s);if(d&&p?.takenOver)throw new k("taken-over","the user is controlling this browser right now","wait for them to hand it back, or ask them; do not retry in a loop");let I=u||p?.device||R;if(p&&(p.device!==I||p.state==="error")){let Ho=p.takenOver;await z(p),p=void 0,Ho&&V.info(`${s}: switching device ends the takeover`)}if(p?.state==="ready")return await No(p),g(p),p;let v={sessionId:s,device:I,abSession:Zt(s,I),state:"starting",cdpEndpoint:null,holdsRef:!1,takenOver:!1,lastUsedAt:e.now(),idleTimer:null,refreshing:!1,refreshAgain:!1};return t.set(s,v),g(v),l(),await Fo(v),v})}function $t(s){let u=t.get(s);if(!u)throw new k("no-lease",`session ${s} has no browser`);return u}function Uo(s){let u=$t(s);if(u.state!=="ready"||!u.cdpEndpoint)throw new k("no-lease",`the browser for session ${s} is ${u.state}`);return u}async function Ce(s,u){let d=m(),p=()=>e.run(d.bin,ee(s.cdpEndpoint,s.abSession,u),d.env),I=await p();return I.code===0||!Kt(I.stderr)||(V.info(`${s.sessionId}: bound tab is gone \u2014 opening a new one`),(await e.run(d.bin,ee(s.cdpEndpoint,s.abSession,["tab","new"]),d.env)).code!==0)?I:(await kt(s),p())}async function kt(s){let u=m(),d=await e.run(u.bin,ee(s.cdpEndpoint,s.abSession,Jt),u.env).catch(p=>({code:-1,stdout:"",stderr:String(p)}));d.code!==0&&V.warn(`${s.sessionId}: could not set the viewport: ${d.stderr.trim().slice(0,200)}`)}async function Ct(s){if(s.refreshing){s.refreshAgain=!0;return}s.refreshing=!0;try{do{if(s.refreshAgain=!1,t.get(s.sessionId)!==s||s.state!=="ready"||!c)return;let u=async I=>{let v=await e.run(c.bin,ee(s.cdpEndpoint,s.abSession,["--json","get",I]),c.env);if(v.code===0)try{return We(JSON.parse(v.stdout)?.data?.[I])||void 0}catch{return}},[d,p]=[await u("url"),await u("title")];(d!==s.url||p!==s.title)&&(s.url=d,s.title=p,l())}while(s.refreshAgain)}finally{s.refreshing=!1}}function Tt(s){try{return JSON.parse(s)}catch{return null}}return{async leaseBrowser({sessionId:s,device:u}){let d=We(s);if(!d)throw new k("bad-request","no session id","cortex-browser must run inside a Cortex session (CORTEX_SESSION_ID is unset)");let p=await Et(d,We(u)||null,!0);return{device:p.device,cdpEndpoint:p.cdpEndpoint,abSession:p.abSession}},listBrowserSessions(){return[...t.values()].sort((s,u)=>u.lastUsedAt-s.lastUsedAt).map(s=>({sessionId:s.sessionId,device:s.device,abSession:s.abSession,state:s.state,...s.error?{error:s.error}:{},...s.url?{url:s.url}:{},...s.title?{title:s.title}:{},takenOver:s.takenOver,lastUsedAt:s.lastUsedAt}))},async runAgentBrowser(s,u){let d=await Et(s,null,!1),p=await Ce(d,u);return Ct(d),p},async streamPort(s){let u=t.get(s);if(!u||u.state!=="ready")return null;let d=Tt((await Ce(u,["--json","stream","status"])).stdout);if(d?.data?.enabled&&typeof d.data.port=="number")return d.data.port;let p=Tt((await Ce(u,["--json","stream","enable"])).stdout);return typeof p?.data?.port=="number"?p.data.port:null},setTakeover(s,u){let d=$t(s);d.takenOver!==u&&(d.takenOver=u,g(d),V.info(`${s}: browser ${u?"taken over by the user":"handed back to the agent"}`),l())},isTakenOver(s){return t.get(s)?.takenOver??!1},async insertText(s,u){let d=Uo(s),p=await Ce(d,["keyboard","inserttext",u]);if(p.code!==0)throw new Error(p.stderr.trim()||`agent-browser exited ${p.code}`)},noteBrowserCommand(s){let u=t.get(We(s));u&&(g(u),Ct(u))},agentBrowserRuntime(){return m()},onBrowserSessionsChanged(s){return a.add(s),()=>{a.delete(s)}},shutdown(){for(let s of t.values())s.idleTimer&&clearTimeout(s.idleTimer);t.clear(),a.clear()}}}async function zs(e){try{return(await fetch(`${e}/json/version`,{signal:AbortSignal.timeout(Gs)})).ok}catch{return!1}}function Xs(){return{async acquire(e){return e===R?(await ut()).cdpEndpoint:(await gt(e)).cdpEndpoint},release(e){e===R?dt():So(e)},async refresh(e,t){if(e===R){let o=fo().browser?.cdpEndpoint;if(o)return o;let r=(await ut()).cdpEndpoint;return dt(),r}return await zs(t)?t:(await gt(e)).cdpEndpoint},availability(e){let t=Ue().map(o=>o.device).sort();return Xn(e)?{state:"online",online:t}:{state:Object.hasOwn(Le(),e)?"offline":"unknown",online:t}},resolveBin:()=>Yt(),baseEnv:()=>Qt(),run:(e,t,o)=>en(e,t,{env:o}),now:()=>Date.now(),idleMs:Bs}}var bt=null;function q(){return bt??=qs(Xs()),bt}var nl=e=>q().leaseBrowser(e),ol=()=>q().listBrowserSessions();var rl=e=>q().streamPort(e),sl=(e,t)=>q().setTakeover(e,t),il=e=>q().isTakenOver(e),al=(e,t)=>q().insertText(e,t),cl=e=>q().noteBrowserCommand(e),ll=()=>q().agentBrowserRuntime();function ul(){bt?.shutdown()}import*as x from"node:fs";import*as O from"node:path";var K=h("project-store"),Ys=1e3;function xo(e,t,o){return[`# ${e} Status`,"","Updated: \u2014","","## Current Situation",t,"","## In Flight & New Variables","none","","## Blockers & Pending Decisions","none","","## Next Step",o,""].join(`
|
|
62
|
+
`)}var Zs=xo("general","Synthetic umbrella project \u2014 collects work not scoped to a specific project.","none"),Js=`# general
|
|
63
|
+
|
|
64
|
+
Synthetic umbrella project \u2014 always present. Created automatically by the system.
|
|
65
|
+
`,Ks=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,wt=class{projectsDir;watchEnabled;projects=[];initialized=!1;watcher=null;debounceTimer=null;constructor(t={}){this.projectsDir=t.projectsDir??Pt,this.watchEnabled=t.watchEnabled??!0}async initialize(){this.initialized||(this.scaffoldGeneral(),this.scan(),this.initialized=!0,this.watchEnabled&&this.startWatcher(),K.info(`ProjectStore initialized: ${this.projects.length} projects (${this.projectsDir})`))}list(){return[...this.projects]}get(t){return this.projects.find(o=>o.id===t)}exists(t){return this.projects.some(o=>o.id===t)}getDefault(){return this.projects.find(t=>t.kind==="general")}resolveFromMessage(t){if(!t)return this.getDefault();let o=t.match(/\[project:([^\]]+)\]/);if(o)return this.get(o[1])??this.getDefault();let r=t.toLowerCase(),i=null,a=0;for(let c of this.projects){if(c.kind==="general")continue;let l=c.id.toLowerCase();r.includes(l)&&c.id.length>a&&(i=c,a=c.id.length)}return i??this.getDefault()}refresh(){this.scan()}createProject(t){let o=typeof t=="string"?t.trim():"";if(!o||o==="general"||!Ks.test(o)||O.basename(o)!==o)return{ok:!1,code:"invalid-name",message:`Invalid project name: ${JSON.stringify(t)}`};let r=O.join(this.projectsDir,o);if(this.exists(o)||x.existsSync(r))return{ok:!1,code:"already-exists",message:`Project already exists: ${o}`};this.scaffoldProject(r,xo(o,"New project \u2014 not yet oriented.","Define mission.md and roadmap.md."),`# ${o}
|
|
66
|
+
|
|
67
|
+
${o} project.
|
|
68
|
+
`),K.info(`Created project at ${r}`),this.scan();let i=this.get(o);return i?{ok:!0,project:i}:{ok:!1,code:"invalid-name",message:`Project not registered after creation: ${o}`}}async removeProject(t){let o=this.get(t);return!o||o.kind!=="user"||!o.contextDir?!1:((await x.promises.lstat(o.contextDir).catch(()=>null))?.isDirectory()&&await x.promises.rm(o.contextDir,{recursive:!0,force:!0}),K.info(`Deleted project at ${o.contextDir}`),this.scan(),!0)}destroy(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.watcher&&(this.watcher.close(),this.watcher=null),this.initialized=!1}scaffoldGeneral(){let t=O.join(this.projectsDir,"general");x.existsSync(t)||(this.scaffoldProject(t,Zs,Js),K.info(`Scaffolded general project at ${t}`))}scaffoldProject(t,o,r){x.mkdirSync(t,{recursive:!0}),x.writeFileSync(O.join(t,"STATUS.md"),o,"utf8"),x.writeFileSync(O.join(t,"AGENTS.md"),r,"utf8")}scan(){let t=[];t.push(this.makeGeneralProject());try{let o=x.readdirSync(this.projectsDir,{withFileTypes:!0});for(let r of o)r.isDirectory()&&(r.name.startsWith(".")||r.name!=="general"&&t.push({id:r.name,name:r.name,kind:"user",contextDir:O.join(this.projectsDir,r.name)}))}catch{}this.projects=t}makeGeneralProject(){return{id:"general",name:"general",kind:"general",contextDir:O.join(this.projectsDir,"general")}}startWatcher(){try{this.watcher=x.watch(this.projectsDir,(t,o)=>{o&&(o.startsWith(".")||this.debouncedRescan())}),this.watcher.on("error",t=>{K.error(`Watcher error for ${this.projectsDir}:`,t.message)})}catch(t){K.error(`Failed to start watcher for ${this.projectsDir}:`,t)}}debouncedRescan(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan(),K.debug("Rescanned projects after directory change")},Ys)}},fl=new wt;import*as C from"node:fs";import*as _ from"node:path";var Qs=["mission.md","roadmap.md","STATUS.md"],ei=["experiments","knowledge","patterns","decisions"];function It(e){return Object.assign(new Error(e),{code:"not-found"})}function Ge(e){return Object.assign(new Error(e),{code:"invalid-args"})}function Eo(e,t){let o=e.projectStore.get(t);if(!o)throw It(`project not found: ${t}`);try{return C.realpathSync(o.contextDir)}catch{throw It(`project directory not found: ${t}`)}}function vo(e,t){return t===e||t.startsWith(e+_.sep)}function ti(e,t){if(_.isAbsolute(t))throw Ge(`absolute path not allowed: ${t}`);let o=_.resolve(e,t);if(!vo(e,o))throw Ge(`path escapes project root: ${t}`);let r;try{r=C.realpathSync(o)}catch{throw It(`file not found: ${t}`)}if(!vo(e,r))throw Ge(`path escapes project root: ${t}`);if(!C.statSync(r).isFile())throw Ge(`not a file: ${t}`);return r}async function wl(e,t){let o=Eo(e,t.projectId),r=Qs.flatMap(a=>{let c=_.join(o,a),l;try{l=C.statSync(c)}catch{return[]}return l.isFile()?[{name:a,sizeBytes:l.size,modifiedAt:l.mtime.toISOString()}]:[]}),i=ei.flatMap(a=>{let c=_.join(o,a),l;try{l=C.readdirSync(c,{withFileTypes:!0})}catch{return[]}let f=l.filter(m=>m.isFile()&&m.name.endsWith(".md")&&m.name!=="index.md"&&m.name!=="AGENTS.md").map(m=>{let w=C.statSync(_.join(c,m.name));return{name:m.name,sizeBytes:w.size,modifiedAt:w.mtime.toISOString()}}).sort((m,w)=>m.name.localeCompare(w.name));return[{name:a,entryCount:f.length,entries:f}]});return{projectId:t.projectId,files:r,dirs:i}}async function ni(e,t){let o=await oe("git",["diff","--numstat","HEAD","--",t],{cwd:e,timeoutMs:5e3,maxBuffer:1048576,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});if(!o.ok)return null;let i=o.stdout.split(`
|
|
69
|
+
`).find(m=>m.trim().length>0);if(!i)return{added:0,removed:0};let[a,c]=i.split(" "),l=Number(a),f=Number(c);return!Number.isFinite(l)||!Number.isFinite(f)?null:{added:l,removed:f}}var oi=/\b(?:task|manager|gate)\s+([0-9a-f]{4})\b/i;function ri(e){let t=oi.exec(e);return t?t[1].toLowerCase():null}function si(e){let t=[],o=new Map,r=null,i=0;for(let a of e.split(`
|
|
70
|
+
`)){if(a.startsWith(" ")){r&&t.push({line:i,commit:r.slice(0,8),taskRef:o.get(r)??null}),r=null;continue}let c=/^([0-9a-f]{40}) \d+ (\d+)(?: \d+)?$/.exec(a);if(c){r=c[1],i=Number(c[2]);continue}r&&a.startsWith("summary ")&&o.set(r,ri(a.slice(8)))}return t}async function ii(e,t){let o=await oe("git",["blame","--line-porcelain","HEAD","--",t],{cwd:e,timeoutMs:5e3,maxBuffer:8388608,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return o.ok?si(o.stdout):null}async function Il(e,t){let o=Eo(e,t.projectId),r=ti(o,t.path),i=C.statSync(r),a=C.readFileSync(r,"utf8"),[c,l]=an()?await Promise.all([ni(o,t.path),ii(o,t.path)]):[null,null];return{projectId:t.projectId,path:t.path,content:a,sizeBytes:i.size,modifiedAt:i.mtime.toISOString(),lineDiff:c,blame:l}}var $o={feishu:["FEISHU_APP_ID","FEISHU_APP_SECRET","FEISHU_DOMAIN","FEISHU_ENCRYPT_KEY","FEISHU_VERIFICATION_TOKEN"],slack:["SLACK_BOT_TOKEN","SLACK_SIGNING_SECRET","SLACK_APP_TOKEN"]},xl={feishu:["FEISHU_APP_ID","FEISHU_APP_SECRET"],slack:$o.slack},vl=["FEISHU_APP_ID","FEISHU_DOMAIN"],Q=n.string().min(1).max(4096).regex(/^[^\s'\\\u0000-\u001f\u007f]+$/,"Invalid credential characters"),ai=n.object({FEISHU_APP_ID:Q.nullable().optional(),FEISHU_APP_SECRET:Q.nullable().optional(),FEISHU_DOMAIN:n.enum(["feishu","lark"]).nullable().optional(),FEISHU_ENCRYPT_KEY:Q.nullable().optional(),FEISHU_VERIFICATION_TOKEN:Q.nullable().optional(),SLACK_BOT_TOKEN:Q.nullable().optional(),SLACK_SIGNING_SECRET:Q.nullable().optional(),SLACK_APP_TOKEN:Q.nullable().optional()}).strict(),ko=n.object({platform:n.enum(["feishu","slack"]),enabled:n.boolean().optional(),fields:ai}).strict().refine(e=>Object.keys(e.fields).every(t=>$o[e.platform].includes(t)),"Fields must belong to the selected platform");var yt=["openai-codex","anthropic"];function $l(e){return yt.includes(e)}var Co=n.object({sessionId:n.string().min(1),starred:n.boolean()}),To=n.object({sessionId:n.string().min(1),label:n.string().trim().min(1).max(60)});var ci=n.object({projectId:n.string().optional(),resumable:n.boolean().optional(),origin:n.enum(["direct","thread","scheduled"]).optional()}),li=n.object({sessionId:n.string(),compactSubagents:n.boolean().optional(),since:n.string().max(64).optional()}),ui=n.object({sessionId:n.string(),subagentId:n.string().min(1).max(512)}),di=n.object({sessionId:n.string(),ref:n.string().min(1).max(512)}),pi=n.object({sessionId:n.string().min(1)}),mi=n.object({projectId:n.string().optional(),paused:n.boolean().optional()}),fi=n.object({projectId:n.string().optional()}),hi=n.object({boardId:n.string()}),gi=n.object({boardId:n.string()}),bi=n.object({}),wi=n.object({sessionId:n.string().min(1)}),Ii=n.object({status:n.array(n.string()).optional(),limit:n.number().optional()}),yi=n.object({executionId:n.string()}),Si=n.object({projectId:n.string()}),xi=n.object({projectId:n.string(),path:n.string()}),vi=n.object({status:n.enum(["pending","approved","rejected","failed"]).optional()}),Ei=n.object({projectId:n.string()}),$i=n.object({projectId:n.string()});var Ul=n.object({}),Hl=n.object({projectId:n.string().nullish()}),ki=n.enum(["24h","7d","30d","90d"]),Ci=n.object({range:ki,page:n.number().int().min(0).max(400).optional(),projectId:n.string().nullish()}),Bl=Ci.extend({kind:n.enum(["tool","skill","mcp"]).optional()}),Wl=n.object({provider:n.string().nullish(),route:n.string().nullish()}),Gl=n.object({}),Vl=n.object({}),ql=n.object({flowId:n.string().min(1)}),zl=n.object({}),Xl=n.object({enabled:n.boolean(),name:n.string().trim().optional(),org:n.string().trim().optional(),email:n.string().trim().optional()}),Yl=n.object({}),Zl=Ft,Jl=n.object({}),Kl=n.object({}),Ql=n.object({machine:n.string().min(1)}),eu=n.object({}),tu=n.object({sessionId:n.string().min(1).optional(),agentName:n.string().min(1).nullable().optional()}),nu=n.object({}),ou=n.object({}),ru=n.object({}),su=n.object({}),iu=n.object({}),au=n.object({limit:n.number().int().positive().max(50).optional()}),cu=n.object({}),lu=n.object({}),uu=n.object({}),St=n.string().min(1).regex(je).nullable().optional(),du=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1),connection:St,authType:n.enum(["api_key","oauth"]),noticeId:n.string().min(1).optional()}),pu=n.object({backend:n.enum(["claude","pi"]),label:n.string().trim().min(1).max(64),provider:n.string().min(1).optional(),authType:n.enum(["api_key","oauth"]).optional()}),mu=n.object({backend:n.enum(["claude","pi"]),id:n.string().min(1).regex(je)}),fu=n.object({flowId:n.string().min(1),value:n.string(),promptId:n.number().int().nonnegative().optional()}),hu=n.object({flowId:n.string().min(1)}),gu=n.object({backend:n.enum(["claude","pi"]).optional()}),bu=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1),connection:St,authType:n.enum(["api_key","oauth"])}),Ve=n.string().min(1).regex(je),jo=n.array(n.string().min(1)),wu=n.object({}),Iu=n.discriminatedUnion("kind",[n.object({kind:n.literal("claude"),id:Ve,label:n.string().optional(),baseUrl:n.string().optional(),authStyle:n.enum(["x-api-key","bearer"]).optional(),billing:n.enum(["metered","subscription"]).optional(),models:jo.optional(),key:n.string().optional(),create:n.boolean().optional()}),n.object({kind:n.literal("pi-override"),provider:Ve,baseUrl:n.string(),key:n.string().optional(),create:n.boolean().optional()}),n.object({kind:n.literal("pi-custom"),provider:Ve,api:n.enum(Nt),baseUrl:n.string(),models:jo.min(1),key:n.string().optional(),create:n.boolean().optional()})]),yu=n.object({backend:n.enum(["claude","pi"]),id:Ve}),Su=n.object({name:n.string()}),xu=n.object({projectId:n.string().min(1)}),vu=n.object({sessionId:n.string().min(1)}),Eu=n.object({projectId:n.string().optional()}),$u=n.object({sessionId:n.string(),text:n.string(),attachments:n.array(n.object({name:n.string(),path:n.string(),size:n.number(),mimeType:n.string(),type:n.enum(["image","video","file","view"])})).optional()}),ku=n.object({sessionId:n.string()}),Cu=n.object({sessionId:n.string(),pendingId:n.string(),action:n.enum(["send","edit"])}),Tu=n.object({sessionId:n.string()}),ju=n.object({sessionId:n.string()}),Ru=n.object({sessionIds:n.array(n.string()).min(1).max(500)}),_u=n.object({sessionId:n.string(),agentName:n.string().min(1).nullable().optional()}),Do=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1).nullable(),model:n.string().min(1),thinking:n.string().min(1).nullable(),connection:n.string().min(1).nullable()}).strict(),$e=Do,Au=n.object({sessionId:n.string(),selection:$e}).strict(),Pu=n.object({requestId:n.string().min(1),answers:n.record(n.string(),n.string()),sessionId:n.string().min(1).optional()}),Du=n.object({requestId:n.string().min(1),approved:n.boolean(),feedback:n.string().optional()}),Ou=n.object({sessionId:n.string().min(1),decisionId:n.string().min(1),action:n.enum(["approve","explain","revise"]),message:n.string().optional()}),Mu=n.object({sessionId:n.string().regex(/^[\w-]+$/),ts:n.string().min(1),src:n.string().min(1)}),Lu=n.object({sessionId:n.string()}),Fu=n.object({sessionId:n.string(),turnIndex:n.number().int().min(0),text:n.string().min(1)}),Nu=n.object({projectId:n.string(),agentName:n.string().min(1).optional(),selection:$e.optional(),clean:n.boolean().optional(),text:n.string(),draftUploadId:n.string().uuid().optional(),attachments:n.array(n.object({name:n.string(),path:n.string(),size:n.number(),mimeType:n.string(),type:n.enum(["image","video","file"])})).optional()}),Uu=n.object({waitpointId:n.string().min(1)}),Hu=n.object({executionId:n.string()}),Bu=n.object({scheduleId:n.string()}),Wu=n.object({type:n.enum(["interval","daily","weekly","once"]),message:n.string().min(1),projectId:n.string().optional(),selection:$e.optional(),intervalMs:n.number().int().positive().optional(),time:n.string().regex(/^\d{2}:\d{2}$/).optional(),dayOfWeek:n.number().int().min(0).max(6).optional(),delay:n.number().int().positive().optional()}).superRefine((e,t)=>{e.type==="interval"&&e.intervalMs===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["intervalMs"],message:S("ui.schedule.intervalRequired")}),(e.type==="daily"||e.type==="weekly")&&e.time===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["time"],message:S("ui.schedule.timeRequired",{type:e.type})}),e.type==="weekly"&&e.dayOfWeek===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["dayOfWeek"],message:S("ui.schedule.dayOfWeekRequired")}),e.type==="once"&&e.delay===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["delay"],message:S("ui.schedule.delayRequired")})}),Gu=n.object({scheduleId:n.string(),message:n.string().min(1).optional(),projectId:n.string().optional(),selection:$e.optional(),intervalMs:n.number().int().positive().optional(),time:n.string().regex(/^\d{2}:\d{2}$/).optional(),dayOfWeek:n.number().int().min(0).max(6).optional()}),Ro=new Set(["__proto__","prototype","constructor"]),_o=120,Ti={boolean:n.boolean(),number:n.number().finite(),"number|null":n.number().finite().nullable(),"string[]":n.array(n.string()),"string|null":n.string().nullable()};function ji(e){let t=Ti[e.type];return!("validate"in e)||typeof e.validate!="function"?t:t.superRefine((o,r)=>{let i=e.validate(o);i&&r.addIssue({code:n.ZodIssueCode.custom,message:i})})}var Ri=Object.fromEntries(Object.entries(Ot).filter(([e])=>e!=="providerRateLimits").map(([e,t])=>[e,ji(t)]));function _i(e,t){for(let[o,r]of Object.entries(e))r===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:[o],message:"setting must not be undefined"})}var Ai=n.object(Ri).partial().strict().superRefine(_i),Vu=n.discriminatedUnion("section",[n.object({section:n.literal("budget"),project:n.string().min(1).nullish(),value:n.object({daily_usd:n.number().finite().positive(),monthly_usd:n.number().finite().positive()}).nullish()}).superRefine((e,t)=>{e.value==null&&!e.project&&t.addIssue({code:n.ZodIssueCode.custom,path:["value"],message:"a budget write without a value clears a per-project override and requires `project`"})}),n.object({section:n.literal("settings"),value:Ai}),n.object({section:n.literal("preferences"),value:n.object({lang:n.enum(["en","zh"])})})]),qu=n.object({provider:n.string().trim().min(1).max(_o).refine(e=>!Ro.has(e),"provider key is reserved"),windowType:n.string().trim().min(1).nullish(),windowLabel:n.string().trim().min(1).nullish(),account:n.string().trim().min(1).max(_o).refine(e=>!Ro.has(e),"account key is reserved").nullish(),enabled:n.boolean(),threshold:n.union([n.number().finite().gt(0).lte(1),n.null()]).optional()}).superRefine((e,t)=>{e.windowLabel&&!e.windowType&&t.addIssue({code:n.ZodIssueCode.custom,path:["windowType"],message:"windowType is required when windowLabel is set"}),e.account&&!e.windowType&&t.addIssue({code:n.ZodIssueCode.custom,path:["windowType"],message:"windowType is required when account is set"})}),zu=n.object({}),Pi=n.union([n.string(),n.number(),n.boolean(),n.null()]),Oo={event:n.string().min(1),matcher:n.string().optional(),matcherFilters:n.record(n.string(),Pi).optional(),script:n.string().min(1).optional(),command:n.string().min(1).optional(),timeoutSec:n.number().finite().positive().optional(),backends:n.array(n.enum(["claude","pi"])).optional(),requiresTool:n.string().min(1).optional(),result:n.enum(["stdout-as-prompt","none"]).optional(),enabled:n.boolean().optional()};function Mo(e,t){let o=e.script!==void 0,r=e.command!==void 0;o===r&&t.addIssue({code:n.ZodIssueCode.custom,path:["script"],message:S("ui.hook.exactlyOneRun")})}var Xu=n.object({id:n.string().min(1),...Oo}).superRefine(Mo),Yu=n.object({id:n.string().min(1),...Oo}).superRefine(Mo),Zu=n.object({id:n.string().min(1),enabled:n.boolean()}),Ju=n.object({id:n.string().min(1)}),Ku=n.object({id:n.string().min(1),payload:n.string()}),Di=Do.pick({backend:!0,provider:!0,model:!0}),Qu=n.object({backend:n.enum(["claude","pi"]),provider:n.string().min(1).nullable().optional(),model:n.string().min(1)}).strict(),ed=n.object({ref:Di,thinking:n.string().nullable()}).strict(),td=n.object({selection:$e}).strict(),Ao=n.array(n.string().trim().min(1).max(200)).max(200),nd=n.object({allow:n.union([n.literal("all"),n.literal("favorites"),Ao]),deny:Ao}).strict(),Oi=e=>new TextEncoder().encode(e).byteLength<=255,Mi=e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"),Li=n.string().max(240).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),Fi=n.string().min(1).refine(Oi).refine(Mi),xt=n.string().regex(/^[a-f0-9]{64}$/),Ni=n.object({kind:n.literal("agent"),name:Li,baseHash:xt}),od=n.object({target:Ni,pluginIds:n.array(Fi),acknowledgeMcp:n.boolean().optional()}),M=n.string().min(1).max(64).regex(/^(?!.*--)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/),ue={pluginId:M,skill:M},rd=n.object(ue),sd=n.object({...ue,content:n.string().max(512*1024),baseHash:xt}),id=n.object({...ue,description:n.string().min(1).max(1024)}),ad=n.object({...ue,toPluginId:M,toSkill:M}),cd=n.object(ue),ld=n.object(ue),ud=n.object({id:M,description:n.string().max(1024).optional()}),dd=n.object({id:M}),pd=n.object({id:M}),md=n.object({pluginId:M}),Po=n.record(n.string().min(1).max(200),n.string().max(4096).nullable()),fd=n.object({pluginId:M,servers:n.array(n.object({name:n.string().min(1).max(64).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),type:n.enum(["stdio","streamable-http","sse"]),command:n.string().max(1024).optional(),args:n.array(n.string().max(1024)).max(64).optional(),cwd:n.string().max(1024).optional(),url:n.string().max(2048).optional(),env:Po.optional(),headers:Po.optional()})).max(32),baseHash:xt}),ke=n.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),hd=n.object({name:ke}),gd=n.object({name:ke,body:n.record(n.string(),n.unknown())}),bd=n.object({name:ke,body:n.record(n.string(),n.unknown()),baseHash:n.string().optional()}),wd=n.object({name:ke}),Id=n.object({name:ke,text:n.string().max(65536)}),yd=n.object({id:n.string()}),Sd=n.object({projectId:n.string(),id:n.string()}),Ui=n.string().trim().min(1).max(1e3).refine(e=>!/[\r\n]/.test(e),{error:()=>S("ui.note.oneLine")}),Hi=n.object({projectId:n.string(),text:Ui}),xd=Hi.extend({id:n.string()}),vd=n.object({projectId:n.string(),id:n.string(),completed:n.boolean()}),Ed=n.object({projectId:n.string(),id:n.string()}),$d=n.object({projectId:n.string()}),kd=n.object({id:n.string(),feedback:n.string().optional()}),Cd=n.object({kind:n.enum(["soft","hard","force"])}),Td=n.object({provider:n.string().optional()}),jd=n.object({}),Rd=n.object({provider:n.enum(yt),connection:St,creditId:n.string().min(1).optional()}),_d=n.object({}),Ad=n.object({}),Pd=n.object({}),Dd=n.object({}),Od=n.object({}),Md=n.object({kind:n.enum(["reconnect-platform","add-machine"]),platform:n.enum(["slack","feishu"]).optional(),machineName:n.string().min(1).optional()}).superRefine((e,t)=>{e.kind==="reconnect-platform"&&e.platform===void 0&&t.addIssue({code:n.ZodIssueCode.custom,path:["platform"],message:"platform is required for kind=reconnect-platform"}),e.kind==="add-machine"&&(e.machineName===void 0||e.machineName.trim()==="")&&t.addIssue({code:n.ZodIssueCode.custom,path:["machineName"],message:S("ui.approval.machineNameRequired")})});export{$o as a,xl as b,vl as c,ko as d,yt as e,$l as f,Co as g,To as h,ci as i,li as j,ui as k,di as l,pi as m,mi as n,fi as o,hi as p,gi as q,bi as r,wi as s,Ii as t,yi as u,Si as v,xi as w,vi as x,Ei as y,$i as z,Ul as A,Hl as B,Ci as C,Bl as D,Wl as E,Gl as F,Vl as G,ql as H,zl as I,Xl as J,Yl as K,Zl as L,Jl as M,Kl as N,Ql as O,eu as P,tu as Q,nu as R,ou as S,ru as T,su as U,iu as V,au as W,cu as X,lu as Y,uu as Z,du as _,pu as $,mu as aa,fu as ba,hu as ca,gu as da,bu as ea,wu as fa,Iu as ga,yu as ha,Su as ia,xu as ja,vu as ka,Eu as la,$u as ma,ku as na,Cu as oa,Tu as pa,ju as qa,Ru as ra,_u as sa,$e as ta,Au as ua,Pu as va,Du as wa,Ou as xa,Mu as ya,Lu as za,Fu as Aa,Nu as Ba,Uu as Ca,Hu as Da,Bu as Ea,Wu as Fa,Gu as Ga,Vu as Ha,qu as Ia,zu as Ja,Xu as Ka,Yu as La,Zu as Ma,Ju as Na,Ku as Oa,Di as Pa,Qu as Qa,ed as Ra,td as Sa,nd as Ta,od as Ua,rd as Va,sd as Wa,id as Xa,ad as Ya,cd as Za,ld as _a,ud as $a,dd as ab,pd as bb,md as cb,fd as db,hd as eb,gd as fb,bd as gb,wd as hb,Id as ib,yd as jb,Sd as kb,Hi as lb,xd as mb,vd as nb,Ed as ob,$d as pb,kd as qb,Cd as rb,Td as sb,jd as tb,Rd as ub,_d as vb,Ad as wb,Pd as xb,Dd as yb,Od as zb,Md as Ab,dn as Bb,Ki as Cb,pn as Db,Qi as Eb,oe as Fb,ca as Gb,De as Hb,Je as Ib,ha as Jb,ga as Kb,zi as Lb,Xi as Mb,or as Nb,ja as Ob,Hc as Pb,La as Qb,Fa as Rb,Tn as Sb,Le as Tb,Na as Ub,Ua as Vb,Ha as Wb,pc as Xb,qa as Yb,tt as Zb,Ya as _b,Ie as $b,Cr as ac,nc as bc,oc as cc,rc as dc,sc as ec,ic as fc,ac as gc,cc as hc,lc as ic,Sc as jc,xc as kc,ns as lc,vc as mc,Ec as nc,Ue as oc,Xn as pc,$c as qc,Yn as rc,Zn as sc,to as tc,ae as uc,Rc as vc,_c as wc,Xc as xc,k as yc,nl as zc,ol as Ac,rl as Bc,sl as Cc,il as Dc,al as Ec,cl as Fc,ll as Gc,ul as Hc,fl as Ic,Eo as Jc,ti as Kc,wl as Lc,ri as Mc,Il as Nc};
|
|
@@ -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}from"./chunk-VPVSKJGX.js";import{e as R}from"./chunk-WHC7AYZD.js";var _=R(l(),1);import*as u from"node:fs";import*as a from"node:net";import*as T from"node:os";import*as n from"node:path";var s="CORTEX_UI_PORT",E=26789,N="CORTEX_UI_HOST",f="127.0.0.1",C="/tui",m=26999,I="CORTEX_CLIENT_PORT",x=["WEBHOOK_PORT","CORTEX_TUI_PORT"];function c(e){let r=(e??"").trim();if(!/^\d+$/.test(r))return null;let t=Number(r);return t>=1&&t<=65535?t:null}function i(e=process.env){let r=e.CORTEX_HOME?n.resolve(e.CORTEX_HOME):n.join(T.homedir(),".cortex");return n.join(r,"config",".env")}function O(e,r){try{return _.parse(u.readFileSync(e))[r]}catch{return}}function d(e=process.env,r=i(e)){let t=r===null?void 0:O(r,s);return c(e[s])??c(t)??E}function v(e=process.env,r=i(e)){return`http://127.0.0.1:${d(e,r)}`}function h(e=process.env,r=i(e)){return(e.CORTEX_CLIENT_TOKEN||O(r,"CORTEX_CLIENT_TOKEN")||"").trim()}var p=new Set;function A(e,r){for(let t of x)!e[t]||p.has(t)||(p.add(t),r(`${t} is no longer used and is ignored: every endpoint is served on ${s} (${d(e)}). Remove ${t} from your environment or ${i(e)}.`))}function P(e,r=f){return new Promise(t=>{let o=a.createServer();o.unref(),o.once("error",()=>t(!1)),o.listen({port:e,host:r,exclusive:!0},()=>o.close(()=>t(!0)))})}async function $(e=f,r=E,t=m){for(let o=r;o<=t;o++)if(await P(o,e))return o;throw new Error(`No free port between ${r} and ${t}; set ${s} to a free port and retry.`)}export{s as a,E as b,N as c,f as d,C as e,I as f,c as g,d as h,v as i,h as j,A as k,P as l,$ as m};
|
|
@@ -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{e as h}from"./chunk-NXZS5PEW.js";import{a as m,j as l}from"./chunk-Z24SBRJK.js";import*as o from"node:fs";import*as a from"node:path";var d=78,f=a.join(l,"app-stopped.json");function A(n,t,r,e){return r==="EADDRINUSE"?`Port ${n} is already in use by another process. Set CORTEX_UI_PORT in ${e} to a free port, then run \`cortex daemon restart\`.`:`Cannot listen on ${t}:${n} (${r??"unknown error"}). Check CORTEX_UI_PORT and CORTEX_UI_HOST in ${e}.`}function R(n,t=f){try{o.mkdirSync(a.dirname(t),{recursive:!0}),o.writeFileSync(t,JSON.stringify(n,null,2)+`
|
|
5
|
+
`)}catch{}}function _(n=f){try{let t=JSON.parse(o.readFileSync(n,"utf8"));return t&&typeof t.message=="string"?t:null}catch{return null}}function y(n=f){try{o.unlinkSync(n)}catch{}}import*as i from"path";var x="@cortex-agent/server";function O(n=process.execPath,t=m,r=process.platform){let e=r==="win32"?i.win32:i.posix,p=[e.dirname(n)],s=h(t,x,r);return s&&p.push(r==="win32"?s:e.join(s,"bin")),p}function w(n,t,r=process.platform){let e=r==="win32"?i.win32:i.posix,p=c=>{let u=e.normalize(c).replace(/[\\/]+$/,"");return r==="win32"?u.toLowerCase():u},s=n.split(e.delimiter).filter(Boolean),S=new Set(s.map(p));return[...t.filter(c=>!S.has(p(c))),...s].join(e.delimiter)}function C(){process.env.PATH=w(process.env.PATH??"",O())}export{d as a,A as b,R as c,_ as d,y as e,O as f,C as g};
|
|
@@ -0,0 +1,22 @@
|
|
|
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 Vt,A as Ut,B as Ot,D as At,F as kt,G as It,I as Pt,J as Ae,L as Mt,M as Lt,P as $t,Q as qt,R as Wt,S as Ht,T as Nt,X as jt,Z as x,aa as Dt,b as F,ba as Ft,ca as Gt,d as vt,da as Zt,i as Ct,j as de,k as Rt,l as bt,m as St,n as U,o as te,p as he,r as Et,t as Tt,u as Ve,w as xt,y as zt}from"./chunk-TMV2ZDOI.js";import{C as mt,H as gt,J as yt,e as ft,n as c,o as _t,p as je,q,s as wt,u as _,v as j,w as Oe}from"./chunk-W34AK4SK.js";import{c as zr,e as Ur}from"./chunk-WHC7AYZD.js";var Qt=zr(De=>{"use strict";var Jt=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,Ar=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Xt=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,kr=/\\([\u000b\u0020-\u00ff])/g,Ir=/([\\"])/g,Kt=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;De.format=Pr;De.parse=Mr;function Pr(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!Kt.test(r))throw new TypeError("invalid type");var o=r;if(e&&typeof e=="object")for(var n,i=Object.keys(e).sort(),a=0;a<i.length;a++){if(n=i[a],!Xt.test(n))throw new TypeError("invalid parameter name");o+="; "+n+"="+$r(e[n])}return o}function Mr(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?Lr(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),o=r!==-1?e.slice(0,r).trim():e.trim();if(!Kt.test(o))throw new TypeError("invalid media type");var n=new qr(o.toLowerCase());if(r!==-1){var i,a,s;for(Jt.lastIndex=r;a=Jt.exec(e);){if(a.index!==r)throw new TypeError("invalid parameter format");r+=a[0].length,i=a[1].toLowerCase(),s=a[2],s.charCodeAt(0)===34&&(s=s.slice(1,-1),s.indexOf("\\")!==-1&&(s=s.replace(kr,"$1"))),n.parameters[i]=s}if(r!==e.length)throw new TypeError("invalid parameter format")}return n}function Lr(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function $r(t){var e=String(t);if(Xt.test(e))return e;if(e.length>0&&!Ar.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(Ir,"\\$1")+'"'}function qr(t){this.parameters=Object.create(null),this.type=t}});var ke=class{constructor(e){this._client=e}async*callToolStream(e,r=Ae,o){let n=this._client,i={...o,task:o?.task??(n.isToolTask(e.name)?{}:void 0)},a=n.requestStream({method:"tools/call",params:e},r,i),s=n.getToolOutputValidator(e.name);for await(let l of a){if(l.type==="result"&&s){let d=l.result;if(!d.structuredContent&&!d.isError){yield{type:"error",error:new x(U.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(d.structuredContent)try{let h=s(d.structuredContent);if(!h.valid){yield{type:"error",error:new x(U.InvalidParams,`Structured content does not match the tool's output schema: ${h.errorMessage}`)};return}}catch(h){if(h instanceof x){yield{type:"error",error:h};return}yield{type:"error",error:new x(U.InvalidParams,`Failed to validate structured content: ${h instanceof Error?h.message:String(h)}`)};return}}yield l}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._client.getTaskResult({taskId:e},r,o)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,o){return this._client.requestStream(e,r,o)}};function Ie(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,o=t.properties;for(let n of Object.keys(o)){let i=o[n];r[n]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[n]=i.default),r[n]!==void 0&&Ie(i,r[n])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Ie(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Ie(r,e)}}function Or(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Bt=class extends Vt{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ft,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Mt,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",It,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ot,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ke(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Dt(this._capabilities,e)}setRequestHandler(e,r){let n=vt(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let i=Ct(n);if(typeof i!="string")throw new Error("Schema method literal must be a string");let a=i;if(a==="elicitation/create"){let s=async(l,d)=>{let h=F(Ht,l);if(!h.success){let A=h.error instanceof Error?h.error.message:String(h.error);throw new x(U.InvalidParams,`Invalid elicitation request: ${A}`)}let{params:f}=h.data;f.mode=f.mode??"form";let{supportsFormMode:R,supportsUrlMode:w}=Or(this._capabilities.elicitation);if(f.mode==="form"&&!R)throw new x(U.InvalidParams,"Client does not support form-mode elicitation requests");if(f.mode==="url"&&!w)throw new x(U.InvalidParams,"Client does not support URL-mode elicitation requests");let S=await Promise.resolve(r(l,d));if(f.task){let A=F(Ve,S);if(!A.success){let Y=A.error instanceof Error?A.error.message:String(A.error);throw new x(U.InvalidParams,`Invalid task creation result: ${Y}`)}return A.data}let m=F(Nt,S);if(!m.success){let A=m.error instanceof Error?m.error.message:String(m.error);throw new x(U.InvalidParams,`Invalid elicitation result: ${A}`)}let v=m.data,M=f.mode==="form"?f.requestedSchema:void 0;if(f.mode==="form"&&v.action==="accept"&&v.content&&M&&this._capabilities.elicitation?.form?.applyDefaults)try{Ie(M,v.content)}catch{}return v};return super.setRequestHandler(e,s)}if(a==="sampling/createMessage"){let s=async(l,d)=>{let h=F($t,l);if(!h.success){let v=h.error instanceof Error?h.error.message:String(h.error);throw new x(U.InvalidParams,`Invalid sampling request: ${v}`)}let{params:f}=h.data,R=await Promise.resolve(r(l,d));if(f.task){let v=F(Ve,R);if(!v.success){let M=v.error instanceof Error?v.error.message:String(v.error);throw new x(U.InvalidParams,`Invalid task creation result: ${M}`)}return v.data}let S=f.tools||f.toolChoice?Wt:qt,m=F(S,R);if(!m.success){let v=m.error instanceof Error?m.error.message:String(m.error);throw new x(U.InvalidParams,`Invalid sampling result: ${v}`)}return m.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let o=await this.request({method:"initialize",params:{protocolVersion:de,capabilities:this._capabilities,clientInfo:this._clientInfo}},Et,r);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!Rt.includes(o.protocolVersion))throw new Error(`Server's protocol version is not supported: ${o.protocolVersion}`);this._serverCapabilities=o.capabilities,this._serverVersion=o.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(o.protocolVersion),this._instructions=o.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(o){throw this.close(),o}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){Gt(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&Zt(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},he,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},jt,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},he,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},kt,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},At,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},xt,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},zt,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Ut,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},he,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},he,r)}async callTool(e,r=Ae,o){if(this.isToolTaskRequired(e.name))throw new x(U.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let n=await this.request({method:"tools/call",params:e},r,o),i=this.getToolOutputValidator(e.name);if(i){if(!n.structuredContent&&!n.isError)throw new x(U.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{let a=i(n.structuredContent);if(!a.valid)throw new x(U.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof x?a:new x(U.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let n=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}let o=r.execution?.taskSupport;(o==="required"||o==="optional")&&this._cachedKnownTaskTools.add(r.name),o==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let o=await this.request({method:"tools/list",params:e},Pt,r);return this.cacheToolMetadata(o.tools),o}_setupListChangedHandler(e,r,o,n){let i=Lt.safeParse(o);if(!i.success)throw new Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof o.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:s}=i.data,{onChanged:l}=o,d=async()=>{if(!a){l(null,null);return}try{let f=await n();l(null,f)}catch(f){let R=f instanceof Error?f:new Error(String(f));l(R,null)}},h=()=>{if(s){let f=this._listChangedDebounceTimers.get(e);f&&clearTimeout(f);let R=setTimeout(d,s);this._listChangedDebounceTimers.set(e,R)}else d()};this.setNotificationHandler(r,h)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Yt=Ur(Qt(),1);function er(t){if(t)try{return Yt.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function re(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Pe(t=fetch,e){return e?async(r,o)=>{let n={...e,...o,headers:o?.headers?{...re(e.headers),...re(o.headers)}:e.headers};return t(r,n)}:t}var Wr=5,Hr=[301,302,303,307,308];function Nr(t,e){return t.protocol===e.protocol&&t.hostname===e.hostname&&t.port===e.port?!0:t.hostname===e.hostname&&t.protocol==="http:"&&t.port===""&&e.protocol==="https:"&&e.port===""}function tr(t,e){let r=Hr.includes(t.status)?t.headers.get("location"):null;try{return r?new URL(r,e):void 0}catch{return}}function Me(t,e,r,o,n=0){let i=tr(o,e),a=o.status===307||o.status===308||(r?.method??"GET").toUpperCase()==="GET";if(!i||n===Wr||!a)return;let s=new URL(e);if(!((i.username||i.password)&&(i.username!==s.username||i.password!==s.password)||!Nr(s,i)))return Promise.resolve(o.body?.cancel()).then(()=>t(i,{...r,redirect:"manual"})).then(d=>Me(t,i,r,d,n+1)??d)}var rr=new WeakSet;function oe(t){let e=(r,o)=>(t??fetch)(r,o);return rr.add(e),e}function $(t=fetch){return rr.has(t)?t:(e,r)=>r?.redirect==="error"||r?.redirect==="manual"?t(e,r):Promise.resolve(t(e,{...r,redirect:"manual"})).then(o=>Me(t,e,r,o)??o)}function se(t,e){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";let r=t.url||e,o=tr(t,r);if(o)return o.username=o.password=o.search=o.hash="",o.protocol==="http:"&&new URL(r).protocol==="https:"?(o.protocol="https:",`Redirect to plain http not followed; try ${o.href} instead`):`Redirect to ${o.href} not followed`}var Fe;Fe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function jr(t){return(await Fe).getRandomValues(new Uint8Array(t))}async function Vr(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,o="";for(;o.length<t;){let n=await jr(t-o.length);for(let i of n)i<r&&(o+=e[i%e.length])}return o}async function Dr(t){return await Vr(t)}async function Fr(t){let e=await(await Fe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Ge(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await Dr(t),r=await Fr(e);return{code_verifier:e,code_challenge:r}}var O=_t().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:gt.custom,message:"URL must be parseable",fatal:!0}),ft}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),sr=Oe({resource:c().url(),authorization_servers:_(O).optional(),jwks_uri:c().url().optional(),scopes_supported:_(c()).optional(),bearer_methods_supported:_(c()).optional(),resource_signing_alg_values_supported:_(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:q().optional(),authorization_details_types_supported:_(c()).optional(),dpop_signing_alg_values_supported:_(c()).optional(),dpop_bound_access_tokens_required:q().optional()}),Ze=Oe({issuer:c(),authorization_endpoint:O,token_endpoint:O,registration_endpoint:O.optional(),scopes_supported:_(c()).optional(),response_types_supported:_(c()),response_modes_supported:_(c()).optional(),grant_types_supported:_(c()).optional(),token_endpoint_auth_methods_supported:_(c()).optional(),token_endpoint_auth_signing_alg_values_supported:_(c()).optional(),service_documentation:O.optional(),revocation_endpoint:O.optional(),revocation_endpoint_auth_methods_supported:_(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:_(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(c()).optional(),code_challenge_methods_supported:_(c()).optional(),client_id_metadata_document_supported:q().optional()}),Gr=Oe({issuer:c(),authorization_endpoint:O,token_endpoint:O,userinfo_endpoint:O.optional(),jwks_uri:O,registration_endpoint:O.optional(),scopes_supported:_(c()).optional(),response_types_supported:_(c()),response_modes_supported:_(c()).optional(),grant_types_supported:_(c()).optional(),acr_values_supported:_(c()).optional(),subject_types_supported:_(c()),id_token_signing_alg_values_supported:_(c()),id_token_encryption_alg_values_supported:_(c()).optional(),id_token_encryption_enc_values_supported:_(c()).optional(),userinfo_signing_alg_values_supported:_(c()).optional(),userinfo_encryption_alg_values_supported:_(c()).optional(),userinfo_encryption_enc_values_supported:_(c()).optional(),request_object_signing_alg_values_supported:_(c()).optional(),request_object_encryption_alg_values_supported:_(c()).optional(),request_object_encryption_enc_values_supported:_(c()).optional(),token_endpoint_auth_methods_supported:_(c()).optional(),token_endpoint_auth_signing_alg_values_supported:_(c()).optional(),display_values_supported:_(c()).optional(),claim_types_supported:_(c()).optional(),claims_supported:_(c()).optional(),service_documentation:c().optional(),claims_locales_supported:_(c()).optional(),ui_locales_supported:_(c()).optional(),claims_parameter_supported:q().optional(),request_parameter_supported:q().optional(),request_uri_parameter_supported:q().optional(),require_request_uri_registration:q().optional(),op_policy_uri:O.optional(),op_tos_uri:O.optional(),client_id_metadata_document_supported:q().optional()}),nr=j({...Gr.shape,...Ze.pick({code_challenge_methods_supported:!0}).shape}),ir=j({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:yt.number().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),ar=j({error:c(),error_description:c().optional(),error_uri:c().optional()}),or=O.optional().or(mt("").transform(()=>{})),Zr=j({redirect_uris:_(O),token_endpoint_auth_method:c().optional(),grant_types:_(c()).optional(),response_types:_(c()).optional(),client_name:c().optional(),client_uri:O.optional(),logo_uri:or,scope:c().optional(),contacts:_(c()).optional(),tos_uri:or,policy_uri:c().optional(),jwks_uri:O.optional(),jwks:wt().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Br=j({client_id:c(),client_secret:c().optional(),client_id_issued_at:je().optional(),client_secret_expires_at:je().optional(),issuer:c().optional().catch(void 0)}).strip(),cr=Zr.merge(Br),qo=j({error:c(),error_description:c().optional()}).strip(),Wo=j({token:c(),token_type_hint:c().optional()}).strip();function lr(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function ur({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),o=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var E=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},pe=class extends E{};pe.errorCode="invalid_request";var G=class extends E{};G.errorCode="invalid_client";var Z=class extends E{};Z.errorCode="invalid_grant";var B=class extends E{};B.errorCode="unauthorized_client";var fe=class extends E{};fe.errorCode="unsupported_grant_type";var _e=class extends E{};_e.errorCode="invalid_scope";var we=class extends E{};we.errorCode="access_denied";var W=class extends E{};W.errorCode="server_error";var me=class extends E{};me.errorCode="temporarily_unavailable";var ge=class extends E{};ge.errorCode="unsupported_response_type";var ye=class extends E{};ye.errorCode="unsupported_token_type";var ve=class extends E{};ve.errorCode="invalid_token";var Ce=class extends E{};Ce.errorCode="method_not_allowed";var Re=class extends E{};Re.errorCode="too_many_requests";var J=class extends E{};J.errorCode="invalid_client_metadata";var be=class extends E{};be.errorCode="insufficient_scope";var Se=class extends E{};Se.errorCode="invalid_target";var dr={[pe.errorCode]:pe,[G.errorCode]:G,[Z.errorCode]:Z,[B.errorCode]:B,[fe.errorCode]:fe,[_e.errorCode]:_e,[we.errorCode]:we,[W.errorCode]:W,[me.errorCode]:me,[ge.errorCode]:ge,[ye.errorCode]:ye,[ve.errorCode]:ve,[Ce.errorCode]:Ce,[Re.errorCode]:Re,[J.errorCode]:J,[be.errorCode]:be,[Se.errorCode]:Se};var k=class extends Error{constructor(e){super(e??"Unauthorized")}};function Jr(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Be="code",Je="S256";function Xr(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&Jr(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Kr(t,e,r,o){let{client_id:n,client_secret:i}=e;switch(t){case"client_secret_basic":Qr(n,i,r);return;case"client_secret_post":Yr(n,i,o);return;case"none":eo(n,o);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Qr(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${o}`)}function Yr(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function eo(t,e){e.set("client_id",t)}async function pr(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let o=ar.parse(JSON.parse(r)),{error:n,error_description:i,error_uri:a}=o,s=dr[n]||W;return new s(i||"",a)}catch(o){let n=t instanceof Response?se(t,t.url):void 0,i=`${e?`HTTP ${e}: `:""}${n??`Invalid OAuth error response: ${o}. Raw body: ${r}`}`;return new W(i)}}function to(t,e){let[r,o]=[t,e];try{[r,o]=[new URL(t).href,new URL(e).href]}catch{}return r===o||r.endsWith("/")&&r.slice(0,-1)===o||o.endsWith("/")&&o.slice(0,-1)===r}function Qe(t,e){if(t)return typeof t.issuer!="string"?t.issuer==null?t:{...t,issuer:void 0}:to(t.issuer,e)?t:void 0}var ro=ir.omit({issuer:!0}),oo=cr.omit({issuer:!0});function fr(t,e){return new Error(`OAuth client information is bound to authorization server ${t.issuer} and is not presented to ${e}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function H(t,e){try{return await Xe(t,e)}catch(r){if(r instanceof G||r instanceof B)return await t.invalidateCredentials?.("all"),await Xe(t,e);if(r instanceof Z)return await t.invalidateCredentials?.("tokens"),await Xe(t,e);throw r}}async function Xe(t,{serverUrl:e,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:i}){let a=await t.discoveryState?.(),s,l,d,h=n;if(!h&&a?.resourceMetadataUrl&&(h=new URL(a.resourceMetadataUrl)),a?.authorizationServerUrl){if(l=a.authorizationServerUrl,s=a.resourceMetadata,d=a.authorizationServerMetadata??await wr(l,{fetchFn:i}),!s)try{s=await _r(e,{resourceMetadataUrl:h},i)}catch{}(d!==a.authorizationServerMetadata||s!==a.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:d})}else{let C=await uo(e,{resourceMetadataUrl:h,fetchFn:i});l=C.authorizationServerUrl,d=C.authorizationServerMetadata,s=C.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:d})}let f=String(l),R=await no(e,t,s),w=R&&s&&!t.validateResourceURL?s.resource:R,S=o||s?.scopes_supported?.join(" ")||t.clientMetadata.scope,m=await Promise.resolve(t.clientInformation()),v=Qe(m,f),M=t.saveClientInformation!==void 0&&!!t.redirectUrl;if(m&&!v&&!M)throw fr(m,f);let A=v?.issuer==null?v:void 0,Y=async()=>{try{A&&await t.saveClientInformation?.({...A,issuer:f})}catch{}};if(!v){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let C=d?.client_id_metadata_document_supported===!0,I=t.clientMetadataUrl;if(I&&!so(I))throw new J(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${I}`);if(C&&I)v={client_id:I,issuer:f},await t.saveClientInformation?.(v);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");v={...await wo(l,{metadata:d,clientMetadata:t.clientMetadata,scope:S,fetchFn:i}),issuer:f},await t.saveClientInformation(v)}}let Ne=!t.redirectUrl;if(r!==void 0||Ne){let C=await _o(t,l,{metadata:d,resource:w,authorizationCode:r,fetchFn:i});return await Y(),await t.saveTokens({...C,issuer:f}),"AUTHORIZED"}let p=Qe(await t.tokens(),f);if(p?.refresh_token&&p.issuer==null&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),p?.refresh_token)try{let C=await fo(l,{metadata:d,clientInformation:v,refreshToken:p.refresh_token,resource:w,addClientAuthentication:t.addClientAuthentication,fetchFn:i});return await Y(),await t.saveTokens({...C,issuer:f}),"AUTHORIZED"}catch(C){if(!(!(C instanceof E)||C instanceof W))throw C}let u=t.state?await t.state():void 0,{authorizationUrl:y,codeVerifier:T}=await ho(l,{metadata:d,clientInformation:v,state:u,redirectUrl:t.redirectUrl,scope:S,resource:w});return await t.saveCodeVerifier(T),await t.redirectToAuthorization(y),"REDIRECT"}function so(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function no(t,e,r){let o=lr(t);if(e.validateResourceURL)return await e.validateResourceURL(o,r?.resource);if(r){if(!ur({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}function ne(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,o]=e.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let n=Ke(t,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let a=Ke(t,"scope")||void 0,s=Ke(t,"error")||void 0;return{resourceMetadataUrl:i,scope:a,error:s}}function Ke(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function _r(t,e,r=fetch){let o=await co(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return sr.parse(await o.json())}async function Ye(t,e,r=fetch){try{return await $(r)(t,{headers:e})}catch(o){if(o instanceof TypeError)return e?Ye(t,void 0,r):void 0;throw o}}function io(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function hr(t,e,r=fetch){return await Ye(t,{"MCP-Protocol-Version":e},r)}function ao(t,e){return!t||!t.ok&&t.status<500&&e!=="/"}async function co(t,e,r,o){let n=new URL(t),i=o?.protocolVersion??de,a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{let l=io(e,n.pathname);a=new URL(l,o?.metadataServerUrl??n),a.search=n.search}let s=await hr(a,i,r);if(!o?.metadataUrl&&ao(s,n.pathname)){let l=new URL(`/.well-known/${e}`,n);s=await hr(l,i,r)}return s}function lo(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),o;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),o}async function wr(t,{fetchFn:e=fetch,protocolVersion:r=de}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},n=lo(t);for(let{url:i,type:a}of n){let s=await Ye(i,o,e);if(s){if(!s.ok){if(await s.body?.cancel(),s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return a==="oauth"?Ze.parse(await s.json()):nr.parse(await s.json())}}}async function uo(t,e){let r,o;try{r=await _r(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",t)));let n=await wr(o,{fetchFn:e?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function mr(t){return typeof t=="string"?t:t.href}async function ho(t,{metadata:e,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:a}){let s;if(e){if(s=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Be))throw new Error(`Incompatible auth server: does not support response type ${Be}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Je))throw new Error(`Incompatible auth server: does not support code challenge method ${Je}`)}else s=new URL("/authorize",t);let l=await Ge(),d=l.code_verifier,h=l.code_challenge;return s.searchParams.set("response_type",Be),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",h),s.searchParams.set("code_challenge_method",Je),s.searchParams.set("redirect_uri",String(o)),i&&s.searchParams.set("state",i),n&&s.searchParams.set("scope",n),n?.includes("offline_access")&&s.searchParams.append("prompt","consent"),a&&s.searchParams.set("resource",mr(a)),{authorizationUrl:s,codeVerifier:d}}function po(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function gr(t,{metadata:e,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:i,fetchFn:a}){let s=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",mr(i)),n)await n(l,r,s,e);else if(o){let h=e?.token_endpoint_auth_methods_supported??[],f=Xr(o,h);Kr(f,o,l,r)}let d=await $(a??fetch)(s,{method:"POST",headers:l,body:r});if(!d.ok)throw await pr(d);return ro.parse(await d.json())}async function fo(t,{metadata:e,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,fetchFn:a}){let s=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),l=await gr(t,{metadata:e,tokenRequestParams:s,clientInformation:r,addClientAuthentication:i,resource:n,fetchFn:a});return{refresh_token:o,...l}}async function _o(t,e,{metadata:r,resource:o,authorizationCode:n,fetchFn:i}={}){let a=async()=>{let h=await t.clientInformation(),f=Qe(h,String(e));if(h&&!f)throw fr(h,String(e));return f},s=await a(),l=t.clientMetadata.scope,d;if(t.prepareTokenRequest&&(d=await t.prepareTokenRequest(l)),!d){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let h=await t.codeVerifier();d=po(n,h,t.redirectUrl)}return s??(s=await a()),gr(e,{metadata:r,tokenRequestParams:d,clientInformation:s,addClientAuthentication:t.addClientAuthentication,resource:o,fetchFn:i})}async function wo(t,{metadata:e,clientMetadata:r,scope:o,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let a=await $(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!a.ok)throw await pr(a);return oo.parse(await a.json())}var Ee=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},yr=10,mo=13,X=32;function et(t){}function Le(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=et,onError:r=et,onRetry:o=et,onComment:n,maxBufferSize:i}=t,a=[],s=0,l=!0,d,h="",f=0,R,w=!1;function S(p){if(w)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,p.charCodeAt(0)===239&&p.charCodeAt(1)===187&&p.charCodeAt(2)===191&&(p=p.slice(3))),a.length===0){let T=v(p);T!==""&&(a.push(T),s=T.length),m();return}if(p.indexOf(`
|
|
5
|
+
`)===-1&&p.indexOf("\r")===-1){a.push(p),s+=p.length,m();return}a.push(p);let u=a.join("");a.length=0,s=0;let y=v(u);y!==""&&(a.push(y),s=y.length),m()}function m(){i!==void 0&&(s+h.length<=i||(w=!0,a.length=0,s=0,d=void 0,h="",f=0,R=void 0,r(new Ee(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function v(p){let u=0;if(p.indexOf("\r")===-1){let y=p.indexOf(`
|
|
6
|
+
`,u);for(;y!==-1;){if(u===y){f>0&&e({id:d,event:R,data:h}),d=void 0,h="",f=0,R=void 0,u=y+1,y=p.indexOf(`
|
|
7
|
+
`,u);continue}let T=p.charCodeAt(u);if(vr(p,u,T)){let C=p.charCodeAt(u+5)===X?u+6:u+5,I=p.slice(C,y);if(f===0&&p.charCodeAt(y+1)===yr){e({id:d,event:R,data:I}),d=void 0,h="",R=void 0,u=y+2,y=p.indexOf(`
|
|
8
|
+
`,u);continue}h=f===0?I:`${h}
|
|
9
|
+
${I}`,f++}else Cr(p,u,T)?R=p.slice(p.charCodeAt(u+6)===X?u+7:u+6,y)||void 0:M(p,u,y);u=y+1,y=p.indexOf(`
|
|
10
|
+
`,u)}return p.slice(u)}for(;u<p.length;){let y=p.indexOf("\r",u),T=p.indexOf(`
|
|
11
|
+
`,u),C=-1;if(y!==-1&&T!==-1?C=y<T?y:T:y!==-1?y===p.length-1?C=-1:C=y:T!==-1&&(C=T),C===-1)break;M(p,u,C),u=C+1,p.charCodeAt(u-1)===mo&&p.charCodeAt(u)===yr&&u++}return p.slice(u)}function M(p,u,y){if(u===y){Y();return}let T=p.charCodeAt(u);if(vr(p,u,T)){let ee=p.charCodeAt(u+5)===X?u+6:u+5,pt=p.slice(ee,y);h=f===0?pt:`${h}
|
|
12
|
+
${pt}`,f++;return}if(Cr(p,u,T)){R=p.slice(p.charCodeAt(u+6)===X?u+7:u+6,y)||void 0;return}if(T===105&&p.charCodeAt(u+1)===100&&p.charCodeAt(u+2)===58){let ee=p.slice(p.charCodeAt(u+3)===X?u+4:u+3,y);ee.includes("\0")||(d=ee);return}if(T===58){if(n){let ee=p.slice(u,y);n(ee.slice(p.charCodeAt(u+1)===X?2:1))}return}let C=p.slice(u,y),I=C.indexOf(":");if(I===-1){A(C,"",C);return}let dt=C.slice(0,I),ht=C.charCodeAt(I+1)===X?2:1,xr=C.slice(I+ht);A(dt,xr,C)}function A(p,u,y){switch(p){case"event":R=u||void 0;break;case"data":h=f===0?u:`${h}
|
|
13
|
+
${u}`,f++;break;case"id":u.includes("\0")||(d=u);break;case"retry":/^\d+$/.test(u)?o(parseInt(u,10)):r(new Ee(`Invalid \`retry\` value: "${u}"`,{type:"invalid-retry",value:u,line:y}));break;default:r(new Ee(`Unknown field "${p.length>20?`${p.slice(0,20)}\u2026`:p}"`,{type:"unknown-field",field:p,value:u,line:y}));break}}function Y(){f>0&&e({id:d,event:R,data:h}),d=void 0,h="",f=0,R=void 0}function Ne(p={}){if(p.consume&&a.length>0){let u=a.join("");M(u,0,u.length)}l=!0,d=void 0,h="",f=0,R=void 0,a.length=0,s=0,w=!1}return{feed:S,reset:Ne}}function vr(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function Cr(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}var $e=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:o,maxBufferSize:n}={}){let i;super({start(a){i=Le({onEvent:s=>{a.enqueue(s)},onError(s){typeof e=="function"&&e(s),(e==="terminate"||s.type==="max-buffer-size-exceeded")&&a.error(s)},onRetry:r,onComment:o,maxBufferSize:n})},transform(a){i.feed(a)}})}};var go={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},V=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Rr=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Pe(r?.fetch,r?.requestInit),this._followRedirects=r?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=oe(this._fetch),this._fetchWithInit=oe(this._fetchWithInit)),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??go}_unfollowedRedirect(e,r){let o=se(e,r);return o&&!this._followRedirects?`${o} (redirectPolicy: 'same-origin')`:o}async _authThenStart(){if(!this._authProvider)throw new k("No auth provider");let e;try{e=await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new k;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(e.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=re(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let o=await this._commonHeaders();o.set("Accept","text/event-stream"),r&&o.set("last-event-id",r);let n=this._fetch??fetch,i={method:"GET",headers:o,signal:this._abortController?.signal},a=await n(this._url,this._followRedirects?i:{...i,redirect:"manual"}),s=this._followRedirects?void 0:Me(n,this._url,i,a);if(s&&(a=await s),!a.ok){if(await a.body?.cancel(),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new V(a.status,`Failed to open SSE stream: ${this._unfollowedRedirect(a,this._url)??a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(o){throw this.onerror?.(o),o}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,o=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(o,e),n)}_scheduleReconnection(e,r=0){let o=this._reconnectionOptions.maxRetries;if(r>=o){this.onerror?.(new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}let n=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(e,r+1)})},n)}_handleSseStream(e,r,o){if(!e)return;let{onresumptiontoken:n,replayMessageId:i}=r,a,s=!1,l=!1;(async()=>{try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new $e({onRetry:w=>{this._serverRetryMs=w}})).getReader();for(;;){let{value:w,done:S}=await h.read();if(S)break;if(w.id&&(a=w.id,s=!0,n?.(w.id)),!!w.data&&(!w.event||w.event==="message"))try{let m=te.parse(JSON.parse(w.data));St(m)&&(l=!0,i!==void 0&&(m.id=i)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(o||s)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:i},0)}catch(h){if(this.onerror?.(new Error(`SSE stream disconnected: ${h}`)),(o||s)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:i},0)}catch(w){this.onerror?.(new Error(`Failed to reconnect: ${w instanceof Error?w.message:String(w)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new k("No auth provider");if(await H(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new k("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:o,onresumptiontoken:n}=r||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:bt(e)?e.id:void 0}).catch(w=>this.onerror?.(w));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let a={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},s=await $(this._fetch??fetch)(this._url,a),l=s.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!s.ok){let w=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new V(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:S,scope:m}=ne(s);if(this._resourceMetadataUrl=S,this._scope=m,await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new k;return this._hasCompletedAuthFlow=!0,this.send(e)}if(s.status===403&&this._authProvider){let{resourceMetadataUrl:S,scope:m,error:v}=ne(s);if(v==="insufficient_scope"){let M=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new V(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),S&&(this._resourceMetadataUrl=S),this._lastUpscopingHeader=M??void 0,await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new k;return this.send(e)}}throw new V(s.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(s,this._url)??w}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,s.status===202){await s.body?.cancel(),Tt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(w=>this.onerror?.(w));return}let h=(Array.isArray(e)?e:[e]).filter(w=>"method"in w&&"id"in w&&w.id!==void 0).length>0,f=s.headers.get("content-type"),R=er(f);if(h)if(R==="text/event-stream")this._handleSseStream(s.body,{onresumptiontoken:n},!1);else if(R==="application/json"){let w=await s.json(),S=Array.isArray(w)?w.map(m=>te.parse(m)):[te.parse(w)];for(let m of S)this.onmessage?.(m)}else throw await s.body?.cancel(),new V(-1,`Unexpected content type: ${f}`);else await s.body?.cancel()}catch(o){throw this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},o=await $(this._fetch??fetch)(this._url,r);if(await o.body?.cancel(),!o.ok&&o.status!==405)throw new V(o.status,`Failed to terminate session: ${this._unfollowedRedirect(o,this._url)??o.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var We=class extends Event{constructor(e,r){var o,n;super(e),this.code=(o=r?.code)!=null?o:void 0,this.message=(n=r?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,o){return o(br(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(br(this),r)}};function yo(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function tt(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(tt).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${tt(t.cause)}`:t.message:`${t}`}function br(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var Er=t=>{throw TypeError(t)},lt=(t,e,r)=>e.has(t)||Er("Cannot "+r),g=(t,e,r)=>(lt(t,e,"read from private field"),r?r.call(t):e.get(t)),z=(t,e,r)=>e.has(t)?Er("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),b=(t,e,r,o)=>(lt(t,e,"write to private field"),e.set(t,r),r),N=(t,e,r)=>(lt(t,e,"access private method"),r),P,K,ie,qe,He,ze,le,Ue,D,ae,ue,ce,Te,L,rt,ot,st,Sr,nt,it,xe,at,ct,Q=class extends EventTarget{constructor(e,r){var o,n;super(),z(this,L),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,z(this,P),z(this,K),z(this,ie),z(this,qe),z(this,He),z(this,ze),z(this,le),z(this,Ue,null),z(this,D),z(this,ae),z(this,ue,null),z(this,ce,null),z(this,Te,null),z(this,ot,async i=>{var a;g(this,ae).reset();let{body:s,redirected:l,status:d,headers:h}=i;if(d===204){N(this,L,xe).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?b(this,ie,new URL(i.url)):b(this,ie,void 0),d!==200){N(this,L,xe).call(this,`Non-200 status code (${d})`,d);return}if(!(h.get("content-type")||"").startsWith("text/event-stream")){N(this,L,xe).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(g(this,P)===this.CLOSED)return;b(this,P,this.OPEN);let f=new Event("open");if((a=g(this,Te))==null||a.call(this,f),this.dispatchEvent(f),typeof s!="object"||!s||!("getReader"in s)){N(this,L,xe).call(this,"Invalid response body, expected a web ReadableStream",d),this.close();return}let R=new TextDecoder,w=s.getReader(),S=!0;do{let{done:m,value:v}=await w.read();v&&g(this,ae).feed(R.decode(v,{stream:!m})),m&&(S=!1,g(this,ae).reset(),N(this,L,at).call(this))}while(S)}),z(this,st,i=>{b(this,D,void 0),!(i.name==="AbortError"||i.type==="aborted")&&N(this,L,at).call(this,tt(i))}),z(this,nt,i=>{typeof i.id=="string"&&b(this,Ue,i.id);let a=new MessageEvent(i.event||"message",{data:i.data,origin:g(this,ie)?g(this,ie).origin:g(this,K).origin,lastEventId:i.id||""});g(this,ce)&&(!i.event||i.event==="message")&&g(this,ce).call(this,a),this.dispatchEvent(a)}),z(this,it,i=>{b(this,ze,i)}),z(this,ct,()=>{b(this,le,void 0),g(this,P)===this.CONNECTING&&N(this,L,rt).call(this)});try{if(e instanceof URL)b(this,K,e);else if(typeof e=="string")b(this,K,new URL(e,vo()));else throw new Error("Invalid URL")}catch{throw yo("An invalid or illegal string was specified")}b(this,ae,Le({onEvent:g(this,nt),onRetry:g(this,it)})),b(this,P,this.CONNECTING),b(this,ze,3e3),b(this,He,(o=r?.fetch)!=null?o:globalThis.fetch),b(this,qe,(n=r?.withCredentials)!=null?n:!1),N(this,L,rt).call(this)}get readyState(){return g(this,P)}get url(){return g(this,K).href}get withCredentials(){return g(this,qe)}get onerror(){return g(this,ue)}set onerror(e){b(this,ue,e)}get onmessage(){return g(this,ce)}set onmessage(e){b(this,ce,e)}get onopen(){return g(this,Te)}set onopen(e){b(this,Te,e)}addEventListener(e,r,o){let n=r;super.addEventListener(e,n,o)}removeEventListener(e,r,o){let n=r;super.removeEventListener(e,n,o)}close(){g(this,le)&&clearTimeout(g(this,le)),g(this,P)!==this.CLOSED&&(g(this,D)&&g(this,D).abort(),b(this,P,this.CLOSED),b(this,D,void 0))}};P=new WeakMap,K=new WeakMap,ie=new WeakMap,qe=new WeakMap,He=new WeakMap,ze=new WeakMap,le=new WeakMap,Ue=new WeakMap,D=new WeakMap,ae=new WeakMap,ue=new WeakMap,ce=new WeakMap,Te=new WeakMap,L=new WeakSet,rt=function(){b(this,P,this.CONNECTING),b(this,D,new AbortController),g(this,He)(g(this,K),N(this,L,Sr).call(this)).then(g(this,ot)).catch(g(this,st))},ot=new WeakMap,st=new WeakMap,Sr=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...g(this,Ue)?{"Last-Event-ID":g(this,Ue)}:void 0},cache:"no-store",signal:(t=g(this,D))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},nt=new WeakMap,it=new WeakMap,xe=function(t,e){var r;g(this,P)!==this.CLOSED&&b(this,P,this.CLOSED);let o=new We("error",{code:e,message:t});(r=g(this,ue))==null||r.call(this,o),this.dispatchEvent(o)},at=function(t,e){var r;if(g(this,P)===this.CLOSED)return;b(this,P,this.CONNECTING);let o=new We("error",{code:e,message:t});(r=g(this,ue))==null||r.call(this,o),this.dispatchEvent(o),b(this,le,setTimeout(g(this,ct),g(this,ze)))},ct=new WeakMap,Q.CONNECTING=0,Q.OPEN=1,Q.CLOSED=2;function vo(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var ut=class extends Error{constructor(e,r,o){super(`SSE error: ${r}`),this.code=e,this.event=o}},Tr=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Pe(r?.fetch,r?.requestInit),this._followRedirects=r?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=oe(this._fetch),this._fetchWithInit=oe(this._fetchWithInit))}_unfollowedRedirect(e,r){let o=se(e,r);return o&&!this._followRedirects?`${o} (redirectPolicy: 'same-origin')`:o}async _authThenStart(){if(!this._authProvider)throw new k("No auth provider");let e;try{e=await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new k;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(e.Authorization=`Bearer ${o.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=re(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch,r=this._followRedirects?e:$(e),o;return new Promise((n,i)=>{this._eventSource=new Q(this._url.href,{...this._eventSourceInit,fetch:async(a,s)=>{let l=await this._commonHeaders();l.set("Accept","text/event-stream");let d=await r(a,{...s,headers:l});if(o=this._unfollowedRedirect(d,a),d.status===401&&d.headers.has("www-authenticate")){let{resourceMetadataUrl:h,scope:f}=ne(d);this._resourceMetadataUrl=h,this._scope=f}return d}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{if(a.code===401&&this._authProvider){this._authThenStart().then(n,i);return}let s=new ut(a.code,o??a.message,a);i(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{let s=a;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(l){i(l),this.onerror?.(l),this.close();return}n()}),this._eventSource.onmessage=a=>{let s=a,l;try{l=te.parse(JSON.parse(s.data))}catch(d){this.onerror?.(d);return}this.onmessage?.(l)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new k("No auth provider");if(await H(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new k("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},n=await $(this._fetch??fetch)(this._endpoint,o);if(!n.ok){let i=await n.text().catch(()=>null);if(n.status===401&&this._authProvider){let{resourceMetadataUrl:a,scope:s}=ne(n);if(this._resourceMetadataUrl=a,this._scope=s,await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new k;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${n.status}): ${this._unfollowedRedirect(n,this._endpoint)??i}`)}await n.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};function Co(t,e){let r=new Headers(t);for(let[o,n]of new Headers(e).entries())r.set(o,n);return r}function Ro(t,e){let r=t.headers.get("location");return r?new URL(r,e):null}async function bo(t){try{await t.body?.cancel()}catch{}}function ps(t,e=fetch){return async(r,o)=>{let n=new Request(r,o),i=new Request(n,{headers:Co(t,n.headers),redirect:"manual"}),a=new URL(i.url),s=await e(i),l=Ro(s,a);if(s.status<300||s.status>=400||!l)return s;throw await bo(s),new Error(`MCP redirect rejected: ${a.origin} -> ${l.origin}`)}}export{Bt as a,Rr as b,Tr as c,ps as d};
|
|
14
|
+
/*! Bundled license information:
|
|
15
|
+
|
|
16
|
+
content-type/index.js:
|
|
17
|
+
(*!
|
|
18
|
+
* content-type
|
|
19
|
+
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
20
|
+
* MIT Licensed
|
|
21
|
+
*)
|
|
22
|
+
*/
|
|
@@ -0,0 +1,6 @@
|
|
|
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{d as n,e as g}from"./chunk-T73GHMFB.js";import{f as u}from"./chunk-NNBSSISP.js";import{f as p}from"./chunk-VK5J556O.js";import{e as c}from"./chunk-VBN2JSER.js";import{mkdirSync as f,readFileSync as D,writeFileSync as m}from"fs";import*as s from"path";var l=c("pi-agent-dir"),x=p(),I=s.join(n,"agents");function P(t){u({defaultsDir:t?.defaultsDir,rolesDir:t?.rolesDir,legacyDir:t?.legacyDir??I})}function E(){f(n,{recursive:!0}),f(g,{recursive:!0}),P(),d()}function d(t){let r=s.join(t?.agentDir??n,"settings.json"),e=y(r);if(e.transport!=="sse")try{m(r,`${JSON.stringify({...e,transport:"sse"},null,2)}
|
|
5
|
+
`)}catch(o){l.warn(`Failed to pin PI transport in ${r}: ${o.message}`)}}function O(t,r){let e=s.join(r?.agentDir??n,"settings.json"),o=y(e),i=o.compaction,a=i&&typeof i=="object"&&!Array.isArray(i)?i:{};if(a.reserveTokens!==t)try{m(e,`${JSON.stringify({...o,compaction:{...a,reserveTokens:t}},null,2)}
|
|
6
|
+
`)}catch(S){l.warn(`Failed to set PI compaction reserve in ${e}: ${S.message}`)}}function y(t){try{let r=JSON.parse(D(t,"utf-8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}catch{return{}}}export{x as a,P as b,E as c,d,O as e};
|
|
@@ -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{c as y}from"./chunk-IKLTEWA3.js";import{a as E}from"./chunk-5M4PFLRW.js";import{b,i as w}from"./chunk-Z24SBRJK.js";import*as f from"node:fs";import*as i from"node:path";var S=i.join(b,"config","hooks");function p(){return{user:i.join(w,"hooks"),builtin:E()?S:null}}var x=new Set(["agent:pre-tool","agent:post-tool","agent:session-start","agent:session-end","agent:pre-compact","agent:user-prompt","agent:turn-end"]),R=/^\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/,T=new Set(["stdout-as-prompt","none"]),g="hook-result",$=new Map([["cortex:session.new","stdout-as-prompt"],["cortex:session.messageEnd","stdout-as-prompt"]]),d=class extends Error{};function u(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function a(e,t){if(typeof e!="string"||e.trim()==="")throw new Error(`${t} must be a non-empty string`);return e}function O(e){let t=a(e,"event");if(x.has(t)||t.match(/^(?:cc|pi|cortex):(.*)$/s)?.[1].trim())return t;throw new Error(`unsupported hook event "${t}"`)}function M(e){return e===null||["string","number","boolean"].includes(typeof e)}function _(e,t){if(typeof e!="string")throw new Error(`${t}: matcher must be a string`);try{new RegExp(e)}catch{throw new Error(`${t}: matcher must be a valid regular expression`)}}function j(e,t){let n;try{n=u(e,"matcher")}catch{throw new Error(`${t}: matcher must be an object`)}if(!Object.values(n).every(M))throw new Error(`${t}: matcher values must be primitive`)}function A(e,t,n){e!==void 0&&(t.startsWith("cortex:")?j(e,n):_(e,n))}function I(e){let t=a(e,"run.script"),n=t.split(/[\\/]/).includes("..");if(i.isAbsolute(t)||i.win32.isAbsolute(t)||n)throw new Error("run.script must stay relative to the hooks directory")}function H(e){if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<=0))throw new Error("run.timeout must be a positive number")}function N(e){let t=u(e,"run"),n=t.script!==void 0,r=t.command!==void 0;if(n===r)throw new Error("run must contain exactly one of script or command");n&&I(t.script),r&&a(t.command,"run.command"),H(t.timeout)}function B(e){if(!Array.isArray(e))throw new Error("scope.backends must be an array");if(!e.every(t=>t==="claude"||t==="pi"))throw new Error("scope.backends contains an unsupported backend")}function D(e){if(e===void 0)return;let t=u(e,"scope");t.backends!==void 0&&B(t.backends),t.requiresTool!==void 0&&a(t.requiresTool,"scope.requiresTool")}function F(e){if(e===void 0)return;let t=u(e,"blocking");if(t.mode!=="webhook")throw new Error("blocking.mode must be webhook");if(typeof t.ttlMin!="number"||!Number.isFinite(t.ttlMin)||t.ttlMin<=0)throw new Error("blocking.ttlMin must be a positive number")}function L(e,t){if(e!==void 0){if(e===g)throw new d(`result mode "${g}" is retired; remove the hook or its result field`);if(typeof e!="string"||!T.has(e))throw new Error("result must be stdout-as-prompt or none");if(e!=="none"&&$.get(t)!==e)throw new Error(`result mode "${e}" is not permitted for event "${t}"`)}}function P(e,t){if(D(e.scope),F(e.blocking),L(e.result,t),e.enabled!==void 0&&typeof e.enabled!="boolean")throw new Error("enabled must be a boolean");if(e.version!==void 0&&!R.test(a(e.version,"version")))throw new Error("version must be a CalVer string")}function l(e){let t=u(e,"hook entry"),n=a(t.id,"id"),r=O(t.event);return A(t.matcher,r,n),N(t.run),P(t,r),t}function m(e,t){let n=t instanceof Error?t.message:String(t);(t instanceof d?console.warn:console.error)(`[hook-registry] skipped ${e}: ${n}`)}function k(e){if(!e)return new Set;try{return new Set(f.readdirSync(e).filter(t=>t.endsWith(".json")))}catch(t){return t.code!=="ENOENT"&&m(e,t),new Set}}function h(e){return u(JSON.parse(f.readFileSync(e,"utf8")),"hook entry")}function C(e,t){if(!t)return null;try{return h(e)}catch(n){return m(i.basename(e),n),null}}function U(e,t,n){let r=i.join(t.builtin,e),o=l(h(r)),c=i.join(t.user,e),s=C(c,n);return{entry:s?l({...o,...s,id:o.id}):o,filePath:s?c:r,source:"builtin",builtin:{entry:o,overridePath:c,override:s}}}function q(e,t){let n=i.join(t.user,e);return{entry:l(h(n)),filePath:n,source:"user"}}function v(e=p()){let t=k(e.builtin),n=k(e.user),r=[],o=new Set;for(let c of[...new Set([...t,...n])].sort())try{let s=t.has(c)?U(c,e,n.has(c)):q(c,e);if(o.has(s.entry.id))throw new Error(`duplicate hook id "${s.entry.id}"`);o.add(s.entry.id),r.push(s)}catch(s){m(c,s)}return r}function re(e=p()){return v(e).map(t=>t.entry)}function V(e){return{kind:"registry",id:e.entry.id,event:e.entry.event,enabled:e.entry.enabled!==!1,source:e.source,overridden:e.builtin?.override!=null,entry:e.entry,filePath:e.filePath}}function W(e=p()){return v(e).map(V)}function G(e){return{id:e.id,event:e.event,enabled:e.enabled,source:e.source,overridden:e.overridden}}function oe(e=p()){return W(e).map(G)}function Y(e){return`'${e.replace(/'/g,"'\\''")}'`}function ie(e,t,n,r=1/0){let o=e.entry.run;return{command:o.script===void 0?o.command:`node ${y(o.script,t).map(Y).join(" ")}`,timeoutMs:Math.min((o.timeout??30)*1e3,r),stdinPayload:n,label:e.id}}function K(e){return e.startsWith("agent:")?["claude","pi"]:e.startsWith("cc:")?["claude"]:e.startsWith("pi:")?["pi"]:[]}function z(e){let t=K(e.event),n=e.scope?.backends;return n?t.filter(r=>n.includes(r)):t}function J(e,t){return t.event===void 0||e.event===t.event}function Q(e,t){return t.backend===void 0||z(e).includes(t.backend)}function X(e,t){let n=e.scope?.requiresTool;return n===void 0||t.availableTools===void 0||t.availableTools.has(n)}function se(e,t={}){return e.filter(n=>n.enabled!==!1).filter(n=>J(n,t)).filter(n=>Q(n,t)).filter(n=>X(n,t))}export{p as a,$ as b,l as c,v as d,re as e,W as f,G as g,oe as h,ie as i,z as j,se as k};
|