@cortex-agent/server 2026.10.28 → 2026.11.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +255 -21
- package/README.md +36 -7
- package/THIRD_PARTY_NOTICES.txt +1109 -278
- package/defaults/hooks/cortex-hook-api.mjs +2 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
- package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
- package/dist/chunks/{anthropic-messages-M3SMXACA.js → anthropic-messages-M732OMEE.js} +1 -1
- package/dist/chunks/{azure-openai-responses-76YWXHSB.js → azure-openai-responses-RAKTV6JY.js} +1 -1
- package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +62 -0
- package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
- package/dist/chunks/child-runner-MO5RT6FH.js +4 -0
- package/dist/chunks/chunk-2ATTYCRJ.js +4 -0
- package/dist/chunks/{chunk-PXS5SHOV.js → chunk-2ROGTDM2.js} +1 -1
- package/dist/chunks/chunk-2VVRTJQN.js +4 -0
- package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
- package/dist/chunks/chunk-3CPIMAYX.js +30 -0
- package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-3CZPBLB3.js} +1 -1
- package/dist/chunks/chunk-3ORG56I5.js +8 -0
- package/dist/chunks/{chunk-LEUENXI2.js → chunk-4YLAGSDM.js} +1 -1
- package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-53TQNK7Z.js} +1 -1
- package/dist/chunks/{chunk-4U7XXM4W.js → chunk-5A6CA5TM.js} +1 -1
- package/dist/chunks/{chunk-PBJ5MPPX.js → chunk-5DF5WJNM.js} +1 -1
- package/dist/chunks/chunk-5PAW3DEU.js +50 -0
- package/dist/chunks/{chunk-DXBSQXJL.js → chunk-7GAYFN52.js} +1 -1
- package/dist/chunks/chunk-7GEBDPTT.js +4 -0
- package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-AFTBQRPN.js} +1 -1
- package/dist/chunks/chunk-AVXDF7AG.js +4 -0
- package/dist/chunks/chunk-BDLKI2NT.js +4 -0
- package/dist/chunks/{chunk-P52RMIYX.js → chunk-BJGYGEZO.js} +1 -1
- package/dist/chunks/chunk-BUZQBTV2.js +10 -0
- package/dist/chunks/chunk-BZDIAI5M.js +125 -0
- package/dist/chunks/{chunk-A34TDMIC.js → chunk-CEGSDGYQ.js} +1 -1
- package/dist/chunks/{chunk-Q7CE3UIE.js → chunk-CK3P345X.js} +69 -69
- package/dist/chunks/{chunk-YAEVYJAR.js → chunk-EE3WT25T.js} +1 -1
- package/dist/chunks/chunk-ETIBCA2S.js +4 -0
- package/dist/chunks/{chunk-REBNWCKI.js → chunk-FP7ML72L.js} +1 -1
- package/dist/chunks/{chunk-H2FP6DG4.js → chunk-H4QZ2P3Z.js} +1 -1
- package/dist/chunks/chunk-IA6IODY3.js +4 -0
- package/dist/chunks/{chunk-D3NXKK2L.js → chunk-IKLTEWA3.js} +1 -1
- package/dist/chunks/chunk-IYVZHGUQ.js +5 -0
- package/dist/chunks/chunk-JJDEQ6N2.js +4 -0
- package/dist/chunks/chunk-JKL3AK5D.js +106 -0
- package/dist/chunks/chunk-KDPY2YA3.js +129 -0
- package/dist/chunks/{chunk-SUFW24P4.js → chunk-KUDK7GPS.js} +1 -1
- package/dist/chunks/chunk-LAWOWPZX.js +363 -0
- package/dist/chunks/chunk-LEAV3FFG.js +4 -0
- package/dist/chunks/chunk-LP72AF56.js +45 -0
- package/dist/chunks/{chunk-KENCMLRE.js → chunk-LP7T32PW.js} +1 -1
- package/dist/chunks/chunk-LQTFDC67.js +4 -0
- package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-MGYYSX7Y.js} +1 -1
- package/dist/chunks/chunk-NNBSSISP.js +4 -0
- package/dist/chunks/chunk-NNTQUHLO.js +877 -0
- package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-NRD57ICT.js} +1 -1
- package/dist/chunks/{chunk-QWAQHHRS.js → chunk-NXZS5PEW.js} +1 -1
- package/dist/chunks/chunk-OFEPDNRB.js +4 -0
- package/dist/chunks/{chunk-6LZK4DDH.js → chunk-P7TVR4GY.js} +1 -1
- package/dist/chunks/chunk-QEL6CMLE.js +4 -0
- package/dist/chunks/chunk-QMSSIDRQ.js +70 -0
- package/dist/chunks/chunk-QUXPMNFQ.js +4 -0
- package/dist/chunks/chunk-R52AVUQB.js +5 -0
- package/dist/chunks/chunk-R6CGBSTC.js +22 -0
- package/dist/chunks/chunk-RA2BUYI3.js +6 -0
- package/dist/chunks/chunk-RDW6FRF5.js +4 -0
- package/dist/chunks/chunk-RF4JLYBX.js +6 -0
- package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-ROVKOIHF.js} +1 -1
- package/dist/chunks/chunk-RYLSRII6.js +7 -0
- package/dist/chunks/{chunk-XNSSUVT6.js → chunk-S3MR37DL.js} +1 -1
- package/dist/chunks/chunk-SAJD4EKE.js +10 -0
- package/dist/chunks/chunk-SFX7V5O2.js +10 -0
- package/dist/chunks/chunk-STCNHXPJ.js +6 -0
- package/dist/chunks/{chunk-FOJQXLL2.js → chunk-SY2HV3V5.js} +1 -1
- package/dist/chunks/chunk-T73GHMFB.js +4 -0
- package/dist/chunks/chunk-TKFFQNAP.js +19 -0
- package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
- package/dist/chunks/chunk-TX46YMGI.js +5 -0
- package/dist/chunks/chunk-U23S37TT.js +6 -0
- package/dist/chunks/chunk-UT6DGZDO.js +4 -0
- package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
- package/dist/chunks/chunk-V6X7Y62J.js +7 -0
- package/dist/chunks/chunk-V7K3KNDM.js +4 -0
- package/dist/chunks/{chunk-NAA7GF6Q.js → chunk-VBN2JSER.js} +1 -1
- package/dist/chunks/chunk-VIMHSW6J.js +4 -0
- package/dist/chunks/chunk-VK5J556O.js +4 -0
- package/dist/chunks/chunk-VPVSKJGX.js +6 -0
- package/dist/chunks/chunk-VTL3Z2OP.js +23 -0
- package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
- package/dist/chunks/chunk-W34AK4SK.js +65 -0
- package/dist/chunks/chunk-W6AKCEYF.js +8 -0
- package/dist/chunks/chunk-WBSE3EF3.js +27 -0
- package/dist/chunks/chunk-WZYS2HAK.js +4 -0
- package/dist/chunks/{chunk-UNVEZI57.js → chunk-XEBEWR6Y.js} +1 -1
- package/dist/chunks/chunk-XPPZ6Y3X.js +8 -0
- package/dist/chunks/chunk-XYSXL3KX.js +4 -0
- package/dist/chunks/chunk-YAAKL3QS.js +80 -0
- package/dist/chunks/chunk-YB5LUJHS.js +65 -0
- package/dist/chunks/chunk-Z24SBRJK.js +4 -0
- package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +1 -1
- package/dist/chunks/context-GQKWKFRM.js +4 -0
- package/dist/chunks/cost-OOO32GLC.js +5 -0
- package/dist/chunks/dist-V5FRMUFH.js +4 -0
- package/dist/chunks/easter-egg-3d-CZH7AYZ7.js +4 -0
- package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
- package/dist/chunks/execution-repo-XXL4FXC6.js +4 -0
- package/dist/chunks/{executions-6ARGR3IO.js → executions-BN6OLLVM.js} +1 -1
- package/dist/chunks/file-H572PL2Z.js +4 -0
- package/dist/chunks/google-generative-ai-2G4ITOZL.js +4 -0
- package/dist/chunks/google-vertex-PACHCMRZ.js +4 -0
- package/dist/chunks/init-75F4V7SK.js +4 -0
- package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-ABBD7DO5.js} +1 -1
- package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-EE2UPR3Q.js} +1 -1
- package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-C446T2GZ.js} +1 -1
- package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-IA2F2H7A.js} +1 -1
- package/dist/chunks/local-client-stop-5YOLXGYT.js +4 -0
- package/dist/chunks/memory-cli-5SSF6YJM.js +11 -0
- package/dist/chunks/{mistral-conversations-34F66L3O.js → mistral-conversations-VHP63CDS.js} +1 -1
- package/dist/chunks/{model-resolver-N3DTAQ2S.js → model-resolver-FVJNZ6NA.js} +1 -1
- package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
- package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
- package/dist/chunks/{openai-codex-responses-ZBVHREB3.js → openai-codex-responses-EHJ4AZBE.js} +1 -1
- package/dist/chunks/{openai-completions-VVIB26SH.js → openai-completions-CRAGQFCE.js} +1 -1
- package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-P5UX7BWY.js} +1 -1
- package/dist/chunks/{openai-responses-735XA2ZX.js → openai-responses-IZ22NVQ7.js} +1 -1
- package/dist/chunks/{openrouter-images-3IKETHAC.js → openrouter-images-W2JAMSRH.js} +1 -1
- package/dist/chunks/{pi-messages-I3E4ZFHA.js → pi-messages-MJEEQU2R.js} +1 -1
- package/dist/chunks/{radius-HXRZVBDB.js → radius-ZM7ZRMXF.js} +1 -1
- package/dist/chunks/{remote-ops-BALZYKH6.js → remote-ops-O5CR4RGA.js} +1 -1
- package/dist/chunks/runner-S6R3US24.js +4 -0
- package/dist/chunks/schedule-cli-4T4YC5V5.js +4 -0
- package/dist/chunks/slack-2CGM4SMY.js +4 -0
- package/dist/chunks/start-ui-http-3D7QNHGB.js +43 -0
- package/dist/chunks/subagent-OZGUOV3J.js +4 -0
- package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
- package/dist/chunks/tool-shims-IA2WELXJ.js +4 -0
- package/dist/chunks/typesafe-system-one-6ULACYD4.js +1 -1
- package/dist/chunks/ui-board-H4INJD6C.js +5 -0
- package/dist/chunks/ui-decision-6HHNROIT.js +4 -0
- package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-6PLXHSTB.js} +1 -1
- package/dist/chunks/ui-view-6MDU4GXY.js +4 -0
- package/dist/chunks/virtual-modules-OFI7QKYH.js +4 -0
- package/dist/chunks/waitpoint-W5M3BE55.js +5 -0
- package/dist/chunks/workers-GTFP75MS.js +4 -0
- package/dist/client-bundle/client.mjs +44 -31
- package/dist/client-bundle/manifest.json +2 -2
- package/dist/core/pi-sdk.js +1 -1
- package/dist/domain/auth/cc-auth-cli.js +1 -1
- package/dist/domain/mcp/bundled-server.js +1 -1
- package/dist/domain/mcp/feishu/client.js +4 -0
- package/dist/entry/app.js +201 -191
- package/dist/entry/browser-cli.js +10 -10
- package/dist/entry/cli.js +1 -1
- package/dist/entry/cortex-cli.js +1 -1
- package/dist/entry/daemon.js +4 -4
- package/dist/entry/hook-cli.js +2 -2
- package/dist/entry/production-app-bootstrap.js +1 -1
- package/dist/entry/production-evidence-export-cli.js +1 -1
- package/dist/entry/signal-cli.js +2 -2
- package/dist/tui/index.js +41 -41
- package/package.json +3 -3
- package/vendor/pi/dist/core/extensions/loader.js +1 -1
- package/vendor/pi/dist/extensions/codemode/execute.js +1 -1
- package/vendor/pi-ai/bedrock.js +1 -1
- package/vendor/pi-ai/oauth-load.js +1 -1
- package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-BgIyUG-C.js} +1 -1
- package/web/dist/assets/index-9lyu2S6W.css +1 -0
- package/web/dist/assets/index-C-hpzey7.js +532 -0
- package/web/dist/assets/{index-WCm6wwmM.js → index-C2eMpcuI.js} +1 -1
- package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
- package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
- package/web/dist/index.html +2 -2
- package/web/dist/theme.css +22 -0
- package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
- package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
- package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
- package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
- package/dist/chunks/chunk-3F6WW7HR.js +0 -13
- package/dist/chunks/chunk-3OKHUVEM.js +0 -7
- package/dist/chunks/chunk-3THJYAEF.js +0 -4
- package/dist/chunks/chunk-3YHOCPQU.js +0 -10
- package/dist/chunks/chunk-4LLH5OWM.js +0 -10
- package/dist/chunks/chunk-52T37Y47.js +0 -8
- package/dist/chunks/chunk-7MU2AKNM.js +0 -4
- package/dist/chunks/chunk-AAA3UBIS.js +0 -4
- package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
- package/dist/chunks/chunk-BGVHA2D4.js +0 -4
- package/dist/chunks/chunk-BKHDWCRT.js +0 -79
- package/dist/chunks/chunk-CQLH4UVX.js +0 -4
- package/dist/chunks/chunk-D6UA4BZC.js +0 -19
- package/dist/chunks/chunk-DGMNI4AO.js +0 -4
- package/dist/chunks/chunk-DHSA5ACV.js +0 -125
- package/dist/chunks/chunk-DPQPXBTP.js +0 -68
- package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
- package/dist/chunks/chunk-EQITBTJC.js +0 -10
- package/dist/chunks/chunk-EXJA5RIX.js +0 -357
- package/dist/chunks/chunk-FH74NME3.js +0 -115
- package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
- package/dist/chunks/chunk-J5DVLUKY.js +0 -6
- package/dist/chunks/chunk-JW2HFMTF.js +0 -4
- package/dist/chunks/chunk-KIGMAATV.js +0 -23
- package/dist/chunks/chunk-KIU5FAPY.js +0 -5
- package/dist/chunks/chunk-KIWMQPH7.js +0 -739
- package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
- package/dist/chunks/chunk-MEPASGPP.js +0 -6
- package/dist/chunks/chunk-MFAEUHMV.js +0 -28
- package/dist/chunks/chunk-NKDMKRSB.js +0 -68
- package/dist/chunks/chunk-NKXV32S6.js +0 -4
- package/dist/chunks/chunk-NVX5IPRN.js +0 -4
- package/dist/chunks/chunk-O3JW2F7D.js +0 -8
- package/dist/chunks/chunk-OISO5JXB.js +0 -4
- package/dist/chunks/chunk-OPYXNSMY.js +0 -4
- package/dist/chunks/chunk-PZMXHA6X.js +0 -9
- package/dist/chunks/chunk-QEOFEETJ.js +0 -4
- package/dist/chunks/chunk-REPYBMQS.js +0 -4
- package/dist/chunks/chunk-TAWLERZA.js +0 -4
- package/dist/chunks/chunk-TWAEABGG.js +0 -52
- package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
- package/dist/chunks/chunk-UD3NMUHR.js +0 -12
- package/dist/chunks/chunk-W25TB3PU.js +0 -4
- package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
- package/dist/chunks/chunk-XAJLZR7C.js +0 -28
- package/dist/chunks/chunk-XH6FMP3N.js +0 -71
- package/dist/chunks/chunk-XSRZHN63.js +0 -4
- package/dist/chunks/chunk-YG7OEPR2.js +0 -6
- package/dist/chunks/chunk-YHIWOGVL.js +0 -4
- package/dist/chunks/chunk-YZSHTWNM.js +0 -92
- package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
- package/dist/chunks/client-XOGYH5UR.js +0 -4
- package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
- package/dist/chunks/context-VCQH5OB6.js +0 -4
- package/dist/chunks/cost-PGGFI7QJ.js +0 -5
- package/dist/chunks/dist-PUKMZ7GW.js +0 -4
- package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
- package/dist/chunks/es5-VNTQPCKX.js +0 -4
- package/dist/chunks/execution-repo-ZLJTBWFC.js +0 -4
- package/dist/chunks/file-7BN7RCAY.js +0 -4
- package/dist/chunks/gateway-UCRPMR75.js +0 -36
- package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
- package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
- package/dist/chunks/init-HA7FAQ73.js +0 -4
- package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
- package/dist/chunks/memory-cli-PYOILNN5.js +0 -11
- package/dist/chunks/models-L5VF4I5O-XXNJYQMQ.js +0 -4
- package/dist/chunks/runner-PLVZDGHB.js +0 -4
- package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
- package/dist/chunks/slack-WAGSPZUX.js +0 -4
- package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
- package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
- package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
- package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
- package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
- package/dist/chunks/ui-view-O7PLANT7.js +0 -4
- package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
- package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
- package/dist/chunks/workers-XN4PSTH6.js +0 -4
- package/vendor/aistatus/gateway-cli.js +0 -21
- package/web/dist/assets/index-BHZpFXhc.js +0 -525
- package/web/dist/assets/index-DqWMdMkh.css +0 -1
- package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
- package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
|
@@ -0,0 +1,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{M as me,P as ye,Q as ge,l as B,n as H,o as T,p}from"./chunk-JJDEQ6N2.js";import{a as pe}from"./chunk-MGYYSX7Y.js";import{a as _}from"./chunk-LCKVYFMD.js";import{c as fe}from"./chunk-STUHNKQS.js";import{p as he,q as D}from"./chunk-TX46YMGI.js";import{a as y}from"./chunk-Q4UGYGU5.js";import{e as ue}from"./chunk-VBN2JSER.js";import{i as de,j as g}from"./chunk-Z24SBRJK.js";import{readFileSync as we}from"node:fs";import*as be from"node:path";var Y=ue("models-repo"),V=0,Ie=be.join(de,"models.json"),$t=new y;function zt(){return V}function Se(n){let e=JSON.parse(n);return e?.default?{...e,default:D(e.default)}:e}var J=class{filePath;cache=null;constructor(e=Ie){this.filePath=e}readSync(){return this.cache||(this.cache=Se(we(this.filePath,"utf8"))),this.cache}readIfPresent(){try{return this.readSync()}catch(e){if(e.code==="ENOENT")return null;throw e}}invalidate(){this.cache=null,V+=1}reload(){this.cache=Se(we(this.filePath,"utf8"))}},M=new J,K=null;function _t(n){K=n}function nn(n,e){try{n.reload(),V+=1,e?.(),Y.info("Hot-reload: models.json reloaded"),K?.(`${_.refresh} \`models.json\` hot-reloaded`)}catch(t){Y.error(`Hot-reload models.json failed: ${t.message} \u2014 keeping previous config`),K?.(`${_.warning} \`models.json\` hot-reload FAILED \u2014 keeping previous config`)}}function Ht(n=M,e=Ie,t){let i=null,s=fe({label:"models.json",filePath:e,onChange:()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,nn(n,t)},300)},warn:o=>Y.error(o)});return()=>{s.close(),i&&clearTimeout(i),i=null}}import*as $e from"node:path";import{isDeepStrictEqual as lt}from"node:util";import ve from"node:fs";import u from"node:fs/promises";import Q from"node:path";import rn from"node:readline";function W(n){return typeof n=="string"&&n.length>0}function tn(n){if(!n||typeof n!="object")return;let e=n;if(W(e.after))return{after:e.after};if(W(e.before))return{before:e.before}}function G(n){let e=tn(n),t=n?.file;return e&&W(t)?{file:t,...e}:void 0}var on=1,sn=256,an=16*1024*1024,cn=1024*1024,ln=Q.join(g,"channel-registry.json"),dn=/^\[[^\]]+:[^\]]+\]$/;function A(){return{live:new Map,pending:new Map,bindings:new Map,turns:new Map,conversations:new Map,eventCount:0,fileSize:0,compactedFileSize:0}}function Ae(n){return n.replace(/\.jsonl$/,".json")}function un(n){return`${Ae(n)}.bak`}function Ee(n,e){return n==="scheduled"?"scheduled":e&&dn.test(e)?"thread":"direct"}function xe(n,e){let t={fileSize:n.fileSize,eventCount:n.eventCount,liveCount:n.live.size};if(e.shouldCompact)return e.shouldCompact(t);let i=Math.max(512,n.live.size*4,fn(n)*2),r=Math.max(an,n.compactedFileSize*2);return n.fileSize>r||n.eventCount>i}function fn(n){let e=0;for(let t of n.turns.values())e+=t.length;return n.live.size+n.pending.size+n.bindings.size+n.conversations.size+e}async function Ce(n,e={}){return await mn(n),await ot(n),xn(n,e)}async function f(n,e,t,i={}){await Z(n,e,[t],i)}async function Z(n,e,t,i={}){if(t.length===0)return;let r=new Set;for(let l of t){if("id"in l){if(r.has(l.id))throw new Error(`Session appears twice in one append batch: ${l.id}`);r.add(l.id)}Jn(e,l)}let s=t.map(l=>`${JSON.stringify(l)}
|
|
5
|
+
`).join(""),o=await nt(n,s,i.writeAppend);for(let l of t)Pe(e,l);e.eventCount+=t.length,e.fileSize=o}async function q(n,e,t={}){let i=Re(e);await Ue(n,i),e.eventCount=i.length,e.fileSize=(await u.stat(n)).size,e.compactedFileSize=e.fileSize,t.onCompact?.()}function Re(n){let e=[];for(let t of n.live.values())e.push(hn(t));for(let t of n.pending.values())e.push(pn(t.session,t.cleanup));for(let[t,i]of n.bindings)e.push({v:1,op:"bind",channel:t,sessionId:i});for(let[t,i]of n.conversations)e.push({v:1,op:"conversation",channel:t,kind:"set",fields:i});for(let[t,i]of n.turns)for(let r of i)e.push({v:1,op:"turn",channel:t,kind:"begin",turn:r});return e}function hn(n){return{v:1,op:"put",id:n.sessionId,record:n}}function pn(n,e){return{v:1,op:"delete-intent",id:n.sessionId,record:n,cleanup:e}}async function mn(n){await u.mkdir(Q.dirname(n),{recursive:!0});let e=await N(n),t=Ae(n),i=await N(t);if(e&&i&&e.size===0&&i.size>0)throw new Error(`Empty JSONL hides non-empty legacy registry: ${n}`);if(!e){if(i)return yn(n,t);await u.writeFile(n,"",{flag:"a"})}}async function yn(n,e){let t=JSON.parse(await u.readFile(e,"utf8")),i=A();for(let r of await Sn(t))Fe(i,r);await gn(e,un(n)),await Ue(n,Re(i))}async function gn(n,e){let t=await wn(e);await u.copyFile(n,t,ve.constants.COPYFILE_EXCL)}async function wn(n){if(await N(n)===null)return n;let e=new Date().toISOString().replace(/[:.]/g,"-");for(let t=0;t<1e3;t+=1){let i=`${n}.${e}.${t+1}`;if(await N(i)===null)return i}throw new Error(`Could not allocate session registry backup path: ${n}`)}async function Sn(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("legacy session registry must be a plain object");let e=Object.entries(n);return e.length===0?[]:bn(e)==="new"?In(e):await kn(e)}function bn(n){let e=!1,t=!1;for(let[,i]of n){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("legacy session registry entries must be objects");let r=i,s=Object.hasOwn(r,"name"),o=Object.hasOwn(r,"sessionId");if(s)e=!0;else if(o)t=!0;else throw new Error("legacy session registry entry format is unrecognizable");if(e&&t)throw new Error("legacy session registry mixes old and new formats")}return e?"new":"old"}function In(n){return n.map(([e,t])=>{let i=t,r=ee(i.kind),s=E(i.label);return X(i.origin===void 0?{...i,origin:Ee(r,s)}:i,e)})}async function kn(n){let e=await vn(),t=new Map;for(let[,i]of n)An(t,e,i);return Array.from(t.values())}async function vn(){try{let n=JSON.parse(await u.readFile(ln,"utf8"));return Object.fromEntries(Object.entries(n).map(([e,t])=>[t,e]))}catch{return{}}}function An(n,e,t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("legacy session registry entries must be objects");let i=t,r=a(i.sessionId),s=En(e,i),o=n.get(r);(!o||o.lastUsedAt<=s.lastUsedAt)&&n.set(r,s)}function En(n,e){let t=e.kind==="scheduled"?"scheduled":"local",i=E(e.label);return{sessionId:String(e.sessionId),projectId:n[a(e.channel)]||"general",channel:a(e.channel),backend:a(e.backend),kind:t,origin:Ee(t,i),createdAt:a(e.createdAt),lastUsedAt:a(e.lastUsedAt),label:i,selection:P(e.selection),...e.profileName!==void 0?{profileName:e.profileName}:{},agentName:c(e.agentName),backendSessionId:c(e.backendSessionId),lastReadAt:c(e.lastReadAt),scheduleId:c(e.scheduleId),contextUsage:e.contextUsage}}async function xn(n,e){let t=A(),i=ve.createReadStream(n,{encoding:"utf8"}),r=rn.createInterface({input:i,crlfDelay:1/0}),s=0;for await(let o of r)s+=1,Pe(t,Cn(o,s)),s%(e.yieldEvery??sn)===0&&await ct();return t.eventCount=s,t.fileSize=(await u.stat(n)).size,t}function Cn(n,e){if(!n)throw new Error(`Malformed session registry line ${e}: empty line`);let t;try{t=JSON.parse(n)}catch{throw new Error(`Malformed session registry line ${e}`)}return Rn(t,e)}function Rn(n,e){let t=n,i=t?.v,r=t?.op;if(i!==on)throw new Error(`Unknown session registry version at line ${e}`);if(r==="put"){let s=O(t,e);return{v:1,op:r,id:s,record:X(t.record,s)}}if(r==="delete-intent"){let s=O(t,e);return{v:1,op:r,id:s,record:X(t.record,s),cleanup:jn(t.cleanup)}}if(r==="delete-commit")return{v:1,op:r,id:O(t,e)};if(r==="patch")return Dn(t,e);if(r==="bind")return Tn(t,e);if(r==="unbind")return{v:1,op:"unbind",channel:v(t,"channel",e)};if(r==="conversation")return On(t,e);if(r==="turn")return Mn(t,e);throw new Error(`Unknown session registry op at line ${e}`)}function O(n,e){let t=n?.id;if(typeof t!="string"||!t)throw new Error(`Malformed session registry id at line ${e}`);return t}function v(n,e,t){let i=n?.[e];if(typeof i!="string"||!i)throw new Error(`Malformed session registry ${e} at line ${t}`);return i}function Dn(n,e){let t=O(n,e),i=Un(n.fields);return Array.isArray(n.unset)&&n.unset.includes("profileName")&&Object.assign(i,{profileName:void 0}),{v:1,op:"patch",id:t,fields:i,...Bn(n.unset,e)}}function Bn(n,e){if(n===void 0)return{};if(!Array.isArray(n))throw new Error(`Invalid session registry patch unset at line ${e}`);let t=n.map(r=>typeof r=="string"?Oe(r):r);if(t.some(r=>r!==null&&!Fn.has(r)))throw new Error(`Invalid session registry patch unset at line ${e}`);let i=t.filter(r=>r!==null);return i.length?{unset:i}:{}}function Tn(n,e){return{v:1,op:"bind",channel:v(n,"channel",e),sessionId:v(n,"sessionId",e)}}function Mn(n,e){let t=v(n,"channel",e),i=n?.kind;if(i==="begin")return{v:1,op:"turn",channel:t,kind:i,turn:Ln(n.turn)};if(i==="patch")return{v:1,op:"turn",channel:t,kind:i,turnIndex:j(n.turnIndex),fields:_n(n.fields)};if(i==="truncate")return{v:1,op:"turn",channel:t,kind:i,fromIndex:j(n.fromIndex)};if(i==="clear")return{v:1,op:"turn",channel:t,kind:i};throw new Error(`Unknown session registry turn kind at line ${e}`)}function On(n,e){let t=v(n,"channel",e),i=n?.kind;if(i==="set")return{v:1,op:"conversation",channel:t,kind:i,fields:Yn(n.fields)};if(i==="clear")return{v:1,op:"conversation",channel:t,kind:i};throw new Error(`Unknown session registry conversation kind at line ${e}`)}function jn(n){if(n===void 0)return{claudeBackupPaths:[]};if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid session registry delete cleanup");let e=n.claudeBackupPaths;if(!Array.isArray(e)||e.some(t=>typeof t!="string"))throw new Error("Invalid session registry Claude backup paths");return{claudeBackupPaths:[...new Set(e)]}}function X(n,e){let t=n,i={sessionId:a(t?.sessionId),projectId:a(t?.projectId),channel:a(t?.channel),backend:a(t?.backend),kind:ee(t?.kind),origin:De(t?.origin),createdAt:a(t?.createdAt),lastUsedAt:a(t?.lastUsedAt),label:E(t?.label),starred:w(t?.starred),labelRenamed:w(t?.labelRenamed),selection:P(t?.selection),...t?.profileName!==void 0?{profileName:t.profileName}:{},agentName:c(t?.agentName),backendSessionId:c(t?.backendSessionId),lastReadAt:c(t?.lastReadAt),scheduleId:c(t?.scheduleId),boardId:c(t?.boardId??t?.commissionId),boardBlockFor:c(t?.boardBlockFor??t?.commissionBlockFor),contextUsage:t?.contextUsage,teamLeadId:c(t?.teamLeadId),workerName:c(t?.workerName),workerBrief:c(t?.workerBrief),clean:w(t?.clean),workspaceDir:c(t?.workspaceDir)};return i.selection&&delete i.profileName,Nn(i,e)}function Nn(n,e){if(n.sessionId!==e)throw new Error(`Session registry record id mismatch for ${e}`);return n}function a(n){if(typeof n!="string")throw new Error("Invalid session registry string field");return n}function E(n){if(n==null||n==="")return null;if(typeof n!="string")throw new Error("Invalid session registry nullable string");return n}function P(n){if(n==null)return null;let e=n;if(e.backend!=="claude"&&e.backend!=="pi")throw new Error("Invalid session registry selection backend");return{backend:e.backend,provider:h(e.provider),model:a(e.model),thinking:h(e.thinking),connection:Pn(e)}}function Pn(n){return n.backend!=="claude"?null:"connection"in n?h(n.connection):he("claude",n.mode)}function w(n){if(n!==void 0){if(typeof n!="boolean")throw new Error("Invalid session registry boolean field");return n}}function c(n){if(n!==void 0)return E(n)}function ee(n){if(n==="local"||n==="scheduled")return n;throw new Error("Invalid session registry kind")}function De(n){if(n==="direct"||n==="thread"||n==="scheduled")return n;throw new Error("Invalid session registry origin")}function j(n){if(typeof n!="number"||!Number.isFinite(n))throw new Error("Invalid session registry number field");return n}function h(n){if(n===null)return null;if(typeof n=="string")return n;throw new Error("Invalid session registry turn nullable string")}function Be(n){if(!Array.isArray(n)||n.some(e=>typeof e!="string"))throw new Error("Invalid session registry string array");return[...n]}function Te(n){if(n==="processing"||n==="completed"||n==="superseded")return n;throw new Error("Invalid session registry turn status")}var Me={projectId:a,channel:a,backend:a,kind:ee,origin:De,createdAt:a,lastUsedAt:a,label:E,starred:w,labelRenamed:w,selection:P,agentName:c,backendSessionId:c,lastReadAt:c,scheduleId:c,boardId:c,boardBlockFor:c,contextUsage:n=>n,teamLeadId:c,workerName:c,workerBrief:c,clean:w,workspaceDir:c},ne=Object.keys(Me),Fn=new Set(ne),ke={commissionId:"boardId",commissionBlockFor:"boardBlockFor",commissionDraft:null,workerRetiredAt:null,profileName:null,browser:null};function Oe(n){return Object.hasOwn(ke,n)?ke[n]:n}function Un(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid session registry patch fields");let e=n,t={};for(let i of Object.keys(e)){if(i==="profileName"){t[i]=e[i];continue}let r=Oe(i);if(r===null||r!==i&&Object.hasOwn(e,r))continue;let s=Me[r];if(!s)throw new Error(`Unknown session registry patch field: ${i}`);t[r]=s(e[i])}return t}function Ln(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid session registry turn record");let e=n;return{turnIndex:j(e.turnIndex),userMessageTs:a(e.userMessageTs),userMessageText:a(e.userMessageText),statusMessageTs:h(e.statusMessageTs),responseMessageTimestamps:Be(e.responseMessageTimestamps),executionId:h(e.executionId),backupPath:h(e.backupPath),...$n(e.anchor),status:Te(e.status),createdAt:a(e.createdAt),updatedAt:a(e.updatedAt)}}function $n(n){let e=G(n);return e?{anchor:e}:{}}var zn={turnIndex:j,userMessageTs:a,userMessageText:a,statusMessageTs:h,responseMessageTimestamps:Be,executionId:h,backupPath:h,anchor:G,status:Te,createdAt:a,updatedAt:a};function _n(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid session registry turn patch");let e=n,t={};for(let i of Object.keys(e)){let r=zn[i];if(!r)throw new Error(`Unknown session registry turn field: ${i}`);t[i]=r(e[i])}return t}var Hn={sessionId:h,backend:a,selection:P,updatedAt:a};function Yn(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid session registry conversation fields");let e=n,t={};for(let i of Object.keys(e)){if(i==="profileName"){t[i]=e[i];continue}let r=Hn[i];if(i!=="sessionName"){if(!r)throw new Error(`Unknown session registry conversation field: ${i}`);t[i]=r(e[i])}}return t}function Jn(n,e){e.op==="put"&&je(n,e.record),e.op==="delete-intent"&&Vn(n,e.record),e.op==="delete-commit"&&Ne(n,e.id),e.op==="patch"&&Kn(n,e.id)}function Kn(n,e){if(!n.live.has(e))throw new Error(`Patch for non-live session: ${e}`)}function je(n,e){if(n.pending.has(e.sessionId))throw new Error(`Cannot revive pending-deletion session: ${e.sessionId}`)}function Vn(n,e){if(!n.live.get(e.sessionId))throw new Error(`Delete intent for missing session: ${e.sessionId}`)}function Ne(n,e){if(!n.pending.has(e))throw new Error(`Delete commit for missing intent: ${e}`)}function Pe(n,e){if(e.op==="put")return Fe(n,e.record);if(e.op==="delete-intent")return qn(n,e.record,e.cleanup);if(e.op==="delete-commit")return et(n,e.id);if(e.op==="patch")return Wn(n,e);if(e.op==="bind")return Gn(n,e.channel,e.sessionId);if(e.op==="unbind")return Xn(n,e.channel);if(e.op==="conversation")return Zn(n,e);Qn(n,e)}function Wn(n,e){let t=n.live.get(e.id);if(!t)return;let i={...t,...e.fields};for(let r of e.unset??[])delete i[r];(i.selection||i.profileName===void 0)&&delete i.profileName,n.live.set(e.id,i)}function Gn(n,e,t){n.bindings.set(e,t)}function Xn(n,e){n.bindings.delete(e)}function Qn(n,e){let t=n.turns.get(e.channel)??[];if(e.kind==="begin")t.push(e.turn),n.turns.set(e.channel,t);else if(e.kind==="patch"){let i=t.findIndex(r=>r.turnIndex===e.turnIndex);i>=0&&(t[i]={...t[i],...e.fields})}else e.kind==="truncate"?n.turns.set(e.channel,t.filter(i=>i.turnIndex<e.fromIndex)):n.turns.delete(e.channel)}function Zn(n,e){if(e.kind==="clear"){n.conversations.delete(e.channel);return}let i={...n.conversations.get(e.channel)??{sessionId:null,backend:"",selection:null,updatedAt:""},...e.fields};i.selection&&delete i.profileName,n.conversations.set(e.channel,i)}function Fe(n,e){je(n,e),n.live.set(e.sessionId,e)}function qn(n,e,t={claudeBackupPaths:[]}){n.live.delete(e.sessionId),n.pending.set(e.sessionId,{session:e,cleanup:t})}function et(n,e){Ne(n,e),n.pending.delete(e);for(let[t,i]of n.bindings)i===e&&(n.bindings.delete(t),n.turns.delete(t),n.conversations.delete(t))}async function nt(n,e,t){let i=await u.open(n,"a+"),r=(await i.stat()).size;try{return await(t?t(i,e):i.writeFile(e,"utf8")),await i.sync(),(await i.stat()).size}catch(s){throw await i.truncate(r),await i.sync(),s}finally{await i.close()}}async function Ue(n,e){let t=`${n}.tmp.${process.pid}.${Date.now()}`;try{await tt(t,e),await u.rename(t,n),await it(n)}catch(i){throw await rt(t),i}}async function tt(n,e){let t=await u.open(n,"w");try{let i=[],r=0;for(let s of e){let o=`${JSON.stringify(s)}
|
|
6
|
+
`;i.push(o),r+=o.length,!(r<cn)&&(await t.writeFile(i.join(""),"utf8"),i=[],r=0)}i.length&&await t.writeFile(i.join(""),"utf8"),await t.sync()}finally{await t.close()}}async function it(n){if(process.platform==="win32")return;let e=await u.open(Q.dirname(n),"r");try{await e.sync()}finally{await e.close()}}async function rt(n){try{await u.rm(n,{force:!0})}catch(e){if(e.code!=="ENOENT")throw e}}async function ot(n){let e=await u.open(n,"r+");try{let t=(await e.stat()).size,i=await st(e,t);if(i===t)return;await e.truncate(i),await e.sync()}finally{await e.close()}}async function st(n,e){if(e===0)return 0;let t=Buffer.alloc(Math.min(e,4096));if(await n.read(t,0,t.length,e-t.length),t[t.length-1]===10)return e;let i=t.lastIndexOf(10);return i>=0?e-t.length+i+1:at(n,e-t.length)}async function at(n,e){let t=e;for(;t>0;){let i=Math.min(t,4096),r=Buffer.alloc(i);t-=i,await n.read(r,0,i,t);let s=r.lastIndexOf(10);if(s>=0)return t+s+1}return 0}async function N(n){try{return await u.stat(n)}catch{return null}}async function ct(){await new Promise(n=>setImmediate(n))}var dt=$e.join(g,"session-registry.jsonl");function ut(n,e){let t={},i=[];for(let r of ne){let s=n[r],o=e[r],l=s!==void 0,R=o!==void 0;if(!(!l&&!R)){if(l&&!R){i.push(r);continue}lt(s,o)||(t[r]=o)}}return Object.keys(t).length===0&&i.length===0?null:{fields:t,unset:i}}function S(n){return{...n,selection:n.selection?{...n.selection}:null}}function m(n){return Array.from(n,S).sort((e,t)=>t.lastUsedAt.localeCompare(e.lastUsedAt))}function ft(n){return Array.from(n,e=>({session:S(e.session),cleanup:{claudeBackupPaths:[...e.cleanup.claudeBackupPaths]}})).sort((e,t)=>t.session.lastUsedAt.localeCompare(e.session.lastUsedAt))}function te(n){return n?.substring(0,60)||null}function ht(n){return n instanceof Date?n.getTime():n}function pt(n){let e=new Date(n).getTime();return Number.isFinite(e)?e:null}function mt(n,e){return e===null?(delete n.contextUsage,n):(n.contextUsage=e,n)}function ze(n){return n.backendSessionId===void 0?n.sessionId:n.backendSessionId}var re=class{filePath;mutex=new y;options;state=A();loaded=!1;conduitResolvers=[];constructor(e=dt,t={}){this.filePath=e,this.options=t}async registerSession(e){await this.withState(t=>this.doRegisterSession(t,e))}async doRegisterSession(e,t){let i=new Date().toISOString();await this.writePut(e,{sessionId:t.sessionId,projectId:t.projectId??"general",channel:t.channel,backend:t.backend,kind:t.kind,origin:t.origin??(t.kind==="scheduled"?"scheduled":"direct"),createdAt:i,lastUsedAt:i,label:te(t.label),selection:t.selection?{...t.selection}:null,agentName:t.agentName??null,backendSessionId:t.backendSessionId??null,scheduleId:t.scheduleId??null,boardId:t.boardId??null,...t.teamLeadId?{teamLeadId:t.teamLeadId,workerName:t.workerName??null,workerBrief:t.workerBrief??null}:{},...t.clean?{clean:!0,workspaceDir:t.workspaceDir??null}:{}})}async convertToDirect(e,t){return this.updateById(e,i=>({...i,channel:t.channel,kind:"local",origin:"direct"}))}async updateSession(e,t){if("sessionId"in t)throw new Error("updateSession may not change sessionId");await this.withState(i=>this.doUpdateSession(i,e,t))}async doUpdateSession(e,t,i){let r=e.live.get(t);r&&await this.writePatch(e,r,{...r,lastUsedAt:i.lastUsedAt??r.lastUsedAt,label:i.label!==void 0?te(i.label):r.label,selection:i.selection!==void 0?i.selection:r.selection,backend:i.backend??r.backend,agentName:i.agentName!==void 0?i.agentName:r.agentName,backendSessionId:i.backendSessionId!==void 0?i.backendSessionId:r.backendSessionId,contextUsage:i.contextUsage!==void 0?i.contextUsage:r.contextUsage})}async updateContextUsage(e,t){await this.updateById(e,i=>mt({...i},t))}async listRecentSessions(e=10){return this.withState(async t=>m(t.live.values()).slice(0,e))}async getById(e){return this.withState(async t=>{let i=t.live.get(e);return i?S(i):null})}async listByProject(e){return this.withState(async t=>m(F(t,i=>i.projectId===e)))}async listByOrigin(e,t){return this.withState(async i=>m(F(i,r=>r.origin===e&&(t===void 0||r.projectId===t))))}async listWorkers(e){return this.withState(async t=>m(F(t,i=>i.teamLeadId===e)))}async listResumable(e){return this.withState(async t=>m(F(t,i=>i.kind!=="scheduled"&&(e===void 0||i.projectId===e))))}async touchSessionUse(e){return this.withState(async t=>{let i=t.live.get(e);return!i||t.pending.has(e)?!1:(await this.writePatch(t,i,{...i,lastUsedAt:new Date().toISOString()}),!0)})}async setStarred(e,t){return this.updateById(e,i=>({...i,starred:t}))}async rename(e,t){return this.updateById(e,i=>({...i,label:t,labelRenamed:!0}))}async fillLabelIfAbsent(e,t){let i=te(t.trim());return this.updateById(e,r=>r.label?.trim()||!i?r:{...r,label:i})}async markRead(e){await this.updateById(e,t=>({...t,lastReadAt:new Date().toISOString()}))}async bindBoard(e,t){return this.updateById(e,i=>i.boardId===t?i:{...i,boardId:t})}async markBoardBlockDelivered(e,t){return this.updateById(e,i=>({...i,boardBlockFor:t}))}async clearBoardBlockDelivery(e){return this.updateById(e,t=>t.boardBlockFor==null?t:{...t,boardBlockFor:null})}registerConduitResolver(e){return this.conduitResolvers.push(e),()=>{let t=this.conduitResolvers.indexOf(e);t>=0&&this.conduitResolvers.splice(t,1)}}async getBoundSessionId(e){for(let t of this.conduitResolvers){let i=t(e);if(typeof i=="string"&&i)return i}return this.withState(async t=>t.bindings.get(e)??null)}async bindChannel(e,t){await this.withState(i=>this.doBindChannel(i,e,t))}async unbindChannel(e){await this.withState(t=>this.doUnbindChannel(t,e))}async releaseChannels(e){let t=new Set(e);return t.size===0?0:this.withState(async i=>{let r=Array.from(i.bindings).filter(([,o])=>t.has(o)).map(([o])=>o),s=Array.from(i.conversations).filter(([,o])=>o.sessionId&&t.has(o.sessionId)).map(([o])=>o);return await this.appendBatch(i,[...r.map(o=>({v:1,op:"unbind",channel:o})),...s.flatMap(o=>[{v:1,op:"conversation",channel:o,kind:"clear"},{v:1,op:"turn",channel:o,kind:"clear"}])]),new Set([...r,...s]).size})}async listBindings(){return this.withState(async e=>Array.from(e.bindings,([t,i])=>({channel:t,sessionId:i})))}async beginTurn(e,t){await this.withState(i=>this.doBeginTurn(i,e,t))}async patchTurn(e,t,i){await this.withState(r=>this.doPatchTurn(r,e,t,i))}async truncateTurns(e,t){await this.withState(i=>this.doTruncateTurns(i,e,t))}async clearTurns(e){await this.withState(t=>this.doClearTurns(t,e))}async getTurns(e){return this.withState(async t=>x(t,e))}async getConversationHeader(e){return this.withState(async t=>ie(t,e))}async setConversation(e,t){await this.withState(i=>this.doSetConversation(i,e,t))}async clearConversation(e){await this.withState(t=>this.doClearConversation(t,e))}async readConversation(e){return this.withState(async t=>{let i=ie(t,e);return i?{header:i,turns:x(t,e)}:null})}async listConversations(){return this.withState(async e=>Array.from(e.conversations,([t,i])=>({channel:t,header:{...i},turns:x(e,t)})))}async batch(e){return this.withState(t=>e(this.batchOps(t)))}batchOps(e){return{registerSession:t=>this.doRegisterSession(e,t),updateSession:(t,i)=>{if("sessionId"in i)throw new Error("updateSession may not change sessionId");return this.doUpdateSession(e,t,i)},updateById:(t,i)=>this.doUpdateById(e,t,i),bindChannel:(t,i)=>this.doBindChannel(e,t,i),unbindChannel:t=>this.doUnbindChannel(e,t),beginTurn:(t,i)=>this.doBeginTurn(e,t,i),patchTurn:(t,i,r)=>this.doPatchTurn(e,t,i,r),truncateTurns:(t,i)=>this.doTruncateTurns(e,t,i),clearTurns:t=>this.doClearTurns(e,t),setConversation:(t,i)=>this.doSetConversation(e,t,i),clearConversation:t=>this.doClearConversation(e,t),getTurns:t=>x(e,t),getConversationHeader:t=>ie(e,t)}}async doBindChannel(e,t,i){e.bindings.get(t)!==i&&(await f(this.filePath,e,{v:1,op:"bind",channel:t,sessionId:i},this.options),await this.maybeCompact(e))}async doUnbindChannel(e,t){e.bindings.has(t)&&(await f(this.filePath,e,{v:1,op:"unbind",channel:t},this.options),await this.maybeCompact(e))}async doBeginTurn(e,t,i){await f(this.filePath,e,{v:1,op:"turn",channel:t,kind:"begin",turn:{...i}},this.options),await this.maybeCompact(e)}async doPatchTurn(e,t,i,r){await f(this.filePath,e,{v:1,op:"turn",channel:t,kind:"patch",turnIndex:i,fields:{...r}},this.options),await this.maybeCompact(e)}async doTruncateTurns(e,t,i){await f(this.filePath,e,{v:1,op:"turn",channel:t,kind:"truncate",fromIndex:i},this.options),await this.maybeCompact(e)}async doClearTurns(e,t){await f(this.filePath,e,{v:1,op:"turn",channel:t,kind:"clear"},this.options),await this.maybeCompact(e)}async doSetConversation(e,t,i){await f(this.filePath,e,{v:1,op:"conversation",channel:t,kind:"set",fields:{...i}},this.options),await this.maybeCompact(e)}async doClearConversation(e,t){e.conversations.has(t)&&(await f(this.filePath,e,{v:1,op:"conversation",channel:t,kind:"clear"},this.options),await this.maybeCompact(e))}async listPendingDeletions(){return this.withState(async e=>ft(e.pending.values()))}async beginDeleteExpired(e,t,i=Le){return this.withState(async r=>{let s=yt(m(r.live.values()),ht(e),new Set(t));return this.writeDeleteIntents(r,s,i)})}async beginDelete(e,t=Le){return this.withState(async i=>{let r=new Set(e),s=m(i.live.values()).filter(o=>r.has(o.sessionId)||!!o.teamLeadId&&r.has(o.teamLeadId));return this.writeDeleteIntents(i,s,t)})}async commitDeletion(e){return(await this.commitDeletions([e])).length>0}async commitDeletions(e){return this.withState(async t=>{let i=[...new Set(e)].filter(r=>t.pending.has(r));return await this.appendBatch(t,i.map(r=>({v:1,op:"delete-commit",id:r}))),i})}async compactNow(){await this.withState(async e=>{await q(this.filePath,e,this.options)})}invalidate(){this.state=A(),this.loaded=!1}flush(){return this.mutex.run(async()=>{})}withState(e){return this.mutex.run(async()=>e(await this.loadState()))}async loadState(){return this.loaded||(this.state=await Ce(this.filePath,this.options),this.loaded=!0),this.state}async writePut(e,t){await f(this.filePath,e,{v:1,op:"put",id:t.sessionId,record:t},this.options),await this.maybeCompact(e)}async updateById(e,t){return this.withState(i=>this.doUpdateById(i,e,t))}async doUpdateById(e,t,i){let r=e.live.get(t);if(!r)return null;let s=i(S(r));return await this.writePatch(e,r,s),s}async writePatch(e,t,i){let r=ut(t,i);r&&(await f(this.filePath,e,{v:1,op:"patch",id:t.sessionId,fields:r.fields,...r.unset.length?{unset:r.unset}:{}},this.options),await this.maybeCompact(e))}async writeDeleteIntents(e,t,i){let r=gt(e),s=[];for(let o of t){let l=(r.get(o.sessionId)??[]).flatMap(R=>x(e,R));s.push({session:S(o),cleanup:await i(S(o),l)})}return await this.appendBatch(e,s.map(({session:o,cleanup:l})=>({v:1,op:"delete-intent",id:o.sessionId,record:o,cleanup:l}))),s}async appendBatch(e,t){t.length!==0&&(await Z(this.filePath,e,t,this.options),await this.maybeCompact(e))}async maybeCompact(e){xe(e,this.options)&&await q(this.filePath,e,this.options)}},Le=async()=>({claudeBackupPaths:[]});function yt(n,e,t){let i=o=>{if(o.starred===!0||o.boardId)return!1;let l=pt(o.lastUsedAt);return l!==null&&l<e},r=new Set(n.filter(o=>!o.teamLeadId&&!t.has(o.sessionId)&&i(o)).map(o=>o.sessionId)),s=new Set(n.map(o=>o.sessionId));return n.filter(o=>{if(t.has(o.sessionId)||o.starred===!0)return!1;let l=o.teamLeadId&&s.has(o.teamLeadId)?o.teamLeadId:null;return l?r.has(l):i(o)})}function x(n,e){return(n.turns.get(e)??[]).map(t=>({...t}))}function ie(n,e){let t=n.conversations.get(e);return t?{...t}:null}function gt(n){let e=new Map;for(let[t,i]of n.conversations){if(!i.sessionId)continue;let r=e.get(i.sessionId)??[];r.push(t),e.set(i.sessionId,r)}return e}function*F(n,e){for(let t of n.live.values())e(t)&&(yield t)}var b=new re;pe(b);var _e=null;function wt(n){let e=n;if(T(e?.default),!Array.isArray(e.favorites))throw new Error("favorites must be an array");let t=new Set;for(let i of e.favorites){H(i);let r=B(i);if(t.has(r))throw new Error(`Duplicate favorite: ${i.model}`);t.add(r)}}function L(){try{let n=M.readSync();return n!==_e&&(wt(n),_e=n),{default:p(n.default),favorites:n.favorites.map(U)}}catch(n){throw new Error(`Failed to load models.json: ${n.message}`)}}function U({backend:n,provider:e,model:t}){return{backend:n,provider:e,model:t}}function I(){return L().default}function li(){return L().favorites}function He(){return M.readIfPresent()?.default?I():null}function $(n){let e;try{e=L()}catch{return null}if(e.default.backend===n)return U(e.default);let t=e.favorites.find(i=>i.backend===n);return t?U(t):null}function St(n){let e=n.indexOf("/");if(e<0)return null;let t={backend:"pi",provider:n.slice(0,e),model:n.slice(e+1)};return H(t),t}function bt(n,e){let t=[e.default,...e.favorites].filter(s=>s.backend==="pi"),i=ye(me.peek(),n).filter(s=>s.backend==="pi"),r=[...t,...i].find(s=>s.model===n);if(r)return U(r);if(e.default.backend==="pi")return{backend:"pi",provider:e.default.provider,model:n};throw new Error(`Unknown PI model '${n}': specify provider/model or favorite a model first`)}function di(n,e){let t=n.trim();if(!t)throw new Error("Model must be a non-empty string");let i=St(t);if(i)return i;let r=L();return(e??r.default.backend)==="claude"?{backend:"claude",provider:null,model:t}:bt(t,r)}import{readFileSync as It,renameSync as kt,writeFileSync as vt}from"node:fs";import*as Ke from"node:path";var ae=Ke.join(g,"agent-state.json");function z(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function Ye(n){let e=D(n);try{return T(e),p(e)}catch{return null}}function oe(n,e){let t=Object.entries(z(n)).map(([i,r])=>[i,e(r)]);return Object.fromEntries(t.filter(([,i])=>i!==null))}function At(n){let e=z(n);return e.thinking===null||typeof e.thinking=="string"&&!!e.thinking?{thinking:e.thinking}:null}function se(n){return typeof n=="string"&&n?n:null}function Je(n){let e=z(n),t={channelSelections:oe(e.channelSelections,Ye),modelMemory:oe(e.modelMemory,At),defaultAgent:se(e.defaultAgent),channelAgents:oe(e.channelAgents,se)},i=Ye(e.selectionDefault);if(i){t.selectionDefault=i;let r=se(z(e.selectionDefault).agentName);r&&(t.selectionDefault.agentName=r)}return t}function ce(){try{return Je(JSON.parse(It(ae,"utf8")))}catch{return Je(null)}}function Ve(n){let e={};for(let i of["channelSelections","modelMemory","channelAgents"])Object.keys(n[i]).length&&(e[i]=n[i]);n.defaultAgent&&(e.defaultAgent=n.defaultAgent),n.selectionDefault&&(e.selectionDefault=n.selectionDefault);let t=`${ae}.tmp`;vt(t,JSON.stringify(e)),kt(t,ae)}var d=ce();function bi(){d=ce()}function k(n){Ve(n),d=n}function le(n,e,t){let i={...n};return t!==null?i[e]=t:delete i[e],i}function C(n){let e=n?d.channelSelections[n]:null;return e?p(e):null}function We(n,e){let t=e?p(e):null;k({...d,channelSelections:le(d.channelSelections,n,t)})}function Ge(){return Object.fromEntries(Object.entries(d.modelMemory).map(([n,e])=>[n,{...e}]))}function Xe(n){let e={thinking:n.thinking};k({...d,modelMemory:le(d.modelMemory,B(n),e)})}function Ii(){try{return $("claude")?.model??"opus"}catch{return"opus"}}function ki(n){let e=C(n);if(e)return e.backend;try{return I().backend}catch{return"claude"}}function Qe(n){let e=n?.agentName??d.selectionDefault?.agentName,t=n?{...p(n),...e?{agentName:e}:{}}:void 0;k({...d,selectionDefault:t})}function vi(n){let e={...d.selectionDefault??I()};n?e.agentName=n:delete e.agentName,k({...d,selectionDefault:e})}function Ai(){return d.selectionDefault?{...d.selectionDefault}:null}function Ei(n){return n&&d.channelAgents[n]||d.defaultAgent}function Et(n,e){if(!e)return k({...d,defaultAgent:n});k({...d,channelAgents:le(d.channelAgents,e,n)})}function xi(n){d.channelAgents[n]&&Et(null,n)}function Ci(){return{...d.channelAgents}}var xt={selection:He,forBackend:$};function Ct(n={}){return{...n,defaults:xt,memory:Ge}}function Ze(n,e={}){return ge(Ct(n),e)}async function qe(n){let e=await b.getBoundSessionId(n);return e?b.getById(e):null}async function ji(n){let e=await qe(n),t=Ze({session:e?.selection,draft:C(n)});if(t.ok===!1)throw new Error(`No model is configured for this conversation (${t.reason})`);return t.effective}function Ni(n){return C(n)??I()}function Rt(n){let e=n.currentBackend!==n.targetBackend;return n.hasHistory&&e?{allowed:!1,reason:"cross-backend-live-session"}:{allowed:!0,backendChanged:e}}function en(n,e,t){return{...n??{backend:"claude",provider:null,model:"",thinking:null,connection:null},ok:!1,backendChanged:!1,reason:e,...t?{allowed:t}:{}}}function Dt(n){let{channel:e,seedDefault:t,inventory:i,catalog:r,...s}=n;return s}var Bt=new y;function Pi(n){return Bt.run(()=>Tt(n))}async function Tt(n){let e=await qe(n.channel),t=Ze({session:e?.selection,draft:C(n.channel),inventory:n.inventory,catalog:n.catalog},Dt(n));return t.ok===!1?en(t.base,t.reason,t.allowed):Mt(n,t.base,t.selection,e)}async function Mt(n,e,t,i){let r=!!(i&&ze(i))||(await b.getTurns(n.channel)).length>0,s=i?.backend??e?.backend??t.backend,o=Rt({currentBackend:s,targetBackend:t.backend,hasHistory:r});return o.allowed?(i&&await b.updateSession(i.sessionId,{backend:t.backend,selection:t}),We(n.channel,t),Xe(t),n.channel.startsWith("web:")&&n.seedDefault!==!1&&Qe(t),{...t,ok:!0,backendChanged:o.backendChanged}):{...en(e,"cross-backend-live-session"),currentBackend:s,targetBackend:t.backend}}export{Ie as a,$t as b,zt as c,M as d,_t as e,Ht as f,I as g,li as h,He as i,di as j,ze as k,re as l,b as m,bi as n,C as o,We as p,Ge as q,Xe as r,Ii as s,ki as t,vi as u,Ai as v,Ei as w,Et as x,xi as y,Ci as z,Ze as A,ji as B,Ni as C,Pi as D};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
2
|
const require = __cortexCreateRequire(import.meta.url);
|
|
3
3
|
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as K}from"./chunk-
|
|
4
|
+
import{a as K}from"./chunk-V35MFAUQ.js";import{e as I}from"./chunk-AVXDF7AG.js";import{e as A}from"./chunk-VBN2JSER.js";import{s as S}from"./chunk-Z24SBRJK.js";import{e as Y}from"./chunk-WHC7AYZD.js";var j=Y(K(),1);import*as u from"fs";import*as f from"path";var b=A("index-regen"),C=["experiments","knowledge","patterns"],X=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,H=/^([A-Za-z_][\w-]*):(?:\s|$)/;function N(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function J(t){let s={},r=null,i=[],c=()=>{if(!r)return;let o=i.join(`
|
|
5
5
|
`);try{let n=(0,j.parse)(o);s[r]=N(n)?n[r]:null}catch{s[r]=o.slice(r.length+1).trim()}};for(let o of t.split(/\r?\n/)){let n=H.exec(o);n?(c(),r=n[1],i=[o]):r&&i.push(o)}return c(),s}function B(t){let s=X.exec(t);if(!s)return{meta:{},valid:!0};try{let r=(0,j.parse)(s[1]);if(N(r))return{meta:r,valid:!0}}catch{}return{meta:J(s[1]),valid:!1}}function w(t){return Array.isArray(t)?t.map(s=>String(s)):[]}function V(t){let s=new Map,r;try{r=u.readFileSync(f.join(t,"_meta","access-log.jsonl"),"utf8")}catch{return s}for(let i of r.split(`
|
|
6
6
|
`)){if(!i.trim())continue;let c;try{c=JSON.parse(i)}catch{continue}if(typeof c.file!="string")continue;let o=typeof c.ts=="string"?c.ts:null,n=s.get(c.file);if(!n){s.set(c.file,{refs:1,lastRef:o});continue}n.refs++,o&&(!n.lastRef||o>n.lastRef)&&(n.lastRef=o)}return s}var q={refs:0,lastRef:null};function z(t){let s;try{s=u.readdirSync(t).sort()}catch{return[]}let r=[];for(let i of s){if(i==="index.md"||i.startsWith("_")||i.startsWith(".")||!i.endsWith(".md"))continue;let c;try{c=u.readFileSync(f.join(t,i),"utf8")}catch{continue}let{meta:o,valid:n}=B(c);o.id===void 0||o.id===null||o.id===""||(n||b.warn(`${f.join(t,i)}: frontmatter is not valid YAML, read key by key`),r.push({id:String(o.id),filename:i,meta:o,validFrontmatter:n}))}return r}var Z=["invalidated"],G=["superseded","deprecated"],Q=["refined","stale"];function m(t){let s=t.meta.status;return s==null?"":String(s)}function T(t){if(!t)return!0;let s=t.toLowerCase();return!(Z.some(r=>s.startsWith(r))||G.some(r=>s.startsWith(r))||Q.includes(s))}function k(t){return t.toLowerCase().startsWith("invalidated")}var ee={experiments:"Use when: reviewing past experiment results, checking what has been tried, or looking for related prior work before designing a new experiment.",knowledge:"Use when: applying validated facts/principles to current work, checking if a question has already been answered, or verifying assumptions against established knowledge.",patterns:"Use when: looking for cross-experiment regularities, anti-patterns to avoid, or established best practices before making design decisions."},te="> Auto-generated from YAML frontmatter; Refs / Last ref come from _meta/access-log.jsonl. Do not edit manually. Not tracked by git.";function a(t,s){if(t==null)return"";let r=(typeof t=="object"?JSON.stringify(t):String(t)).replace(/\s*\r?\n\s*/g," ");return s!==void 0&&(r=r.slice(0,s)),r.replace(/\|/g,"\\|")}function g(t,...s){for(let r of s){let i=t.meta[r];if(i!=null&&i!=="")return i}}function L(t){return w(t.meta.tags).slice(0,4).map(s=>`\`${a(s)}\``).join(", ")}function _(t,s){I(f.join(t,"index.md"),s)}function ne(t,s){let r=z(t),i=f.basename(t),c=ee[i]||"",o=new Date().toISOString().slice(0,19),n=[`# ${s}`,""];if(c&&n.push(c,""),n.push(te,`> Last updated: ${o}`,""),r.length===0){n.push("_No entries._",""),_(t,n.join(`
|
|
7
7
|
`));return}let W=V(f.dirname(t)),p=e=>W.get(e.filename)??q,x=e=>`${p(e).refs} | ${p(e).lastRef?.slice(0,10)??""}`,d=r.filter(e=>T(m(e))),y=r.filter(e=>k(m(e))),$=r.filter(e=>!T(m(e))&&!k(m(e)));d.sort((e,l)=>{let h=p(l).refs-p(e).refs;return h!==0?h:String(l.meta.date??"").localeCompare(String(e.meta.date??""))});let F=r.some(e=>e.id.startsWith("EXP-")),O=r.some(e=>e.id.startsWith("K-"));if(n.push(`## Active (${d.length} entries)`,""),F){n.push("| ID | Date | Summary | Tags | Refs | Last ref | Links |"),n.push("|----|------|---------|------|------|----------|-------|");for(let e of d){let l=w(e.meta.links).map(h=>a(h)).join(", ");n.push(`| ${a(e.id)} | ${a(e.meta.date)} | ${a(g(e,"summary")??"\u2014",100)} | ${L(e)} | ${x(e)} | ${l} |`)}}else if(O){n.push("| ID | Title | Source | Refs | Last ref |"),n.push("|----|-------|--------|------|----------|");for(let e of d)n.push(`| ${a(e.id)} | ${a(g(e,"title","summary")??"\u2014")} | ${a(e.meta.source)} | ${x(e)} |`)}else{n.push("| ID | Summary | Tags | Sources | Refs | Last ref |"),n.push("|----|---------|------|---------|------|----------|");for(let e of d){let l=w(e.meta["source-experiments"]).map(h=>a(h)).join(", ");n.push(`| ${a(e.id)} | ${a(g(e,"summary","title")??"\u2014")} | ${L(e)} | ${l} | ${x(e)} |`)}}if(y.length>0){n.push("",`## Invalidated (${y.length} entries)`,""),n.push("> These entries have been proven wrong. Do NOT use their conclusions. Kept for audit trail only."),n.push(""),n.push("| ID | Date | Summary | Invalidated By | Refs |"),n.push("|----|------|---------|----------------|------|");for(let e of y){let l=m(e).replace(/^invalidated:/i,"").trim();n.push(`| ${a(e.id)} | ${a(e.meta.date)} | ${a(g(e,"summary","title")??"\u2014",80)} | ${a(l)} | ${p(e).refs} |`)}}if($.length>0){n.push("",`## Superseded / Deprecated (${$.length} entries)`,""),n.push("| ID | Date | Summary | Status | Refs |"),n.push("|----|------|---------|--------|------|");for(let e of $)n.push(`| ${a(e.id)} | ${a(e.meta.date)} | ${a(g(e,"summary","title")??"\u2014",80)} | ${a(m(e))} | ${p(e).refs} |`)}let D=5,R=14,M=Date.now(),P=d.filter(e=>p(e).refs>=D).map(e=>e.id),U=d.filter(e=>{if(p(e).refs>0)return!1;let l=e.meta.date?new Date(String(e.meta.date)):null;return!l||isNaN(l.getTime())?!1:(M-l.getTime())/864e5>R}).map(e=>e.id),E=d.filter(e=>m(e).toLowerCase().startsWith("challenged")),v=r.filter(e=>!e.validFrontmatter);n.push("","## Stats"),n.push(`- Total: ${r.length} (${d.length} active, ${y.length} invalidated, ${$.length} superseded/deprecated)`),E.length>0&&n.push(`- Challenged (under review): ${E.map(e=>e.id).join(", ")}`),n.push(`- Hot (refs >= ${D}): ${P.slice(0,10).join(", ")||"none"}`),n.push(`- Cold (refs=0, age>${R}d): ${U.slice(0,10).join(", ")||"none"}`),v.length>0&&n.push(`- Invalid YAML frontmatter (fix the file): ${v.map(e=>e.filename).join(", ")}`),n.push(""),_(t,n.join(`
|
|
@@ -0,0 +1,7 @@
|
|
|
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 ii}from"./chunk-I6OPDRVF.js";import{e as ti,f as ri}from"./chunk-LP72AF56.js";import{e as Se}from"./chunk-VBN2JSER.js";import{a as F,c as f}from"./chunk-WHC7AYZD.js";var ee=f(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.ErrorCode=void 0;U.errorWithCode=V;U.requestErrorWithOriginal=ni;U.httpErrorFromResponse=ai;U.platformErrorFromResult=oi;U.rateLimitedErrorWithDelay=li;var $;(function(r){r.RequestError="slack_webapi_request_error",r.HTTPError="slack_webapi_http_error",r.PlatformError="slack_webapi_platform_error",r.RateLimitedError="slack_webapi_rate_limited_error",r.FileUploadInvalidArgumentsError="slack_webapi_file_upload_invalid_args_error",r.FileUploadReadFileDataError="slack_webapi_file_upload_read_file_data_error"})($||(U.ErrorCode=$={}));function V(r,e){let t=r;return t.code=e,t}function ni(r,e){let t=V(new Error(`A request error occurred: ${r.message}`),$.RequestError);return e&&(t.original=r),t}function ai(r){let e=V(new Error(`An HTTP protocol error occurred: statusCode = ${r.status}`),$.HTTPError);e.statusCode=r.status,e.statusMessage=r.statusText;let t={};for(let i of Object.keys(r.headers))i&&r.headers[i]&&(t[i]=r.headers[i]);return e.headers=t,e.body=r.data,e}function oi(r){let e=V(new Error(`An API error occurred: ${r.error}`),$.PlatformError);return e.data=r,e}function li(r){let e=V(new Error(`A rate-limit has been reached, you may retry this request in ${r} seconds`),$.RateLimitedError);return e.retryAfter=r,e}});var Re=f((qs,ui)=>{ui.exports={name:"@slack/web-api",version:"7.19.0",description:"Official library for using the Slack Platform's Web API",author:"Slack Technologies, LLC",license:"MIT",keywords:["slack","web-api","bot","client","http","api","proxy","rate-limiting","pagination"],main:"dist/index.js",types:"./dist/index.d.ts",files:["dist/**/*"],engines:{node:">= 18",npm:">= 8.6.0"},repository:{type:"git",url:"git+https://github.com/slackapi/node-slack-sdk.git"},homepage:"https://docs.slack.dev/tools/node-slack-sdk/web-api/",publishConfig:{access:"public"},bugs:{url:"https://github.com/slackapi/node-slack-sdk/issues"},scripts:{build:"npm run build:clean && tsc","build:clean":"shx rm -rf ./dist",docs:"npx typedoc --plugin typedoc-plugin-markdown",prepack:"npm run build",test:"npm run build && bash -c 'node --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=test-results.xml --import tsx --test src/*.test.ts'","test:coverage":"npm run build && node --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=lcov.info --test-reporter=junit --test-reporter-destination=test-results.xml --import tsx --test src/*.test.ts","test:integration":"npm run build && node test/integration/commonjs-project/index.js && node test/integration/esm-project/index.mjs && npm run test:integration:ts","test:integration:ts":"cd test/integration/ts-4.7-project && npm i && npm run build","test:types":"tsd",watch:"npx nodemon --watch 'src' --ext 'ts' --exec npm run build"},dependencies:{"@slack/logger":"^4.0.1","@slack/types":"^2.21.0","@types/node":">=18","@types/retry":"0.12.0",axios:"^1.16.0",eventemitter3:"^5.0.1","form-data":"^4.0.4","is-electron":"2.2.2","is-stream":"^2","p-queue":"^6","p-retry":"^4",retry:"^0.13.1"},devDependencies:{"@types/busboy":"^1.5.4","@types/sinon":"^21",busboy:"^1",nock:"^14",sinon:"^21",tsd:"^0.33.0"},tsd:{directory:"test/types"}}});var ue=f(R=>{"use strict";var ci=R&&R.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),di=R&&R.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),hi=R&&R.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&ci(t,e,i[n]);return di(t,e),t}})();Object.defineProperty(R,"__esModule",{value:!0});R.addAppMetadata=_i;R.getUserAgent=vi;var Te=hi(F("node:os")),fi=F("node:path"),Ue=Re();function Le(r){return r.replace("/",":")}var pi=255;function mi(r){let e="";for(let t of r)e+=t.charCodeAt(0)<=pi?t:encodeURIComponent(t);return e}var gi=`${Le(Ue.name)}/${Ue.version} ${mi((0,fi.basename)(process.title))}/${process.version.replace("v","")} ${Te.platform()}/${Te.release()}`,Fe={};function _i({name:r,version:e}){Fe[Le(r)]=e}function vi(){let r=Object.entries(Fe).map(([e,t])=>`${e}/${t}`).join(" ");return(r.length>0?`${r} `:"")+gi}});var ce=f(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.ConsoleLogger=N.LogLevel=void 0;var P;(function(r){r.ERROR="error",r.WARN="warn",r.INFO="info",r.DEBUG="debug"})(P||(N.LogLevel=P={}));var J=class r{constructor(){this.level=P.INFO,this.name=""}getLevel(){return this.level}setLevel(e){this.level=e}setName(e){this.name=e}debug(...e){r.isMoreOrEqualSevere(P.DEBUG,this.level)&&console.debug(r.labels.get(P.DEBUG),this.name,...e)}info(...e){r.isMoreOrEqualSevere(P.INFO,this.level)&&console.info(r.labels.get(P.INFO),this.name,...e)}warn(...e){r.isMoreOrEqualSevere(P.WARN,this.level)&&console.warn(r.labels.get(P.WARN),this.name,...e)}error(...e){r.isMoreOrEqualSevere(P.ERROR,this.level)&&console.error(r.labels.get(P.ERROR),this.name,...e)}static isMoreOrEqualSevere(e,t){return r.severity[e]>=r.severity[t]}};N.ConsoleLogger=J;J.labels=(()=>{let e=Object.entries(P).map(([t,i])=>[i,`[${t}] `]);return new Map(e)})();J.severity={[P.ERROR]:400,[P.WARN]:300,[P.INFO]:200,[P.DEBUG]:100}});var de=f(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.LogLevel=void 0;G.getLogger=wi;var yi=ce(),bi=ce();Object.defineProperty(G,"LogLevel",{enumerable:!0,get:function(){return bi.LogLevel}});var De=0;function wi(r,e,t){let i=De;De+=1;let n=t!==void 0?t:new yi.ConsoleLogger;return n.setName(`web-api:${r}:${i}`),e!==void 0&&n.setLevel(e),n}});var he=f(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.rapidRetryPolicy=q.fiveRetriesInFiveMinutes=q.tenRetriesInAboutThirtyMinutes=void 0;q.tenRetriesInAboutThirtyMinutes={retries:10,factor:1.96821,randomize:!0};q.fiveRetriesInFiveMinutes={retries:5,factor:3.86};q.rapidRetryPolicy={minTimeout:0,maxTimeout:1};var Oi={tenRetriesInAboutThirtyMinutes:q.tenRetriesInAboutThirtyMinutes,fiveRetriesInFiveMinutes:q.fiveRetriesInFiveMinutes,rapidRetryPolicy:q.rapidRetryPolicy};q.default=Oi});var $e=f(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0})});var ze=f(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0})});var me=f(z=>{"use strict";var fe=z&&z.__rest||function(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(r);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(r,i[n])&&(t[i[n]]=r[i[n]]);return t};Object.defineProperty(z,"__esModule",{value:!0});z.ChatStreamer=void 0;var pe=class{constructor(e,t,i,n){var o;this.buffer="",this.client=e,this.logger=t,this.options={buffer_size:(o=n.buffer_size)!==null&&o!==void 0?o:256},this.state="starting",this.streamArgs=i}get ts(){return this.streamTs}async append(e){if(this.state==="completed")throw new Error(`failed to append stream: stream state is ${this.state}`);let{markdown_text:t,chunks:i}=e,n=fe(e,["markdown_text","chunks"]);if(n.token&&(this.token=n.token),t&&(this.buffer+=t),this.buffer.length>=this.options.buffer_size||i)return await this.flushBuffer(Object.assign({chunks:i},n));let o={bufferLength:this.buffer.length,bufferSize:this.options.buffer_size,channel:this.streamArgs.channel,recipientTeamId:this.streamArgs.recipient_team_id,recipientUserId:this.streamArgs.recipient_user_id,threadTs:this.streamArgs.thread_ts};return this.logger.debug(`ChatStreamer appended to buffer: ${JSON.stringify(o)}`),null}async stop(e){if(this.state==="completed")throw new Error(`failed to stop stream: stream state is ${this.state}`);let t=e??{},{markdown_text:i,chunks:n}=t,o=fe(t,["markdown_text","chunks"]);if(o.token&&(this.token=o.token),i&&(this.buffer+=i),!this.streamTs){let a=await this.client.chat.startStream(Object.assign(Object.assign({},this.streamArgs),{token:this.token}));if(!a.ts)throw new Error("failed to stop stream: stream not started");this.streamTs=a.ts,this.state="in_progress"}let l=[];this.buffer.length>0&&l.push({type:"markdown_text",text:this.buffer}),n&&l.push(...n);let u=await this.client.chat.stopStream(Object.assign({token:this.token,channel:this.streamArgs.channel,ts:this.streamTs,chunks:l},o));return this.state="completed",u}async flushBuffer(e){let t=e??{},{chunks:i}=t,n=fe(t,["chunks"]),o=[];if(this.buffer.length>0&&o.push({type:"markdown_text",text:this.buffer}),i&&o.push(...i),!this.streamTs){let u=await this.client.chat.startStream(Object.assign(Object.assign(Object.assign({},this.streamArgs),{token:this.token,chunks:o}),n));return this.buffer="",this.streamTs=u.ts,this.state="in_progress",u}let l=await this.client.chat.appendStream(Object.assign({token:this.token,channel:this.streamArgs.channel,ts:this.streamTs,chunks:o},n));return this.buffer="",l}};z.ChatStreamer=pe});var Ve=f((Ls,Be)=>{function Ei(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}Be.exports=Ei});var Ge=f((Fs,Je)=>{"use strict";var T=r=>r!==null&&typeof r=="object"&&typeof r.pipe=="function";T.writable=r=>T(r)&&r.writable!==!1&&typeof r._write=="function"&&typeof r._writableState=="object";T.readable=r=>T(r)&&r.readable!==!1&&typeof r._read=="function"&&typeof r._readableState=="object";T.duplex=r=>T.writable(r)&&T.readable(r);T.transform=r=>T.duplex(r)&&typeof r._transform=="function";Je.exports=T});var He=f((Ds,ge)=>{"use strict";var Pi=Object.prototype.hasOwnProperty,M="~";function K(){}Object.create&&(K.prototype=Object.create(null),new K().__proto__||(M=!1));function ki(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ke(r,e,t,i,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new ki(t,i||r,n),l=M?M+e:e;return r._events[l]?r._events[l].fn?r._events[l]=[r._events[l],o]:r._events[l].push(o):(r._events[l]=o,r._eventsCount++),r}function te(r,e){--r._eventsCount===0?r._events=new K:delete r._events[e]}function k(){this._events=new K,this._eventsCount=0}k.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)Pi.call(t,i)&&e.push(M?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};k.prototype.listeners=function(e){var t=M?M+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,l=new Array(o);n<o;n++)l[n]=i[n].fn;return l};k.prototype.listenerCount=function(e){var t=M?M+e:e,i=this._events[t];return i?i.fn?1:i.length:0};k.prototype.emit=function(e,t,i,n,o,l){var u=M?M+e:e;if(!this._events[u])return!1;var a=this._events[u],h=arguments.length,d,c;if(a.fn){switch(a.once&&this.removeListener(e,a.fn,void 0,!0),h){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,t),!0;case 3:return a.fn.call(a.context,t,i),!0;case 4:return a.fn.call(a.context,t,i,n),!0;case 5:return a.fn.call(a.context,t,i,n,o),!0;case 6:return a.fn.call(a.context,t,i,n,o,l),!0}for(c=1,d=new Array(h-1);c<h;c++)d[c-1]=arguments[c];a.fn.apply(a.context,d)}else{var E=a.length,p;for(c=0;c<E;c++)switch(a[c].once&&this.removeListener(e,a[c].fn,void 0,!0),h){case 1:a[c].fn.call(a[c].context);break;case 2:a[c].fn.call(a[c].context,t);break;case 3:a[c].fn.call(a[c].context,t,i);break;case 4:a[c].fn.call(a[c].context,t,i,n);break;default:if(!d)for(p=1,d=new Array(h-1);p<h;p++)d[p-1]=arguments[p];a[c].fn.apply(a[c].context,d)}}return!0};k.prototype.on=function(e,t,i){return Ke(this,e,t,i,!1)};k.prototype.once=function(e,t,i){return Ke(this,e,t,i,!0)};k.prototype.removeListener=function(e,t,i,n){var o=M?M+e:e;if(!this._events[o])return this;if(!t)return te(this,o),this;var l=this._events[o];if(l.fn)l.fn===t&&(!n||l.once)&&(!i||l.context===i)&&te(this,o);else{for(var u=0,a=[],h=l.length;u<h;u++)(l[u].fn!==t||n&&!l[u].once||i&&l[u].context!==i)&&a.push(l[u]);a.length?this._events[o]=a.length===1?a[0]:a:te(this,o)}return this};k.prototype.removeAllListeners=function(e){var t;return e?(t=M?M+e:e,this._events[t]&&te(this,t)):(this._events=new K,this._eventsCount=0),this};k.prototype.off=k.prototype.removeListener;k.prototype.addListener=k.prototype.on;k.prefixed=M;k.EventEmitter=k;typeof ge<"u"&&(ge.exports=k)});var Qe=f((Ws,Ye)=>{"use strict";Ye.exports=(r,e)=>(e=e||(()=>{}),r.then(t=>new Promise(i=>{i(e())}).then(()=>t),t=>new Promise(i=>{i(e())}).then(()=>{throw t})))});var Ze=f(($s,ie)=>{"use strict";var Ci=Qe(),re=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Xe=(r,e,t)=>new Promise((i,n)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){i(r);return}let o=setTimeout(()=>{if(typeof t=="function"){try{i(t())}catch(a){n(a)}return}let l=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new re(l);typeof r.cancel=="function"&&r.cancel(),n(u)},e);Ci(r.then(i,n),()=>{clearTimeout(o)})});ie.exports=Xe;ie.exports.default=Xe;ie.exports.TimeoutError=re});var et=f(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});function Mi(r,e,t){let i=0,n=r.length;for(;n>0;){let o=n/2|0,l=i+o;t(r[l],e)<=0?(i=++l,n-=o+1):n=o}return i}_e.default=Mi});var tt=f(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});var ji=et(),ve=class{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);let i={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(i);return}let n=ji.default(this._queue,i,(o,l)=>l.priority-o.priority);this._queue.splice(n,0,i)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this._queue.length}};ye.default=ve});var it=f(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});var qi=He(),rt=Ze(),Ii=tt(),se=()=>{},Ai=new rt.TimeoutError,be=class extends qi{constructor(e){var t,i,n,o;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=se,this._resolveIdle=se,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Ii.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(i=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&i!==void 0?i:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(n=e.interval)===null||n===void 0?void 0:n.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=se,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=se,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let t=this._intervalEnd-e;if(t<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return t?(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((i,n)=>{let o=async()=>{this._pendingCount++,this._intervalCount++;try{let l=this._timeout===void 0&&t.timeout===void 0?e():rt.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&n(Ai)});i(await l)}catch(l){n(l)}this._next()};this._queue.enqueue(o,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async i=>this.add(i,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};we.default=be});var Et=f(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.getFileUploadJob=Oe;v.getMultipleFileUploadJobs=Ri;v.getFileData=st;v.getFileDataLength=nt;v.getFileDataAsStream=at;v.getAllFileUploadsToComplete=Ti;v.warnIfNotUsingFilesUploadV2=Ui;v.warnIfChannels=ot;v.errorIfChannelsCsv=lt;v.errorIfInvalidOrMissingFileData=ut;v.warnIfMissingOrInvalidFileNameAndDefault=ct;v.warnIfLegacyFileType=dt;v.buildMissingFileIdError=ht;v.buildFileSizeErrorMsg=ft;v.buildLegacyFileTypeWarning=pt;v.buildMissingFileNameWarning=mt;v.buildMissingExtensionWarning=gt;v.buildLegacyMethodWarning=_t;v.buildGeneralFilesUploadWarning=vt;v.buildFilesUploadMissingMessage=yt;v.buildChannelsWarning=bt;v.buildMultipleChannelsErrorMsg=wt;v.buildInvalidFilesUploadParamError=Ot;var Si=F("node:fs"),xi=F("node:stream"),w=ee();async function Oe(r,e){var t,i,n,o;dt(r,e),ot(r,e),lt(r);let l=ct(r,e),u=await st(r),a=nt(u),h={alt_text:r.alt_text,blocks:r.blocks,channel_id:(t=r.channels)!==null&&t!==void 0?t:r.channel_id,filename:(i=r.filename)!==null&&i!==void 0?i:l,highlight_type:r.highlight_type,initial_comment:r.initial_comment,snippet_type:r.snippet_type,title:(o=(n=r.title)!==null&&n!==void 0?n:r.filename)!==null&&o!==void 0?o:l,data:u,length:a};if("thread_ts"in r&&(h.thread_ts=r.thread_ts),"token"in r&&(h.token=r.token),"content"in r)return Object.assign({content:r.content},h);if("file"in r)return Object.assign({file:r.file},h);throw(0,w.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"),w.ErrorCode.FileUploadInvalidArgumentsError)}async function Ri(r,e){if("file_uploads"in r)return Promise.all(r.file_uploads.map(t=>{let{blocks:i,channel_id:n,channels:o,initial_comment:l,thread_ts:u}=t;if(i||n||o||l||u)throw(0,w.errorWithCode)(new Error(Ot()),w.ErrorCode.FileUploadInvalidArgumentsError);let a=Object.assign(Object.assign({},t),{blocks:r.blocks,channels:r.channels,channel_id:r.channel_id,initial_comment:r.initial_comment});if("thread_ts"in r&&(a.thread_ts=r.thread_ts),"token"in r&&(a.token=r.token),"content"in t)return Oe(Object.assign({content:t.content},a),e);if("file"in t)return Oe(Object.assign({file:t.file},a),e);throw(0,w.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"),w.ErrorCode.FileUploadInvalidArgumentsError)}));throw new Error(yt())}async function st(r){if(ut(r),"file"in r){let{file:e}=r;if(Buffer.isBuffer(e))return e;if(typeof e=="string")try{return(0,Si.readFileSync)(e)}catch{throw(0,w.errorWithCode)(new Error(`Unable to resolve file data for ${e}. Please supply a filepath string, or binary data Buffer or String directly.`),w.ErrorCode.FileUploadInvalidArgumentsError)}let t=await at(e);if(t)return t}if("content"in r)return Buffer.from(r.content);throw(0,w.errorWithCode)(new Error("There was an issue getting the file data for the file or content supplied"),w.ErrorCode.FileUploadReadFileDataError)}function nt(r){if(r)return Buffer.byteLength(r,"utf8");throw(0,w.errorWithCode)(new Error(ft()),w.ErrorCode.FileUploadReadFileDataError)}async function at(r){let e=[];return new Promise((t,i)=>{r.on("readable",()=>{let n=r.read();for(;n!==null;)e.push(n),n=r.read()}),r.on("end",()=>{if(e.length>0){let n=Buffer.concat(e);t(n)}else i(Error("No data in supplied file"))})})}function Ti(r){let e={};for(let t of r){let{blocks:i,channel_id:n,thread_ts:o,highlight_type:l,initial_comment:u,file_id:a,title:h}=t;if(a){let d=`:::${n}:::${o}:::${u}:::${JSON.stringify(i)}`;if(Object.prototype.hasOwnProperty.call(e,d))e[d].files.push({id:a,title:h,highlight_type:l});else{if(e[d]={files:[{id:a,title:h,highlight_type:l}],channel_id:n,blocks:i,initial_comment:u},o&&n){let c={channel_id:n,thread_ts:o};e[d]=Object.assign(Object.assign({},e[d]),c)}"token"in t&&(e[d].token=t.token)}}else throw new Error(ht())}return e}function Ui(r,e){let i=["files.upload"].includes(r);r==="files.upload"&&e.warn(_t(r)),i&&e.info(vt())}function ot(r,e){r.channels&&e.warn(bt())}function lt(r){if((r.channels?r.channels.split(","):[]).length>1)throw(0,w.errorWithCode)(new Error(wt()),w.ErrorCode.FileUploadInvalidArgumentsError)}function ut(r){let e="file"in r,t="content"in r;if(!(e||t)||e&&t)throw(0,w.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You cannot supply both"),w.ErrorCode.FileUploadInvalidArgumentsError);if("file"in r){let{file:i}=r;if(i&&!(typeof i=="string"||Buffer.isBuffer(i)||i instanceof xi.Readable))throw(0,w.errorWithCode)(new Error("file must be a valid string path, buffer or Readable"),w.ErrorCode.FileUploadInvalidArgumentsError)}if("content"in r&&r.content&&typeof r.content!="string")throw(0,w.errorWithCode)(new Error("content must be a string"),w.ErrorCode.FileUploadInvalidArgumentsError)}function ct(r,e){var t;let n=`file.${(t=r.filetype)!==null&&t!==void 0?t:"txt"}`,{filename:o}=r;return o?(o.split(".").length<2&&e.warn(gt(o)),o):(e.warn(mt()),n)}function dt(r,e){r.filetype&&e.warn(pt())}function ht(){return"Missing required file id for file upload completion"}function ft(){return"There was an issue calculating the size of your file"}function pt(){return`filetype is no longer a supported field in files.uploadV2.
|
|
5
|
+
Please remove this field. To indicate file type, please do so via the required filename property using the appropriate file extension, e.g. image.png, text.txt`}function mt(){return`filename is a required field for files.uploadV2.
|
|
6
|
+
For backwards compatibility and ease of migration, defaulting the filename. For best experience and consistent unfurl behavior, you should set the filename property with correct file extension, e.g. image.png, text.txt`}function gt(r){return`filename supplied '${r}' may be missing a proper extension. Missing extenions may result in unexpected unfurl behavior when shared`}function _t(r){return`${r} may cause some issues like timeouts for relatively large files.`}function vt(){return"Our latest recommendation is to use client.files.uploadV2() method, which is mostly compatible and much stabler, instead."}function yt(){return"Something went wrong with processing file_uploads"}function bt(){return"Although the 'channels' parameter is still supported for smoother migration from legacy files.upload, we recommend using the new channel_id parameter with a single str value instead (e.g. 'C12345')."}function wt(){return"Sharing files with multiple channels is no longer supported in v2. Share files in each channel separately instead."}function Ot(){return"You may supply file_uploads only for a single channel, message, or thread respectively. Therefore, please supply any channel_id, initial_comment or blocks, or thread_ts in the top-layer."}});var Pt=f(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.default=Li;function Li(r){return new Promise(e=>{setTimeout(e,r)})}});var Ct=f((Gs,Pe)=>{"use strict";var Fi=Object.prototype.hasOwnProperty,j="~";function H(){}Object.create&&(H.prototype=Object.create(null),new H().__proto__||(j=!1));function Di(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function kt(r,e,t,i,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Di(t,i||r,n),l=j?j+e:e;return r._events[l]?r._events[l].fn?r._events[l]=[r._events[l],o]:r._events[l].push(o):(r._events[l]=o,r._eventsCount++),r}function ne(r,e){--r._eventsCount===0?r._events=new H:delete r._events[e]}function C(){this._events=new H,this._eventsCount=0}C.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)Fi.call(t,i)&&e.push(j?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};C.prototype.listeners=function(e){var t=j?j+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,l=new Array(o);n<o;n++)l[n]=i[n].fn;return l};C.prototype.listenerCount=function(e){var t=j?j+e:e,i=this._events[t];return i?i.fn?1:i.length:0};C.prototype.emit=function(e,t,i,n,o,l){var u=j?j+e:e;if(!this._events[u])return!1;var a=this._events[u],h=arguments.length,d,c;if(a.fn){switch(a.once&&this.removeListener(e,a.fn,void 0,!0),h){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,t),!0;case 3:return a.fn.call(a.context,t,i),!0;case 4:return a.fn.call(a.context,t,i,n),!0;case 5:return a.fn.call(a.context,t,i,n,o),!0;case 6:return a.fn.call(a.context,t,i,n,o,l),!0}for(c=1,d=new Array(h-1);c<h;c++)d[c-1]=arguments[c];a.fn.apply(a.context,d)}else{var E=a.length,p;for(c=0;c<E;c++)switch(a[c].once&&this.removeListener(e,a[c].fn,void 0,!0),h){case 1:a[c].fn.call(a[c].context);break;case 2:a[c].fn.call(a[c].context,t);break;case 3:a[c].fn.call(a[c].context,t,i);break;case 4:a[c].fn.call(a[c].context,t,i,n);break;default:if(!d)for(p=1,d=new Array(h-1);p<h;p++)d[p-1]=arguments[p];a[c].fn.apply(a[c].context,d)}}return!0};C.prototype.on=function(e,t,i){return kt(this,e,t,i,!1)};C.prototype.once=function(e,t,i){return kt(this,e,t,i,!0)};C.prototype.removeListener=function(e,t,i,n){var o=j?j+e:e;if(!this._events[o])return this;if(!t)return ne(this,o),this;var l=this._events[o];if(l.fn)l.fn===t&&(!n||l.once)&&(!i||l.context===i)&&ne(this,o);else{for(var u=0,a=[],h=l.length;u<h;u++)(l[u].fn!==t||n&&!l[u].once||i&&l[u].context!==i)&&a.push(l[u]);a.length?this._events[o]=a.length===1?a[0]:a:ne(this,o)}return this};C.prototype.removeAllListeners=function(e){var t;return e?(t=j?j+e:e,this._events[t]&&ne(this,t)):(this._events=new H,this._eventsCount=0),this};C.prototype.off=C.prototype.removeListener;C.prototype.addListener=C.prototype.on;C.prefixed=j;C.EventEmitter=C;typeof Pe<"u"&&(Pe.exports=C)});var jt=f(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0})});var It=f(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0})});var St=f(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0})});var Rt=f(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0})});var Ut=f(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0})});var Ft=f(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0})});var Wt=f(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0})});var Nt=f($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0})});var Bt=f(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0})});var Jt=f(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0})});var Kt=f(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0})});var Yt=f(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0})});var Xt=f(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0})});var er=f(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0})});var rr=f(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0})});var sr=f(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0})});var ar=f(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0})});var lr=f(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0})});var cr=f(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0})});var hr=f(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0})});var pr=f(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0})});var gr=f(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0})});var vr=f(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0})});var br=f(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0})});var Or=f(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0})});var Pr=f(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0})});var Cr=f(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0})});var jr=f(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0})});var Ir=f(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0})});var Sr=f(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0})});var Rr=f(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0})});var Ur=f(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0})});var Fr=f(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0})});var Dr=f(g=>{"use strict";var Wi=g&&g.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),_=g&&g.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Wi(e,r,t)};Object.defineProperty(g,"__esModule",{value:!0});_(Nt(),g);_(Bt(),g);_(Jt(),g);_(Kt(),g);_(Yt(),g);_(Xt(),g);_(er(),g);_(rr(),g);_(sr(),g);_(ar(),g);_(lr(),g);_(cr(),g);_(hr(),g);_(pr(),g);_(gr(),g);_(vr(),g);_(br(),g);_(Or(),g);_(Pr(),g);_(Cr(),g);_(jr(),g);_(Ir(),g);_(Sr(),g);_(Rr(),g);_(Ur(),g);_(Fr(),g)});var $r=f(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0})});var Br=f(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.CustomFieldType=B.EntityType=void 0;var Nr;(function(r){r.Task="slack#/entities/task",r.File="slack#/entities/file",r.Item="slack#/entities/item",r.Incident="slack#/entities/incident",r.ContentItem="slack#/entities/content_item"})(Nr||(B.EntityType=Nr={}));var zr;(function(r){r.Integer="integer",r.String="string",r.Array="array",r.Date="slack#/types/date",r.Timestamp="slack#/types/timestamp",r.Image="slack#/types/image",r.ChannelId="slack#/types/channel_id",r.User="slack#/types/user",r.EntityRef="slack#/types/entity_ref",r.Boolean="boolean",r.Link="slack#/types/link",r.Email="slack#/types/email"})(zr||(B.CustomFieldType=zr={}))});var Jr=f(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0})});var Gr=f(O=>{"use strict";var $i=O&&O.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),A=O&&O.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&$i(e,r,t)};Object.defineProperty(O,"__esModule",{value:!0});A(jt(),O);A(It(),O);A(St(),O);A(Rt(),O);A(Ut(),O);A(Ft(),O);A(Wt(),O);A(Dr(),O);A($r(),O);A(Br(),O);A(Jr(),O)});var Ce=f(L=>{"use strict";var Ni=L&&L.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),zi=L&&L.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Ni(e,r,t)};Object.defineProperty(L,"__esModule",{value:!0});L.Methods=void 0;var Bi=Ct(),Kr=Me();function s(r,e){return r.apiCall.bind(r,e)}function m(r,e){return r.apiCall.bind(r,e)}function Vi(r){return r.filesUploadV2.bind(r)}var ke=class extends Bi.EventEmitter{constructor(){if(super(),this.admin={analytics:{getFile:s(this,"admin.analytics.getFile")},apps:{activities:{list:m(this,"admin.apps.activities.list")},approve:s(this,"admin.apps.approve"),approved:{list:s(this,"admin.apps.approved.list")},clearResolution:s(this,"admin.apps.clearResolution"),config:{lookup:s(this,"admin.apps.config.lookup"),set:s(this,"admin.apps.config.set")},requests:{cancel:s(this,"admin.apps.requests.cancel"),list:s(this,"admin.apps.requests.list")},restrict:s(this,"admin.apps.restrict"),restricted:{list:s(this,"admin.apps.restricted.list")},uninstall:s(this,"admin.apps.uninstall")},auth:{policy:{assignEntities:s(this,"admin.auth.policy.assignEntities"),getEntities:s(this,"admin.auth.policy.getEntities"),removeEntities:s(this,"admin.auth.policy.removeEntities")}},barriers:{create:s(this,"admin.barriers.create"),delete:s(this,"admin.barriers.delete"),list:m(this,"admin.barriers.list"),update:s(this,"admin.barriers.update")},conversations:{archive:s(this,"admin.conversations.archive"),bulkArchive:s(this,"admin.conversations.bulkArchive"),bulkDelete:s(this,"admin.conversations.bulkDelete"),bulkMove:s(this,"admin.conversations.bulkMove"),convertToPrivate:s(this,"admin.conversations.convertToPrivate"),convertToPublic:s(this,"admin.conversations.convertToPublic"),create:s(this,"admin.conversations.create"),delete:s(this,"admin.conversations.delete"),disconnectShared:s(this,"admin.conversations.disconnectShared"),ekm:{listOriginalConnectedChannelInfo:m(this,"admin.conversations.ekm.listOriginalConnectedChannelInfo")},getConversationPrefs:s(this,"admin.conversations.getConversationPrefs"),getCustomRetention:s(this,"admin.conversations.getCustomRetention"),getTeams:s(this,"admin.conversations.getTeams"),invite:s(this,"admin.conversations.invite"),lookup:s(this,"admin.conversations.lookup"),removeCustomRetention:s(this,"admin.conversations.removeCustomRetention"),rename:s(this,"admin.conversations.rename"),restrictAccess:{addGroup:s(this,"admin.conversations.restrictAccess.addGroup"),listGroups:s(this,"admin.conversations.restrictAccess.listGroups"),removeGroup:s(this,"admin.conversations.restrictAccess.removeGroup")},search:m(this,"admin.conversations.search"),setConversationPrefs:s(this,"admin.conversations.setConversationPrefs"),setCustomRetention:s(this,"admin.conversations.setCustomRetention"),setTeams:s(this,"admin.conversations.setTeams"),unarchive:s(this,"admin.conversations.unarchive")},emoji:{add:s(this,"admin.emoji.add"),addAlias:s(this,"admin.emoji.addAlias"),list:m(this,"admin.emoji.list"),remove:s(this,"admin.emoji.remove"),rename:s(this,"admin.emoji.rename")},functions:{list:s(this,"admin.functions.list"),permissions:{lookup:s(this,"admin.functions.permissions.lookup"),set:s(this,"admin.functions.permissions.set")}},inviteRequests:{approve:s(this,"admin.inviteRequests.approve"),approved:{list:s(this,"admin.inviteRequests.approved.list")},denied:{list:s(this,"admin.inviteRequests.denied.list")},deny:s(this,"admin.inviteRequests.deny"),list:s(this,"admin.inviteRequests.list")},roles:{addAssignments:s(this,"admin.roles.addAssignments"),listAssignments:m(this,"admin.roles.listAssignments"),removeAssignments:s(this,"admin.roles.removeAssignments")},teams:{admins:{list:s(this,"admin.teams.admins.list")},create:s(this,"admin.teams.create"),list:m(this,"admin.teams.list"),owners:{list:s(this,"admin.teams.owners.list")},settings:{info:s(this,"admin.teams.settings.info"),setDefaultChannels:s(this,"admin.teams.settings.setDefaultChannels"),setDescription:s(this,"admin.teams.settings.setDescription"),setDiscoverability:s(this,"admin.teams.settings.setDiscoverability"),setIcon:s(this,"admin.teams.settings.setIcon"),setName:s(this,"admin.teams.settings.setName")}},usergroups:{addChannels:s(this,"admin.usergroups.addChannels"),addTeams:s(this,"admin.usergroups.addTeams"),listChannels:s(this,"admin.usergroups.listChannels"),removeChannels:s(this,"admin.usergroups.removeChannels")},users:{assign:s(this,"admin.users.assign"),invite:s(this,"admin.users.invite"),list:m(this,"admin.users.list"),remove:s(this,"admin.users.remove"),session:{clearSettings:s(this,"admin.users.session.clearSettings"),getSettings:s(this,"admin.users.session.getSettings"),invalidate:s(this,"admin.users.session.invalidate"),list:m(this,"admin.users.session.list"),reset:s(this,"admin.users.session.reset"),resetBulk:s(this,"admin.users.session.resetBulk"),setSettings:s(this,"admin.users.session.setSettings")},setAdmin:s(this,"admin.users.setAdmin"),setExpiration:s(this,"admin.users.setExpiration"),setOwner:s(this,"admin.users.setOwner"),setRegular:s(this,"admin.users.setRegular"),unsupportedVersions:{export:s(this,"admin.users.unsupportedVersions.export")}},workflows:{collaborators:{add:s(this,"admin.workflows.collaborators.add"),remove:s(this,"admin.workflows.collaborators.remove")},permissions:{lookup:s(this,"admin.workflows.permissions.lookup")},search:m(this,"admin.workflows.search"),unpublish:s(this,"admin.workflows.unpublish")}},this.api={test:m(this,"api.test")},this.assistant={threads:{setStatus:s(this,"assistant.threads.setStatus"),setSuggestedPrompts:s(this,"assistant.threads.setSuggestedPrompts"),setTitle:s(this,"assistant.threads.setTitle")}},this.apps={connections:{open:m(this,"apps.connections.open")},event:{authorizations:{list:s(this,"apps.event.authorizations.list")}},manifest:{create:s(this,"apps.manifest.create"),delete:s(this,"apps.manifest.delete"),export:s(this,"apps.manifest.export"),update:s(this,"apps.manifest.update"),validate:s(this,"apps.manifest.validate")},uninstall:s(this,"apps.uninstall"),user:{connection:{update:s(this,"apps.user.connection.update")}}},this.auth={revoke:m(this,"auth.revoke"),teams:{list:m(this,"auth.teams.list")},test:m(this,"auth.test")},this.bookmarks={add:s(this,"bookmarks.add"),edit:s(this,"bookmarks.edit"),list:s(this,"bookmarks.list"),remove:s(this,"bookmarks.remove")},this.bots={info:m(this,"bots.info")},this.calls={add:s(this,"calls.add"),end:s(this,"calls.end"),info:s(this,"calls.info"),update:s(this,"calls.update"),participants:{add:s(this,"calls.participants.add"),remove:s(this,"calls.participants.remove")}},this.canvases={access:{delete:s(this,"canvases.access.delete"),set:s(this,"canvases.access.set")},create:m(this,"canvases.create"),delete:s(this,"canvases.delete"),edit:s(this,"canvases.edit"),sections:{lookup:s(this,"canvases.sections.lookup")}},this.chat={appendStream:s(this,"chat.appendStream"),delete:s(this,"chat.delete"),deleteScheduledMessage:s(this,"chat.deleteScheduledMessage"),getPermalink:s(this,"chat.getPermalink"),meMessage:s(this,"chat.meMessage"),postEphemeral:s(this,"chat.postEphemeral"),postMessage:s(this,"chat.postMessage"),scheduleMessage:s(this,"chat.scheduleMessage"),scheduledMessages:{list:m(this,"chat.scheduledMessages.list")},startStream:s(this,"chat.startStream"),stopStream:s(this,"chat.stopStream"),unfurl:s(this,"chat.unfurl"),update:s(this,"chat.update")},this.conversations={acceptSharedInvite:s(this,"conversations.acceptSharedInvite"),approveSharedInvite:s(this,"conversations.approveSharedInvite"),archive:s(this,"conversations.archive"),canvases:{create:s(this,"conversations.canvases.create")},close:s(this,"conversations.close"),create:s(this,"conversations.create"),declineSharedInvite:s(this,"conversations.declineSharedInvite"),externalInvitePermissions:{set:s(this,"conversations.externalInvitePermissions.set")},history:s(this,"conversations.history"),info:s(this,"conversations.info"),invite:s(this,"conversations.invite"),inviteShared:s(this,"conversations.inviteShared"),join:s(this,"conversations.join"),kick:s(this,"conversations.kick"),leave:s(this,"conversations.leave"),list:m(this,"conversations.list"),listConnectInvites:m(this,"conversations.listConnectInvites"),mark:s(this,"conversations.mark"),members:s(this,"conversations.members"),open:s(this,"conversations.open"),rename:s(this,"conversations.rename"),replies:s(this,"conversations.replies"),requestSharedInvite:{approve:s(this,"conversations.requestSharedInvite.approve"),deny:s(this,"conversations.requestSharedInvite.deny"),list:m(this,"conversations.requestSharedInvite.list")},setPurpose:s(this,"conversations.setPurpose"),setTopic:s(this,"conversations.setTopic"),unarchive:s(this,"conversations.unarchive")},this.dialog={open:s(this,"dialog.open")},this.dnd={endDnd:m(this,"dnd.endDnd"),endSnooze:m(this,"dnd.endSnooze"),info:m(this,"dnd.info"),setSnooze:s(this,"dnd.setSnooze"),teamInfo:s(this,"dnd.teamInfo")},this.emoji={list:m(this,"emoji.list")},this.entity={presentDetails:s(this,"entity.presentDetails")},this.files={completeUploadExternal:s(this,"files.completeUploadExternal"),delete:s(this,"files.delete"),getUploadURLExternal:s(this,"files.getUploadURLExternal"),info:s(this,"files.info"),list:s(this,"files.list"),revokePublicURL:s(this,"files.revokePublicURL"),sharedPublicURL:s(this,"files.sharedPublicURL"),upload:s(this,"files.upload"),uploadV2:Vi(this),comments:{delete:s(this,"files.comments.delete")},remote:{add:s(this,"files.remote.add"),info:s(this,"files.remote.info"),list:s(this,"files.remote.list"),remove:s(this,"files.remote.remove"),share:s(this,"files.remote.share"),update:s(this,"files.remote.update")}},this.functions={completeError:s(this,"functions.completeError"),completeSuccess:s(this,"functions.completeSuccess")},this.migration={exchange:s(this,"migration.exchange")},this.oauth={access:s(this,"oauth.access"),v2:{access:s(this,"oauth.v2.access"),exchange:s(this,"oauth.v2.exchange")}},this.openid={connect:{token:s(this,"openid.connect.token"),userInfo:m(this,"openid.connect.userInfo")}},this.pins={add:s(this,"pins.add"),list:s(this,"pins.list"),remove:s(this,"pins.remove")},this.reactions={add:s(this,"reactions.add"),get:s(this,"reactions.get"),list:m(this,"reactions.list"),remove:s(this,"reactions.remove")},this.reminders={add:s(this,"reminders.add"),complete:s(this,"reminders.complete"),delete:s(this,"reminders.delete"),info:s(this,"reminders.info"),list:m(this,"reminders.list")},this.rtm={connect:m(this,"rtm.connect"),start:m(this,"rtm.start")},this.search={all:s(this,"search.all"),files:s(this,"search.files"),messages:s(this,"search.messages")},this.slackLists={access:{delete:s(this,"slackLists.access.delete"),set:s(this,"slackLists.access.set")},create:s(this,"slackLists.create"),download:{get:s(this,"slackLists.download.get"),start:s(this,"slackLists.download.start")},items:{create:s(this,"slackLists.items.create"),delete:s(this,"slackLists.items.delete"),deleteMultiple:s(this,"slackLists.items.deleteMultiple"),info:s(this,"slackLists.items.info"),list:s(this,"slackLists.items.list"),update:s(this,"slackLists.items.update")},update:s(this,"slackLists.update")},this.team={accessLogs:m(this,"team.accessLogs"),billableInfo:m(this,"team.billableInfo"),billing:{info:s(this,"team.billing.info")},externalTeams:{disconnect:s(this,"team.externalTeams.disconnect"),list:s(this,"team.externalTeams.list")},info:m(this,"team.info"),integrationLogs:m(this,"team.integrationLogs"),preferences:{list:m(this,"team.preferences.list")},profile:{get:m(this,"team.profile.get")}},this.tooling={tokens:{rotate:s(this,"tooling.tokens.rotate")}},this.usergroups={create:s(this,"usergroups.create"),disable:s(this,"usergroups.disable"),enable:s(this,"usergroups.enable"),list:m(this,"usergroups.list"),update:s(this,"usergroups.update"),users:{list:s(this,"usergroups.users.list"),update:s(this,"usergroups.users.update")}},this.users={conversations:s(this,"users.conversations"),deletePhoto:s(this,"users.deletePhoto"),discoverableContacts:{lookup:s(this,"users.discoverableContacts.lookup")},getPresence:s(this,"users.getPresence"),identity:s(this,"users.identity"),info:s(this,"users.info"),list:s(this,"users.list"),lookupByEmail:s(this,"users.lookupByEmail"),setPhoto:s(this,"users.setPhoto"),setPresence:s(this,"users.setPresence"),profile:{get:s(this,"users.profile.get"),set:s(this,"users.profile.set")}},this.views={open:s(this,"views.open"),publish:s(this,"views.publish"),push:s(this,"views.push"),update:s(this,"views.update")},this.stars={add:s(this,"stars.add"),list:s(this,"stars.list"),remove:s(this,"stars.remove")},this.workflows={featured:{add:s(this,"workflows.featured.add"),list:s(this,"workflows.featured.list"),remove:s(this,"workflows.featured.remove"),set:s(this,"workflows.featured.set")},stepCompleted:s(this,"workflows.stepCompleted"),stepFailed:s(this,"workflows.stepFailed"),updateStep:s(this,"workflows.updateStep")},new.target!==Kr.WebClient&&!(new.target.prototype instanceof Kr.WebClient))throw new Error("Attempt to inherit from WebClient methods without inheriting from WebClient")}};L.Methods=ke;zi(Gr(),L)});var Me=f(b=>{"use strict";var Ji=b&&b.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),Gi=b&&b.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Ki=b&&b.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&Ji(t,e,i[n]);return Gi(t,e),t}})(),Q=b&&b.__await||function(r){return this instanceof Q?(this.v=r,this):new Q(r)},Hi=b&&b.__asyncGenerator||function(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(r,e||[]),n,o=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",l),n[Symbol.asyncIterator]=function(){return this},n;function l(p){return function(I){return Promise.resolve(I).then(p,c)}}function u(p,I){i[p]&&(n[p]=function(S){return new Promise(function(x,D){o.push([p,S,x,D])>1||a(p,S)})},I&&(n[p]=I(n[p])))}function a(p,I){try{h(i[p](I))}catch(S){E(o[0][3],S)}}function h(p){p.value instanceof Q?Promise.resolve(p.value.v).then(d,c):E(o[0][2],p)}function d(p){a("next",p)}function c(p){a("throw",p)}function E(p,I){p(I),o.shift(),o.length&&a(o[0][0],o[0][1])}},Yi=b&&b.__asyncValues||function(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof __values=="function"?__values(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(o){t[o]=r[o]&&function(l){return new Promise(function(u,a){l=r[o](l),n(u,a,l.done,l.value)})}}function n(o,l,u,a){Promise.resolve(a).then(function(h){o({value:h,done:u})},l)}},Qi=b&&b.__rest||function(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(r);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(r,i[n])&&(t[i[n]]=r[i[n]]);return t},W=b&&b.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(b,"__esModule",{value:!0});b.WebClient=b.WebClientEvent=void 0;b.buildThreadTsWarningMessage=Zr;var Hr=F("node:path"),Xi=F("node:querystring"),Zi=F("node:util"),es=W(F("node:zlib")),ts=W(ri()),rs=W(ti()),is=W(Ve()),qe=W(Ge()),ss=W(it()),je=Ki(ii()),ns=me(),Y=ee(),ae=Et(),as=W(Pt()),os=ue(),Yr=de(),ls=Ce(),us=he(),cs=["delete","common","get","put","head","post","link","patch","purge","unlink","options"],ds="Untitled",hs=200,fs=()=>{},Ie;(function(r){r.RATE_LIMITED="rate_limited"})(Ie||(b.WebClientEvent=Ie={}));var X=class r extends ls.Methods{constructor(e,{slackApiUrl:t="https://slack.com/api/",logger:i=void 0,logLevel:n=void 0,maxRequestConcurrency:o=100,retryConfig:l=us.tenRetriesInAboutThirtyMinutes,agent:u=void 0,tls:a=void 0,timeout:h=0,rejectRateLimitedCalls:d=!1,headers:c={},teamId:E=void 0,allowAbsoluteUrls:p=!0,attachOriginalToWebAPIRequestError:I=!0,requestInterceptor:S=void 0,adapter:x=void 0}={}){super(),this.token=e,this.slackApiUrl=t,this.slackApiUrl.endsWith("/")||(this.slackApiUrl+="/"),this.retryConfig=l,this.requestQueue=new ss.default({concurrency:o}),this.tlsConfig=a!==void 0?a:{},this.rejectRateLimitedCalls=d,this.teamId=E,this.allowAbsoluteUrls=p,this.attachOriginalToWebAPIRequestError=I,typeof i<"u"?(this.logger=i,typeof n<"u"&&this.logger.debug("The logLevel given to WebClient was ignored as you also gave logger")):this.logger=(0,Yr.getLogger)(r.loggerName,n??Yr.LogLevel.INFO,i),this.token&&!c.Authorization&&(c.Authorization=`Bearer ${this.token}`),this.axios=ts.default.create({adapter:x?D=>x(Object.assign(Object.assign({},D),{adapter:void 0})):void 0,timeout:h,baseURL:this.slackApiUrl,headers:(0,is.default)()?c:Object.assign({"User-Agent":(0,os.getUserAgent)()},c),httpAgent:u,httpsAgent:u,validateStatus:()=>!0,maxRedirects:0,proxy:!1}),this.axios.defaults.headers.post["Content-Type"]=void 0,S&&this.axios.interceptors.request.use(S,null),this.axios.interceptors.request.use(this.serializeApiCallData.bind(this),null),this.logger.debug("initialized")}async apiCall(e,t={}){if(this.logger.debug(`apiCall('${e}') start`),ms(e,this.logger),gs(e,this.logger,t),_s(e,this.logger,t),typeof t=="string"||typeof t=="number"||typeof t=="boolean")throw new TypeError(`Expected an options argument but instead received a ${typeof t}`);if((0,ae.warnIfNotUsingFilesUploadV2)(e,this.logger),e==="files.uploadV2")return this.filesUploadV2(t);let i={};t.token&&(i.Authorization=`Bearer ${t.token}`);let n=this.deriveRequestUrl(e),o=await this.makeRequest(n,Object.assign({team_id:this.teamId},t),i),l=await this.buildResult(o);if(this.logger.debug(`http request result: ${JSON.stringify(l)}`),l.response_metadata!==void 0&&l.response_metadata.warnings!==void 0&&l.response_metadata.warnings.forEach(this.logger.warn.bind(this.logger)),l.response_metadata!==void 0&&l.response_metadata.messages!==void 0)for(let u of l.response_metadata.messages){let a=/\[ERROR\](.*)/,h=/\[WARN\](.*)/;if(a.test(u)){let d=u.match(a);d!=null&&this.logger.error(d[1].trim())}else if(h.test(u)){let d=u.match(h);d!=null&&this.logger.warn(d[1].trim())}}if(!l.ok&&o.headers["content-type"]!=="application/gzip"||"ok"in l&&l.ok===!1)throw(0,Y.platformErrorFromResult)(l);return this.logger.debug(`apiCall('${e}') end`),l}paginate(e,t,i,n){let o=(()=>{if(t!==void 0&&typeof t.limit=="number"){let{limit:h}=t;return t.limit=void 0,h}return hs})();function l(){return Hi(this,arguments,function*(){let d,c={limit:o};for(t!==void 0&&t.cursor!==void 0&&(c.cursor=t.cursor);d===void 0||c!==void 0;)d=yield Q(this.apiCall(e,Object.assign(t!==void 0?t:{},c))),yield yield Q(d),c=ps(d,o)})}if(i===void 0)return l.call(this);let u=n!==void 0?n:fs,a=0;return(async()=>{var h,d,c,E;let p=l.call(this),S=(await p.next(void 0)).value,x=u(void 0,S,a);if(a+=1,i(S))return x;try{for(var D=!0,oe=Yi(p),le;le=await oe.next(),h=le.done,!h;D=!0){E=le.value,D=!1;let Z=E;if(x=u(x,Z,a),i(Z))return x;a+=1}}catch(Z){d={error:Z}}finally{try{!D&&!h&&(c=oe.return)&&await c.call(oe)}finally{if(d)throw d.error}}return x})()}chatStream(e){let{buffer_size:t}=e,i=Qi(e,["buffer_size"]),n={buffer_size:t};return new ns.ChatStreamer(this,this.logger,i,n)}async filesUploadV2(e){this.logger.debug("files.uploadV2() start");let t=await this.getAllFileUploads(e);return(await this.fetchAllUploadURLExternal(t)).forEach((o,l)=>{t[l].upload_url=o.upload_url,t[l].file_id=o.file_id}),await this.postFileUploadsToExternalURL(t,e),{ok:!0,files:await this.completeFileUploads(t)}}async fetchAllUploadURLExternal(e){return Promise.all(e.map(t=>{let i={filename:t.filename,length:t.length,alt_text:t.alt_text,snippet_type:t.snippet_type};return"token"in t&&(i.token=t.token),this.files.getUploadURLExternal(i)}))}async completeFileUploads(e){let t=Object.values((0,ae.getAllFileUploadsToComplete)(e));return Promise.all(t.map(i=>this.files.completeUploadExternal(i)))}async postFileUploadsToExternalURL(e,t){return Promise.all(e.map(async i=>{let{upload_url:n,file_id:o,filename:l,data:u}=i,a=u;if(n){let h={};t.token&&(h.Authorization=`Bearer ${t.token}`);let d=await this.makeRequest(n,{body:a},h);if(d.status!==200)return Promise.reject(Error(`Failed to upload file (id:${o}, filename: ${l})`));let c={ok:!0,body:d.data};return Promise.resolve(c)}return Promise.reject(Error(`No upload url found for file (id: ${o}, filename: ${l}`))}))}async getAllFileUploads(e){let t=[];return("file"in e||"content"in e)&&t.push(await(0,ae.getFileUploadJob)(e,this.logger)),"file_uploads"in e&&(t=t.concat(await(0,ae.getMultipleFileUploadJobs)(e,this.logger))),t}async makeRequest(e,t,i={}){let n=()=>this.requestQueue.add(async()=>{try{let o=Object.assign({headers:i},this.tlsConfig);e.endsWith("admin.analytics.getFile")&&(o.responseType="arraybuffer"),e.endsWith("apps.event.authorizations.list")&&(t.token=void 0),this.logger.debug(`http request url: ${e}`),this.logger.debug(`http request body: ${JSON.stringify(Xr(t))}`);let l=Object.keys(this.axios.defaults.headers).reduce((a,h)=>(cs.includes(h)||(a[h]=this.axios.defaults.headers[h]),a),{});l=Object.assign(Object.assign(Object.assign({},this.axios.defaults.headers.common),l),i),this.logger.debug(`http request headers: ${JSON.stringify(Xr(l))}`);let u=await this.axios.post(e,t,o);if(this.logger.debug("http response received"),u.status===429){let a=Qr(u);throw a!==void 0?(this.emit(Ie.RATE_LIMITED,a,{url:e,body:t}),this.rejectRateLimitedCalls?new je.AbortError((0,Y.rateLimitedErrorWithDelay)(a)):(this.logger.info(`API Call failed due to rate limiting. Will retry in ${a} seconds.`),this.requestQueue.pause(),await(0,as.default)(a*1e3),this.requestQueue.start(),new Error(`A rate limit was exceeded (url: ${e}, retry-after: ${a})`))):new je.AbortError(new Error(`Retry header did not contain a valid timeout (url: ${e}, retry-after header: ${u.headers["retry-after"]})`))}if(u.status!==200)throw(0,Y.httpErrorFromResponse)(u);return u}catch(o){let l=o;throw this.logger.warn("http request failed",l.message),l.request?(0,Y.requestErrorWithOriginal)(l,this.attachOriginalToWebAPIRequestError):o}});return(0,je.default)(n,this.retryConfig)}deriveRequestUrl(e){return(e.startsWith("https://")||e.startsWith("http://"))&&this.allowAbsoluteUrls?e:`${this.axios.getUri()+e}`}serializeApiCallData(e){let{data:t,headers:i}=e,n=!1,o=Object.entries(t).map(([u,a])=>{if(a==null)return[];let h=a;return Buffer.isBuffer(a)||(0,qe.default)(a)?n=!0:typeof a!="string"&&typeof a!="number"&&typeof a!="boolean"&&(h=JSON.stringify(a)),[u,h]});if(n){this.logger.debug("Request arguments contain binary data");let u=o.reduce((a,[h,d])=>{if(Buffer.isBuffer(d)||(0,qe.default)(d)){let c={};c.filename=(()=>{let E=d;return typeof E.name=="string"?(0,Hr.basename)(E.name):typeof E.path=="string"?(0,Hr.basename)(E.path):ds})(),a.append(h,d,c)}else h!==void 0&&d!==void 0&&a.append(h,d);return a},new rs.default);if(i)for(let[a,h]of Object.entries(u.getHeaders()))i[a]=h;return e.data=u,e.headers=i,e}i&&(i["Content-Type"]="application/x-www-form-urlencoded");let l={};return e.data=(0,Xi.stringify)(o.reduce((u,[a,h])=>(a!==void 0&&h!==void 0&&(u[a]=h),u),l)),e.headers=i,e}async buildResult(e){let{data:t}=e,i=e.headers["content-type"]==="application/gzip";if(i)try{let o=await new Promise((u,a)=>{es.default.unzip(t,(h,d)=>h?a(h):u(d.toString().split(`
|
|
7
|
+
`)))}).then(u=>u).catch(u=>{throw u}),l=[];if(Array.isArray(o))for(let u of o)u&&u.length>0&&l.push(JSON.parse(u));t={file_data:l}}catch(o){t={ok:!1,error:o}}else!i&&e.request.path==="/api/admin.analytics.getFile"&&(t=JSON.parse(new Zi.TextDecoder().decode(t)));if(typeof t=="string")try{t=JSON.parse(t)}catch{t={ok:!1,error:t}}t.response_metadata===void 0&&(t.response_metadata={}),e.headers["x-oauth-scopes"]!==void 0&&(t.response_metadata.scopes=e.headers["x-oauth-scopes"].trim().split(/\s*,\s*/)),e.headers["x-accepted-oauth-scopes"]!==void 0&&(t.response_metadata.acceptedScopes=e.headers["x-accepted-oauth-scopes"].trim().split(/\s*,\s*/));let n=Qr(e);return n!==void 0&&(t.response_metadata.retryAfter=n),t}};b.WebClient=X;X.loggerName="WebClient";b.default=X;function ps(r,e){if(r!==void 0&&r.response_metadata!==void 0&&r.response_metadata.next_cursor!==void 0&&r.response_metadata.next_cursor!=="")return{limit:e,cursor:r.response_metadata.next_cursor}}function Qr(r){if(r.headers["retry-after"]!==void 0){let e=Number.parseInt(r.headers["retry-after"],10);if(!Number.isNaN(e))return e}}function ms(r,e){["workflows.stepCompleted","workflows.stepFailed","workflows.updateStep"].some(n=>new RegExp(`^${n}`).test(r))&&e.warn(`${r} is deprecated. Please check on https://docs.slack.dev/reference/methods for an alternative.`)}function gs(r,e,t){let n=["chat.postEphemeral","chat.postMessage","chat.scheduleMessage"].includes(r),o=d=>Array.isArray(d.attachments)&&d.attachments.length,l=d=>Array.isArray(d.attachments)&&d.attachments.some(c=>!c.fallback||c.fallback.trim()===""),u=d=>(d.text===void 0||d.text===null||d.text==="")&&(d.markdown_text===void 0||d.markdown===null||d.markdown_text===""),a=()=>`The top-level \`text\` argument is missing in the request payload for a ${r} call - It's a best practice to always provide a \`text\` argument when posting a message. The \`text\` is used in places where the content cannot be rendered such as: system push notifications, assistive technology such as screen readers, etc.`,h=()=>`Additionally, the attachment-level \`fallback\` argument is missing in the request payload for a ${r} call - To avoid this warning, it is recommended to always provide a top-level \`text\` argument when posting a message. Alternatively, you can provide an attachment-level \`fallback\` argument, though this is now considered a legacy field (see https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments for more details).`;n&&typeof t=="object"&&(o(t)?l(t)&&u(t)&&(e.warn(a()),e.warn(h())):u(t)&&e.warn(a()))}function _s(r,e,t){["chat.postEphemeral","chat.postMessage","chat.scheduleMessage","files.upload"].includes(r)&&t?.thread_ts!==void 0&&typeof t?.thread_ts!="string"&&e.warn(Zr(r))}function Zr(r){return`The given thread_ts value in the request payload for a ${r} call is a float value. We highly recommend using a string value instead.`}function Xr(r){let e=Object.entries(r).map(([i,n])=>{if(n==null)return[];let o=n;return(i.match(/.*token.*/)!==null||i.match(/[Aa]uthorization/))&&(o="[[REDACTED]]"),Buffer.isBuffer(n)||(0,qe.default)(n)?o="[[BINARY VALUE OMITTED]]":typeof n!="string"&&typeof n!="number"&&typeof n!="boolean"&&(o=JSON.stringify(n)),[i,o]}),t={};return e.reduce((i,[n,o])=>(n!==void 0&&o!==void 0&&(i[n]=o),i),t)}});var ks=f(y=>{"use strict";var vs=y&&y.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),Ae=y&&y.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&vs(e,r,t)},ys=y&&y.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(y,"__esModule",{value:!0});y.WebClientEvent=y.WebClient=y.ChatStreamer=y.retryPolicies=y.LogLevel=y.addAppMetadata=y.ErrorCode=void 0;var bs=ee();Object.defineProperty(y,"ErrorCode",{enumerable:!0,get:function(){return bs.ErrorCode}});var ws=ue();Object.defineProperty(y,"addAppMetadata",{enumerable:!0,get:function(){return ws.addAppMetadata}});var Os=de();Object.defineProperty(y,"LogLevel",{enumerable:!0,get:function(){return Os.LogLevel}});var Es=he();Object.defineProperty(y,"retryPolicies",{enumerable:!0,get:function(){return ys(Es).default}});Ae($e(),y);Ae(ze(),y);var Ps=me();Object.defineProperty(y,"ChatStreamer",{enumerable:!0,get:function(){return Ps.ChatStreamer}});var ei=Me();Object.defineProperty(y,"WebClient",{enumerable:!0,get:function(){return ei.WebClient}});Object.defineProperty(y,"WebClientEvent",{enumerable:!0,get:function(){return ei.WebClientEvent}});Ae(Ce(),y)});var si=Se("rate-limiter"),xe=class{globalCapacity;globalRefillPerSec;perChannelCapacity;perChannelRefillPerSec;cleanupIntervalMs;buckets=new Map;cleanupTimer=null;constructor(e={}){this.globalCapacity=e.globalCapacity??20,this.globalRefillPerSec=e.globalRefillPerSec??1,this.perChannelCapacity=e.perChannelCapacity??1,this.perChannelRefillPerSec=e.perChannelRefillPerSec??1,this.cleanupIntervalMs=e.cleanupIntervalMs??6e4,this.cleanupTimer=setInterval(()=>this._cleanup(),this.cleanupIntervalMs),typeof this.cleanupTimer.unref=="function"&&this.cleanupTimer.unref()}tryAcquire(e,t){let{globalKey:i,channelKey:n}=this._keys(e,t),o=this._tryConsume(i);if(!o.ok)return o;if(n!==i){let l=this._tryConsume(n);if(!l.ok)return this._refund(i),l}return{ok:!0}}async acquire(e,t){for(;;){let i=this.tryAcquire(e,t);if(i.ok)return;await this._sleep(Math.min(i.retryAfterMs??200,200))}}reportThrottled(e,t,i){let n=i&&i>0?i*1e3+1e3:1e4,o=Date.now()+n,{globalKey:l,channelKey:u}=this._keys(e,t);this._getOrCreate(l).backoffUntil=o,u!==l&&(this._getOrCreate(u).backoffUntil=o),si.warn(`${e}${t?`:${t}`:""} received 429, backing off ${n}ms`)}dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.buckets.clear()}_bucketCount(){return this.buckets.size}_advanceTime(e){let t=Date.now();for(let i of this.buckets.values())i.lastRefill=t-e}_keys(e,t){let i=`__global__:${e}`,n=t?`${e}:${t}`:i;return{globalKey:i,channelKey:n}}_tryConsume(e){let t=this._getOrCreate(e),i=Date.now();if(t.backoffUntil>i)return{ok:!1,retryAfterMs:t.backoffUntil-i};if(this._refill(t,i,e),t.tokens>=1)return t.tokens-=1,{ok:!0};let n=this._refillPerSecForKey(e),o=n>0?Math.ceil((1-t.tokens)/n*1e3):1e3;return{ok:!1,retryAfterMs:Math.min(o,5e3)}}_refund(e){let t=this.buckets.get(e);if(!t)return;let i=this._capacityForKey(e);t.tokens=Math.min(t.tokens+1,i)}_getOrCreate(e){let t=this.buckets.get(e);return t||(t={tokens:this._capacityForKey(e),lastRefill:Date.now(),backoffUntil:0},this.buckets.set(e,t)),t}_refill(e,t,i){let n=(t-e.lastRefill)/1e3;if(n<=0)return;let o=this._refillPerSecForKey(i),l=this._capacityForKey(i);e.tokens=Math.min(e.tokens+n*o,l),e.lastRefill=t}_capacityForKey(e){return e.startsWith("__global__")?this.globalCapacity:this.perChannelCapacity}_refillPerSecForKey(e){return e.startsWith("__global__")?this.globalRefillPerSec:this.perChannelRefillPerSec}_cleanup(){let e=Date.now()-3e5;for(let[t,i]of this.buckets)i.lastRefill<e&&i.backoffUntil<e&&this.buckets.delete(t)}_sleep(e){return new Promise(t=>setTimeout(t,e))}};export{xe as a,ce as b,Ct as c,Gr as d,ks as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
2
|
const require = __cortexCreateRequire(import.meta.url);
|
|
3
3
|
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a,
|
|
4
|
+
import{a,c as u}from"./chunk-UT6DGZDO.js";import*as n from"fs";import*as s from"path";function f(t){return!!(s.isAbsolute(t)||/^[A-Za-z]:[/\\]/.test(t))}function w(t,r){return t&&(t.startsWith(r)?t.slice(r.length):t)}var m=10*6e4;async function c(t,r,e){if(!f(e))throw new Error("file_path must be absolute when `device` is set");let{body:o}=await a("POST",`${t.webhookBaseUrl}/webhook/remote-fetch`,{device:r,filePath:e},u(t),m);if(!o.success)throw new Error(o.error||`Failed to fetch ${e} from ${r}`);return o.data}async function l(t,r,e,o){let i=await c(t,r,e);try{return await o(i)}finally{await n.promises.rm(s.dirname(i.localPath),{recursive:!0,force:!0}).catch(()=>{})}}export{f as a,w as b,l as c};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{a as p,c as S}from"./chunk-WHC7AYZD.js";var T=S((ur,qe)=>{"use strict";var Fe=["nodebuffer","arraybuffer","fragments"],We=typeof Blob<"u";We&&Fe.push("blob");qe.exports={BINARY_TYPES:Fe,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:We,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Y=S((dr,se)=>{"use strict";var{EMPTY_BUFFER:jt}=T(),pe=Buffer[Symbol.species];function Vt(t,e){if(t.length===0)return jt;if(t.length===1)return t[0];let s=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let n=t[i];s.set(n,r),r+=n.length}return r<e?new pe(s.buffer,s.byteOffset,r):s}function Ge(t,e,s,r,i){for(let n=0;n<i;n++)s[r+n]=t[n]^e[n&3]}function $e(t,e){for(let s=0;s<t.length;s++)t[s]^=e[s&3]}function zt(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ge(t){if(ge.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new pe(t):ArrayBuffer.isView(t)?e=new pe(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ge.readOnly=!1),e}se.exports={concat:Vt,mask:Ge,toArrayBuffer:zt,toBuffer:ge,unmask:$e};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=p("bufferutil");se.exports.mask=function(e,s,r,i,n){n<48?Ge(e,s,r,i,n):t.mask(e,s,r,i,n)},se.exports.unmask=function(e,s){e.length<32?$e(e,s):t.unmask(e,s)}}catch{}});var ze=S((_r,Ve)=>{"use strict";var je=Symbol("kDone"),ye=Symbol("kRun"),xe=class{constructor(e){this[je]=()=>{this.pending--,this[ye]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ye]()}[ye](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[je])}}};Ve.exports=xe});var X=S((mr,Xe)=>{"use strict";var K=p("zlib"),He=Y(),Ht=ze(),{kStatusCode:Ye}=T(),Yt=Buffer[Symbol.species],Kt=Buffer.from([0,0,255,255]),ie=Symbol("permessage-deflate"),k=Symbol("total-length"),F=Symbol("callback"),N=Symbol("buffers"),W=Symbol("error"),re,Se=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!re){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;re=new Ht(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[F];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let s=this._options,r=e.find(i=>!(s.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(s.serverMaxWindowBits===!1||typeof s.serverMaxWindowBits=="number"&&s.serverMaxWindowBits>i.server_max_window_bits)||typeof s.clientMaxWindowBits=="number"&&(typeof i.client_max_window_bits=="number"?s.clientMaxWindowBits>i.client_max_window_bits:!i.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return s.serverNoContextTakeover&&(r.server_no_context_takeover=!0),s.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof s.serverMaxWindowBits=="number"&&(r.server_max_window_bits=s.serverMaxWindowBits),typeof s.clientMaxWindowBits=="number"?r.client_max_window_bits=s.clientMaxWindowBits:(r.client_max_window_bits===!0||s.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let s=e[0];if(this._options.clientNoContextTakeover===!1&&s.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!s.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(s.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&s.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return s}normalizeParams(e){return e.forEach(s=>{Object.keys(s).forEach(r=>{let i=s[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);s[r]=i})}),e}decompress(e,s,r){re.add(i=>{this._decompress(e,s,(n,o)=>{i(),r(n,o)})})}compress(e,s,r){re.add(i=>{this._compress(e,s,(n,o)=>{i(),r(n,o)})})}_decompress(e,s,r){let i=this._isServer?"client":"server";if(!this._inflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?K.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=K.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ie]=this,this._inflate[k]=0,this._inflate[N]=[],this._inflate.on("error",Zt),this._inflate.on("data",Ke)}this._inflate[F]=r,this._inflate.write(e),s&&this._inflate.write(Kt),this._inflate.flush(()=>{let n=this._inflate[W];if(n){this._inflate.close(),this._inflate=null,r(n);return}let o=He.concat(this._inflate[N],this._inflate[k]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[k]=0,this._inflate[N]=[],s&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,s,r){let i=this._isServer?"server":"client";if(!this._deflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?K.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=K.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[k]=0,this._deflate[N]=[],this._deflate.on("data",Xt)}this._deflate[F]=r,this._deflate.write(e),this._deflate.flush(K.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=He.concat(this._deflate[N],this._deflate[k]);s&&(n=new Yt(n.buffer,n.byteOffset,n.length-4)),this._deflate[F]=null,this._deflate[k]=0,this._deflate[N]=[],s&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,n)})}};Xe.exports=Se;function Xt(t){this[N].push(t),this[k]+=t.length}function Ke(t){if(this[k]+=t.length,this[ie]._maxPayload<1||this[k]<=this[ie]._maxPayload){this[N].push(t);return}this[W]=new RangeError("Max payload size exceeded"),this[W].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[W][Ye]=1009,this.removeListener("data",Ke),this.reset()}function Zt(t){if(this[ie]._inflate=null,this[W]){this[F](this[W]);return}t[Ye]=1007,this[F](t)}});var q=S((pr,ne)=>{"use strict";var{isUtf8:Ze}=p("buffer"),{hasBlob:Qt}=T(),Jt=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function es(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ee(t){let e=t.length,s=0;for(;s<e;)if((t[s]&128)===0)s++;else if((t[s]&224)===192){if(s+1===e||(t[s+1]&192)!==128||(t[s]&254)===192)return!1;s+=2}else if((t[s]&240)===224){if(s+2>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||t[s]===224&&(t[s+1]&224)===128||t[s]===237&&(t[s+1]&224)===160)return!1;s+=3}else if((t[s]&248)===240){if(s+3>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||(t[s+3]&192)!==128||t[s]===240&&(t[s+1]&240)===128||t[s]===244&&t[s+1]>143||t[s]>244)return!1;s+=4}else return!1;return!0}function ts(t){return Qt&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ne.exports={isBlob:ts,isValidStatusCode:es,isValidUTF8:Ee,tokenChars:Jt};if(Ze)ne.exports.isValidUTF8=function(t){return t.length<24?Ee(t):Ze(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=p("utf-8-validate");ne.exports.isValidUTF8=function(e){return e.length<32?Ee(e):t(e)}}catch{}});var nt=S((gr,it)=>{"use strict";var{Writable:ss}=p("stream"),Qe=X(),{BINARY_TYPES:rs,EMPTY_BUFFER:Je,kStatusCode:is,kWebSocket:ns}=T(),{concat:ve,toArrayBuffer:os,unmask:as}=Y(),{isValidStatusCode:fs,isValidUTF8:et}=q(),oe=Buffer[Symbol.species],v=0,tt=1,st=2,rt=3,be=4,we=5,ae=6,Oe=class extends ss{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||rs[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ns]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=v}_write(e,s,r){if(this._opcode===8&&this._state==v)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new oe(r.buffer,r.byteOffset+e,r.length-e),new oe(r.buffer,r.byteOffset,e)}let s=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=s.length-e;e>=r.length?s.set(this._buffers.shift(),i):(s.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new oe(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return s}startLoop(e){this._loop=!0;do switch(this._state){case v:this.getInfo(e);break;case tt:this.getPayloadLength16(e);break;case st:this.getPayloadLength64(e);break;case rt:this.getMask();break;case be:this.getData(e);break;case we:case ae:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let s=this.consume(2);if((s[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(s[0]&64)===64;if(r&&!this._extensions[Qe.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(s[0]&128)===128,this._opcode=s[0]&15,this._payloadLength=s[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(s[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=tt:this._payloadLength===127?this._state=st:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let s=this.consume(8),r=s.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+s.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(s);return}this._masked?this._state=rt:this._state=be}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=be}getData(e){let s=Je;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}s=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&as(s,this._mask)}if(this._opcode>7){this.controlMessage(s,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=we,this.decompress(s,e);return}s.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(s)),this.dataMessage(e)}decompress(e,s){this._extensions[Qe.extensionName].decompress(e,this._fin,(i,n)=>{if(i)return s(i);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");s(o);return}this._fragments.push(n)}this.dataMessage(s),this._state===v&&this.startLoop(s)})}dataMessage(e){if(!this._fin){this._state=v;return}let s=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=ve(r,s):this._binaryType==="arraybuffer"?i=os(ve(r,s)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=v):(this._state=ae,setImmediate(()=>{this.emit("message",i,!0),this._state=v,this.startLoop(e)}))}else{let i=ve(r,s);if(!this._skipUTF8Validation&&!et(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===we||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=v):(this._state=ae,setImmediate(()=>{this.emit("message",i,!1),this._state=v,this.startLoop(e)}))}}controlMessage(e,s){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Je),this.end();else{let r=e.readUInt16BE(0);if(!fs(r)){let n=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");s(n);return}let i=new oe(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!et(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");s(n);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=v;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=v):(this._state=ae,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=v,this.startLoop(s)}))}createError(e,s,r,i,n){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${s}`:s);return Error.captureStackTrace(o,this.createError),o.code=n,o[is]=i,o}};it.exports=Oe});var lt=S((xr,ft)=>{"use strict";var{Duplex:yr}=p("stream"),{randomFillSync:ls}=p("crypto"),{types:{isUint8Array:hs}}=p("util"),ot=X(),{EMPTY_BUFFER:cs,kWebSocket:us,NOOP:ds}=T(),{isBlob:G,isValidStatusCode:_s}=q(),{mask:at,toBuffer:P}=Y(),b=Symbol("kByteLength"),ms=Buffer.alloc(4),fe=8*1024,R,$=fe,w=0,ps=1,gs=2,Te=class t{constructor(e,s,r){this._extensions=s||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=w,this.onerror=ds,this[us]=void 0}static frame(e,s){let r,i=!1,n=2,o=!1;s.mask&&(r=s.maskBuffer||ms,s.generateMask?s.generateMask(r):($===fe&&(R===void 0&&(R=Buffer.alloc(fe)),ls(R,0,fe),$=0),r[0]=R[$++],r[1]=R[$++],r[2]=R[$++],r[3]=R[$++]),o=(r[0]|r[1]|r[2]|r[3])===0,n=6);let f;typeof e=="string"?(!s.mask||o)&&s[b]!==void 0?f=s[b]:(e=Buffer.from(e),f=e.length):(f=e.length,i=s.mask&&s.readOnly&&!o);let l=f;f>=65536?(n+=8,l=127):f>125&&(n+=2,l=126);let a=Buffer.allocUnsafe(i?f+n:n);return a[0]=s.fin?s.opcode|128:s.opcode,s.rsv1&&(a[0]|=64),a[1]=l,l===126?a.writeUInt16BE(f,2):l===127&&(a[2]=a[3]=0,a.writeUIntBE(f,4,6)),s.mask?(a[1]|=128,a[n-4]=r[0],a[n-3]=r[1],a[n-2]=r[2],a[n-1]=r[3],o?[a,e]:i?(at(e,r,a,n,f),[a]):(at(e,r,e,0,f),[a,e])):[a,e]}close(e,s,r,i){let n;if(e===void 0)n=cs;else{if(typeof e!="number"||!_s(e))throw new TypeError("First argument must be a valid error code number");if(s===void 0||!s.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let f=Buffer.byteLength(s);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");if(n=Buffer.allocUnsafe(2+f),n.writeUInt16BE(e,0),typeof s=="string")n.write(s,2);else if(hs(s))n.set(s,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[b]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==w?this.enqueue([this.dispatch,n,!1,o,i]):this.sendFrame(t.frame(n,o),i)}ping(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):G(e)?(i=e.size,n=!1):(e=P(e),i=e.length,n=P.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[b]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};G(e)?this._state!==w?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==w?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):G(e)?(i=e.size,n=!1):(e=P(e),i=e.length,n=P.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[b]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};G(e)?this._state!==w?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==w?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,s,r){let i=this._extensions[ot.extensionName],n=s.binary?2:1,o=s.compress,f,l;typeof e=="string"?(f=Buffer.byteLength(e),l=!1):G(e)?(f=e.size,l=!1):(e=P(e),f=e.length,l=P.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=f>=i._threshold),this._compress=o):(o=!1,n=0),s.fin&&(this._firstFragment=!0);let a={[b]:f,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:l,rsv1:o};G(e)?this._state!==w?this.enqueue([this.getBlobData,e,this._compress,a,r]):this.getBlobData(e,this._compress,a,r):this._state!==w?this.enqueue([this.dispatch,e,this._compress,a,r]):this.dispatch(e,this._compress,a,r)}getBlobData(e,s,r,i){this._bufferedBytes+=r[b],this._state=gs,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(ke,this,f,i);return}this._bufferedBytes-=r[b];let o=P(n);s?this.dispatch(o,s,r,i):(this._state=w,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(n=>{process.nextTick(ys,this,n,i)})}dispatch(e,s,r,i){if(!s){this.sendFrame(t.frame(e,r),i);return}let n=this._extensions[ot.extensionName];this._bufferedBytes+=r[b],this._state=ps,n.compress(e,r.fin,(o,f)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");ke(this,l,i);return}this._bufferedBytes-=r[b],this._state=w,r.readOnly=!1,this.sendFrame(t.frame(f,r),i),this.dequeue()})}dequeue(){for(;this._state===w&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][b],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][b],this._queue.push(e)}sendFrame(e,s){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],s),this._socket.uncork()):this._socket.write(e[0],s)}};ft.exports=Te;function ke(t,e,s){typeof s=="function"&&s(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],n=i[i.length-1];typeof n=="function"&&n(e)}}function ys(t,e,s){ke(t,e,s),t.onerror(e)}});var Ce=S((Sr,ht)=>{"use strict";var{tokenChars:Z}=q();function O(t,e,s){t[e]===void 0?t[e]=[s]:t[e].push(s)}function xs(t){let e=Object.create(null),s=Object.create(null),r=!1,i=!1,n=!1,o,f,l=-1,a=-1,h=-1,c=0;for(;c<t.length;c++)if(a=t.charCodeAt(c),o===void 0)if(h===-1&&Z[a]===1)l===-1&&(l=c);else if(c!==0&&(a===32||a===9))h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let g=t.slice(l,h);a===44?(O(e,g,s),s=Object.create(null)):o=g,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);else if(f===void 0)if(h===-1&&Z[a]===1)l===-1&&(l=c);else if(a===32||a===9)h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c),O(s,t.slice(l,h),!0),a===44&&(O(e,o,s),s=Object.create(null),o=void 0),l=h=-1}else if(a===61&&l!==-1&&h===-1)f=t.slice(l,c),l=h=-1;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(i){if(Z[a]!==1)throw new SyntaxError(`Unexpected character at index ${c}`);l===-1?l=c:r||(r=!0),i=!1}else if(n)if(Z[a]===1)l===-1&&(l=c);else if(a===34&&l!==-1)n=!1,h=c;else if(a===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(a===34&&t.charCodeAt(c-1)===61)n=!0;else if(h===-1&&Z[a]===1)l===-1&&(l=c);else if(l!==-1&&(a===32||a===9))h===-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let g=t.slice(l,h);r&&(g=g.replace(/\\/g,""),r=!1),O(s,f,g),a===44&&(O(e,o,s),s=Object.create(null),o=void 0),f=void 0,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);if(l===-1||n||a===32||a===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=c);let _=t.slice(l,h);return o===void 0?O(e,_,s):(f===void 0?O(s,_,!0):r?O(s,f,_.replace(/\\/g,"")):O(s,f,_),O(e,o,s)),e}function Ss(t){return Object.keys(t).map(e=>{let s=t[e];return Array.isArray(s)||(s=[s]),s.map(r=>[e].concat(Object.keys(r).map(i=>{let n=r[i];return Array.isArray(n)||(n=[n]),n.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ht.exports={format:Ss,parse:xs}});var xt=S((Er,yt)=>{"use strict";var{kForOnEventAttribute:Q,kListener:Le}=T(),ct=Symbol("kCode"),ut=Symbol("kData"),dt=Symbol("kError"),_t=Symbol("kMessage"),mt=Symbol("kReason"),j=Symbol("kTarget"),pt=Symbol("kType"),gt=Symbol("kWasClean"),C=class{constructor(e){this[j]=null,this[pt]=e}get target(){return this[j]}get type(){return this[pt]}};Object.defineProperty(C.prototype,"target",{enumerable:!0});Object.defineProperty(C.prototype,"type",{enumerable:!0});var U=class extends C{constructor(e,s={}){super(e),this[ct]=s.code===void 0?0:s.code,this[mt]=s.reason===void 0?"":s.reason,this[gt]=s.wasClean===void 0?!1:s.wasClean}get code(){return this[ct]}get reason(){return this[mt]}get wasClean(){return this[gt]}};Object.defineProperty(U.prototype,"code",{enumerable:!0});Object.defineProperty(U.prototype,"reason",{enumerable:!0});Object.defineProperty(U.prototype,"wasClean",{enumerable:!0});var V=class extends C{constructor(e,s={}){super(e),this[dt]=s.error===void 0?null:s.error,this[_t]=s.message===void 0?"":s.message}get error(){return this[dt]}get message(){return this[_t]}};Object.defineProperty(V.prototype,"error",{enumerable:!0});Object.defineProperty(V.prototype,"message",{enumerable:!0});var J=class extends C{constructor(e,s={}){super(e),this[ut]=s.data===void 0?null:s.data}get data(){return this[ut]}};Object.defineProperty(J.prototype,"data",{enumerable:!0});var Es={addEventListener(t,e,s={}){for(let i of this.listeners(t))if(!s[Q]&&i[Le]===e&&!i[Q])return;let r;if(t==="message")r=function(n,o){let f=new J("message",{data:o?n:n.toString()});f[j]=this,le(e,this,f)};else if(t==="close")r=function(n,o){let f=new U("close",{code:n,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[j]=this,le(e,this,f)};else if(t==="error")r=function(n){let o=new V("error",{error:n,message:n.message});o[j]=this,le(e,this,o)};else if(t==="open")r=function(){let n=new C("open");n[j]=this,le(e,this,n)};else return;r[Q]=!!s[Q],r[Le]=e,s.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let s of this.listeners(t))if(s[Le]===e&&!s[Q]){this.removeListener(t,s);break}}};yt.exports={CloseEvent:U,ErrorEvent:V,Event:C,EventTarget:Es,MessageEvent:J};function le(t,e,s){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,s):t.call(e,s)}});var Ue=S((wr,Bt)=>{"use strict";var vs=p("events"),bs=p("https"),ws=p("http"),vt=p("net"),Os=p("tls"),{randomBytes:Ts,createHash:ks}=p("crypto"),{Duplex:vr,Readable:br}=p("stream"),{URL:Ne}=p("url"),B=X(),Cs=nt(),Ls=lt(),{isBlob:Ns}=q(),{BINARY_TYPES:St,CLOSE_TIMEOUT:Bs,EMPTY_BUFFER:he,GUID:Ps,kForOnEventAttribute:Be,kListener:Rs,kStatusCode:Us,kWebSocket:y,NOOP:bt}=T(),{EventTarget:{addEventListener:Is,removeEventListener:Ds}}=xt(),{format:Ms,parse:As}=Ce(),{toBuffer:Fs}=Y(),wt=Symbol("kAborted"),Pe=[8,13],L=["CONNECTING","OPEN","CLOSING","CLOSED"],Ws=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,d=class t extends vs{constructor(e,s,r){super(),this._binaryType=St[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=he,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0?!r||r.protocols===void 0?s=[]:Array.isArray(r.protocols)?s=r.protocols:s=[r.protocols]:Array.isArray(s)||(typeof s=="object"&&s!==null?(r=s,r.protocols===void 0?s=[]:Array.isArray(r.protocols)?s=r.protocols:s=[r.protocols]):s=[s]),Ot(this,e,s,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){St.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,s,r){let i=new Cs({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),n=new Ls(e,this._extensions,r.generateMask);this._receiver=i,this._sender=n,this._socket=e,i[y]=this,n[y]=this,e[y]=this,i.on("conclude",$s),i.on("drain",js),i.on("error",Vs),i.on("message",zs),i.on("ping",Hs),i.on("pong",Ys),n.onerror=Ks,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),s.length>0&&e.unshift(s),e.on("close",Ct),e.on("data",ue),e.on("end",Lt),e.on("error",Nt),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[B.extensionName]&&this._extensions[B.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,s){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._sender.close(e,s,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._readyState=t.CLOSING,kt(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Re(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.ping(e||he,s,r)}pong(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Re(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.pong(e||he,s,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof s=="function"&&(r=s,s={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Re(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...s};this._extensions[B.extensionName]||(i.compress=!1),this._sender.send(e||he,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(d,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")});Object.defineProperty(d.prototype,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")});Object.defineProperty(d,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")});Object.defineProperty(d.prototype,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")});Object.defineProperty(d,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")});Object.defineProperty(d.prototype,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")});Object.defineProperty(d,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")});Object.defineProperty(d.prototype,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(d.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(d.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Be])return e[Rs];return null},set(e){for(let s of this.listeners(t))if(s[Be]){this.removeListener(t,s);break}typeof e=="function"&&this.addEventListener(t,e,{[Be]:!0})}})});d.prototype.addEventListener=Is;d.prototype.removeEventListener=Ds;Bt.exports=d;function Ot(t,e,s,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Bs,protocolVersion:Pe[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!Pe.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Pe.join(", ")})`);let n;if(e instanceof Ne)n=e;else try{n=new Ne(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),t._url=n.href;let o=n.protocol==="wss:",f=n.protocol==="ws+unix:",l;if(n.protocol!=="ws:"&&!o&&!f?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!n.pathname?l="The URL's pathname is empty":n.hash&&(l="The URL contains a fragment identifier"),l){let u=new SyntaxError(l);if(t._redirects===0)throw u;ce(t,u);return}let a=o?443:80,h=Ts(16).toString("base64"),c=o?bs.request:ws.request,_=new Set,g;if(i.createConnection=i.createConnection||(o?Gs:qs),i.defaultPort=i.defaultPort||a,i.port=n.port||a,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new B({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Ms({[B.extensionName]:g.offer()})),s.length){for(let u of s){if(typeof u!="string"||!Ws.test(u)||_.has(u))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(u)}i.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),f){let u=i.path.split(":");i.socketPath=u[0],i.path=u[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=f,t._originalSecure=o,t._originalHostOrSocketPath=f?i.socketPath:n.host;let u=r&&r.headers;if(r={...r,headers:{}},u)for(let[x,M]of Object.entries(u))r.headers[x.toLowerCase()]=M}else if(t.listenerCount("redirect")===0){let u=f?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:n.host===t._originalHostOrSocketPath;(!u||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,u||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=c(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=c(i);i.timeout&&m.on("timeout",()=>{E(t,m,"Opening handshake has timed out")}),m.on("error",u=>{m===null||m[wt]||(m=t._req=null,ce(t,u))}),m.on("response",u=>{let x=u.headers.location,M=u.statusCode;if(x&&i.followRedirects&&M>=300&&M<400){if(++t._redirects>i.maxRedirects){E(t,m,"Maximum redirects exceeded");return}m.abort();let z;try{z=new Ne(x,e)}catch{let A=new SyntaxError(`Invalid URL: ${x}`);ce(t,A);return}Ot(t,z,s,r)}else t.emit("unexpected-response",m,u)||E(t,m,`Unexpected server response: ${u.statusCode}`)}),m.on("upgrade",(u,x,M)=>{if(t.emit("upgrade",u),t.readyState!==d.CONNECTING)return;m=t._req=null;let z=u.headers.upgrade;if(z===void 0||z.toLowerCase()!=="websocket"){E(t,x,"Invalid Upgrade header");return}let De=ks("sha1").update(h+Ps).digest("base64");if(u.headers["sec-websocket-accept"]!==De){E(t,x,"Invalid Sec-WebSocket-Accept header");return}let A=u.headers["sec-websocket-protocol"],H;if(A!==void 0?_.size?_.has(A)||(H="Server sent an invalid subprotocol"):H="Server sent a subprotocol but none was requested":_.size&&(H="Server sent no subprotocol"),H){E(t,x,H);return}A&&(t._protocol=A);let Me=u.headers["sec-websocket-extensions"];if(Me!==void 0){if(!g){E(t,x,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let _e;try{_e=As(Me)}catch{E(t,x,"Invalid Sec-WebSocket-Extensions header");return}let Ae=Object.keys(_e);if(Ae.length!==1||Ae[0]!==B.extensionName){E(t,x,"Server indicated an extension that was not requested");return}try{g.accept(_e[B.extensionName])}catch{E(t,x,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[B.extensionName]=g}t.setSocket(x,M,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function ce(t,e){t._readyState=d.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function qs(t){return t.path=t.socketPath,vt.connect(t)}function Gs(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=vt.isIP(t.host)?"":t.host),Os.connect(t)}function E(t,e,s){t._readyState=d.CLOSING;let r=new Error(s);Error.captureStackTrace(r,E),e.setHeader?(e[wt]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ce,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Re(t,e,s){if(e){let r=Ns(e)?e.size:Fs(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(s){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${L[t.readyState]})`);process.nextTick(s,r)}}function $s(t,e){let s=this[y];s._closeFrameReceived=!0,s._closeMessage=e,s._closeCode=t,s._socket[y]!==void 0&&(s._socket.removeListener("data",ue),process.nextTick(Tt,s._socket),t===1005?s.close():s.close(t,e))}function js(){let t=this[y];t.isPaused||t._socket.resume()}function Vs(t){let e=this[y];e._socket[y]!==void 0&&(e._socket.removeListener("data",ue),process.nextTick(Tt,e._socket),e.close(t[Us])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Et(){this[y].emitClose()}function zs(t,e){this[y].emit("message",t,e)}function Hs(t){let e=this[y];e._autoPong&&e.pong(t,!this._isServer,bt),e.emit("ping",t)}function Ys(t){this[y].emit("pong",t)}function Tt(t){t.resume()}function Ks(t){let e=this[y];e.readyState!==d.CLOSED&&(e.readyState===d.OPEN&&(e._readyState=d.CLOSING,kt(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function kt(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ct(){let t=this[y];if(this.removeListener("close",Ct),this.removeListener("data",ue),this.removeListener("end",Lt),t._readyState=d.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[y]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Et),t._receiver.on("finish",Et))}function ue(t){this[y]._receiver.write(t)||this.pause()}function Lt(){let t=this[y];t._readyState=d.CLOSING,t._receiver.end(),this.end()}function Nt(){let t=this[y];this.removeListener("error",Nt),this.on("error",bt),t&&(t._readyState=d.CLOSING,this.destroy())}});var Js=S((Tr,Ut)=>{"use strict";var Or=Ue(),{Duplex:Xs}=p("stream");function Pt(t){t.emit("close")}function Zs(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Rt(t){this.removeListener("error",Rt),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Qs(t,e){let s=!0,r=new Xs({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(n,o){let f=!o&&r._readableState.objectMode?n.toString():n;r.push(f)||t.pause()}),t.once("error",function(n){r.destroyed||(s=!1,r.destroy(n))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,n){if(t.readyState===t.CLOSED){n(i),process.nextTick(Pt,r);return}let o=!1;t.once("error",function(l){o=!0,n(l)}),t.once("close",function(){o||n(i),process.nextTick(Pt,r)}),s&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,n,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,n,o)});return}t.send(i,o)},r.on("end",Zs),r.on("error",Rt),r}Ut.exports=Qs});var Dt=S((kr,It)=>{"use strict";var{tokenChars:er}=q();function tr(t){let e=new Set,s=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&er[o]===1)s===-1&&(s=i);else if(i!==0&&(o===32||o===9))r===-1&&s!==-1&&(r=i);else if(o===44){if(s===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let f=t.slice(s,r);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),s=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(s===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let n=t.slice(s,i);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}It.exports={parse:tr}});var cr=S((Lr,Gt)=>{"use strict";var sr=p("events"),de=p("http"),{Duplex:Cr}=p("stream"),{createHash:rr}=p("crypto"),Mt=Ce(),I=X(),ir=Dt(),nr=Ue(),{CLOSE_TIMEOUT:or,GUID:ar,kWebSocket:fr}=T(),lr=/^[+/0-9A-Za-z]{22}==$/,At=0,Ft=1,qt=2,Ie=class extends sr{constructor(e,s){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:or,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:nr,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=de.createServer((r,i)=>{let n=de.STATUS_CODES[426];i.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),i.end(n)}),this._server.listen(e.port,e.host,e.backlog,s)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=hr(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,n,o)=>{this.handleUpgrade(i,n,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=At}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===qt){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ee,this);return}if(e&&this.once("close",e),this._state!==Ft)if(this._state=Ft,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ee,this):process.nextTick(ee,this);else{let s=this._server;this._removeListeners(),this._removeListeners=this._server=null,s.close(()=>{ee(this)})}}shouldHandle(e){if(this.options.path){let s=e.url.indexOf("?");if((s!==-1?e.url.slice(0,s):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,s,r,i){s.on("error",Wt);let n=e.headers["sec-websocket-key"],o=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){D(this,e,s,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){D(this,e,s,400,"Invalid Upgrade header");return}if(n===void 0||!lr.test(n)){D(this,e,s,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){D(this,e,s,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){te(s,400);return}let l=e.headers["sec-websocket-protocol"],a=new Set;if(l!==void 0)try{a=ir.parse(l)}catch{D(this,e,s,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],c={};if(this.options.perMessageDeflate&&h!==void 0){let _=new I({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Mt.parse(h);g[I.extensionName]&&(_.accept(g[I.extensionName]),c[I.extensionName]=_)}catch{D(this,e,s,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(g,m,u,x)=>{if(!g)return te(s,m||401,u,x);this.completeUpgrade(c,n,a,e,s,r,i)});return}if(!this.options.verifyClient(_))return te(s,401)}this.completeUpgrade(c,n,a,e,s,r,i)}completeUpgrade(e,s,r,i,n,o,f){if(!n.readable||!n.writable)return n.destroy();if(n[fr])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>At)return te(n,503);let a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${rr("sha1").update(s+ar).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(r.size){let c=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;c&&(a.push(`Sec-WebSocket-Protocol: ${c}`),h._protocol=c)}if(e[I.extensionName]){let c=e[I.extensionName].params,_=Mt.format({[I.extensionName]:[c]});a.push(`Sec-WebSocket-Extensions: ${_}`),h._extensions=e}this.emit("headers",a,i),n.write(a.concat(`\r
|
|
5
|
+
`).join(`\r
|
|
6
|
+
`)),n.removeListener("error",Wt),h.setSocket(n,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ee,this)})),f(h,i)}};Gt.exports=Ie;function hr(t,e){for(let s of Object.keys(e))t.on(s,e[s]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function ee(t){t._state=qt,t.emit("close")}function Wt(){this.destroy()}function te(t,e,s,r){s=s||de.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${de.STATUS_CODES[e]}\r
|
|
7
|
+
`+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
|
|
8
|
+
`)+`\r
|
|
9
|
+
\r
|
|
10
|
+
`+s)}function D(t,e,s,r,i,n){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,D),t.emit("wsClientError",o,s,e)}else te(s,r,i,n)}});export{X as a,nt as b,lt as c,Ce as d,Ue as e,Js as f,Dt as g,cr as h};
|
|
@@ -0,0 +1,10 @@
|
|
|
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 nt,k as rt}from"./chunk-RDW6FRF5.js";import{c as et}from"./chunk-IKLTEWA3.js";import{f as st}from"./chunk-BDLKI2NT.js";import{L as it}from"./chunk-JJDEQ6N2.js";import{d as ot}from"./chunk-OE4KH3NJ.js";import{d as I,f as Q,i as N,j as Z,k as tt}from"./chunk-Z24SBRJK.js";import w from"node:fs";import g from"node:path";var at="cortex-production-benchmark-evidence-context/1",Nt=/^[a-f0-9]{64}$/;function u(t){return new Error(`Production benchmark evidence context invalid: ${t}`)}function H(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ct(t,e){let o=new Set(e);return e.every(n=>Object.hasOwn(t,n))&&Object.keys(t).every(n=>o.has(n))}function E(t,e){if(typeof t!="string"||t.length===0)throw u(e);return t}function v(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t;if(Array.isArray(t))return Object.freeze(t.map(v));if(!H(t))throw u("model_execution.model_alias_policy");let e=Object.entries(t).map(([o,n])=>[o,v(n)]);return Object.freeze(Object.fromEntries(e))}function vt(t){let e=["model_alias_policy","cli_name","cli_version","max_output_tokens"];if(!H(t)||!ct(t,e))throw u("model_execution");if(t.cli_name!=="claude"&&t.cli_name!=="pi")throw u("model_execution.cli_name");let o=t.max_output_tokens;if(o!==null&&(!Number.isInteger(o)||Number(o)<=0))throw u("model_execution.max_output_tokens");return Object.freeze({model_alias_policy:v(t.model_alias_policy),cli_name:t.cli_name,cli_version:E(t.cli_version,"model_execution.cli_version"),max_output_tokens:o})}function lt(t){let e=["schema_version","trial_id","root_run_id","bundle_manifest_hash","model_execution"];if(!H(t)||!ct(t,e))throw u("evidence context envelope");if(t.schema_version!==at)throw u("schema_version");let o=E(t.bundle_manifest_hash,"bundle_manifest_hash");if(!Nt.test(o))throw u("bundle_manifest_hash");return Object.freeze({schema_version:at,trial_id:E(t.trial_id,"trial_id"),root_run_id:E(t.root_run_id,"root_run_id"),bundle_manifest_hash:o,model_execution:vt(t.model_execution)})}import{createHash as Ht}from"node:crypto";function Ct(t){return JSON.stringify(t)}function Dt(t){return`[${Array.from({length:t.length},(o,n)=>C(t[n])??"null").join(",")}]`}function Ft(t,e){let o=C(t[e]);return o===void 0?null:`${JSON.stringify(e)}:${o}`}function Mt(t){return t!==null}function $t(t){return`{${Object.keys(t).sort().map(o=>Ft(t,o)).filter(Mt).join(",")}}`}function C(t){return t===null||typeof t!="object"?Ct(t):Array.isArray(t)?Dt(t):$t(t)}function d(t){let e=C(t);if(e===void 0)throw new TypeError("Value is not JSON-serializable");return Ht("sha256").update(e,"utf8").digest("hex")}function dt(t){return d({backend:t.backend,requested_model:t.requestedModel,model_alias_policy:t.modelAliasPolicy,provider_protocol:t.providerProtocol,configured_route_base_host:t.configuredRouteBaseHost,claude_cli_version:t.claudeCliVersion,cli_name:t.cliName,cli_version:t.cliVersion,reasoning_effort:t.reasoningEffort,max_output_tokens:t.maxOutputTokens??null})}function ut(t,e){return t<e?-1:t>e?1:0}function k(t){return d({system_prompt_sha256:t.systemPromptSha256,directive_sha256:t.directiveSha256,tools:[...t.tools].sort(),plugin_dirs:[...t.pluginDirs].sort((e,o)=>ut(e.path,o.path)),skills:[...t.skills].sort((e,o)=>ut(e.name,o.name)),mcp_composition:t.mcpComposition,mcp_tool_allowlist:t.mcpToolAllowlist?[...new Set(t.mcpToolAllowlist)].sort():void 0,hook_policy:t.hookPolicy})}import{createHash as zt}from"node:crypto";import p from"node:fs";import _ from"node:path";import*as f from"path";var Ve=3900*1e3,We=3600*1e3,Ke=f.join(tt,"projects"),Ye=f.join(I,"logs","sessions"),Xe=f.join(N,"mcp-config.json"),Qe=f.join(N,"mcp-config-empty.json"),Ze=f.join(I,".claude","settings.json"),to=["plan"],S="AskUserQuestion,Bash,Edit,EnterPlanMode,ExitPlanMode,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",P="mcp__cortex-core__",eo=[`${P}cortex_plan_enter`,`${P}cortex_plan_exit`,`${P}cortex_ask_user`],oo=new Set(["AskUserQuestion","EnterPlanMode","ExitPlanMode"]),no=new Set(["Agent"]);function ro(){return ot.map(t=>P+t)}var ht=class extends Error{cancelled;constructor(){super("Cancelled by user"),this.cancelled=!0}};var Lt={"agent:pre-tool":"PreToolUse","agent:post-tool":"PostToolUse","agent:session-start":"SessionStart"};function Jt(t){return t.startsWith("cc:")?t.slice(3):Lt[t]??null}function mt(t){let o={type:"command",command:t.script!==void 0?`node ${et(t.script).join(" ")}`:t.command};return t.timeout!==void 0&&(o.timeout=t.timeout),o}function qt(t,e,o){let n=t[e]??[];t[e]===void 0&&(t[e]=n);let r=typeof o.matcher=="string"?o.matcher:void 0,i=n.at(-1);if(i&&i.matcher===r){i.hooks.push(mt(o.run));return}let l=[mt(o.run)];n.push(r===void 0?{hooks:l}:{matcher:r,hooks:l})}function Ut(t){let e=rt(nt(),{backend:"claude",availableTools:new Set(t)}),o=Object.create(null);for(let n of e){let r=Jt(n.event);r!==null&&qt(o,r,n)}return o}function ft(t){let e=(t||S).split(",").map(o=>o.trim());return Ut(e)}function D(t){return zt("sha256").update(t).digest("hex")}function pt(t,e=t){let o=[];for(let n of p.readdirSync(e,{withFileTypes:!0})){let r=_.join(e,n.name);n.isDirectory()&&o.push(...pt(t,r)),n.isFile()&&o.push({path:_.relative(t,r),type:"file",sha256:D(p.readFileSync(r))}),n.isSymbolicLink()&&o.push({path:_.relative(t,r),type:"symlink",target:p.readlinkSync(r)})}return o}function F(t,e){return t<e?-1:t>e?1:0}function M(t){if(!p.statSync(t).isDirectory())throw new Error(`Plugin path is not a directory: ${t}`);return d(pt(t).sort((e,o)=>F(e.path,o.path)))}function Bt(t,e){let o=t.map(n=>({path:n,content_sha256:M(n)}));return e&&o.push({path:"@plugin-capability",content_sha256:e}),o.sort((n,r)=>F(n.path,r.path))}function Gt(t){let e=_.join(t,"skills");return p.existsSync(e)?p.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>({name:o.name,content_sha256:M(_.join(e,o.name))})):[]}function Vt(t){return t.map(e=>({name:_.basename(e),content_sha256:M(e)}))}function Wt(t){let e=new Set;for(let o of t){if(e.has(o.name))throw new Error(`Duplicate plugin skill name: ${o.name}`);e.add(o.name)}return t.sort((o,n)=>F(o.name,n.name))}function Kt(t,e){return Wt([...t.flatMap(Gt),...Vt(e)])}function _t(t){return t.tools.rawClaude!==void 0?(t.tools.rawClaude||S).split(","):t.tools.canonical?.length?t.tools.canonical:S.split(",")}function Yt(t){if(t.flags.disableHooks===!0)return{};let e=_t(t).join(",");return ft(e)}function Xt(t){return t.prompt.append===void 0?D(t.prompt.system??""):d({system_prompt:t.prompt.system??"",append_system_prompt:t.prompt.append})}function O(t,e=""){let o=t.plugins.dirs??[],n={systemPromptSha256:Xt(t),directiveSha256:D(e),tools:_t(t),pluginDirs:Bt(o,t.plugins.fingerprint),skills:Kt(o,t.plugins.skillDirs??[]),mcpComposition:t.mcp.composition??"direct",hookPolicy:Yt(t)};return t.mcp.allowlist!==void 0&&(n.mcpToolAllowlist=t.mcp.allowlist),n}import{createHash as G}from"node:crypto";import h from"node:fs";import b from"node:path";import{createHash as Qt}from"node:crypto";import s from"node:fs";var wt="cortex-bench-journal/2",Zt=64*1024,J="direct",j=class extends Error{reason="trajectory_write_failed";constructor(e="Trajectory write failed",o){super(e,o),this.name="TrajectoryWriteFailedError"}},$=class extends Error{operation;constructor(e,o){super(`${e} failed`,{cause:o}),this.operation=e,this.name="FilesystemOperationError"}};function a(t,e){return new $(t,e)}function m(t,e){let o=e.length===1?e[0]:new AggregateError(e);return new j(`${t}: trajectory write failed`,{cause:o})}function St(t,e){throw e instanceof j?e:m(t,[e])}function xt(t){try{return Buffer.from(`${JSON.stringify(t)}
|
|
5
|
+
`,"utf8")}catch(e){throw a("serialize",e)}}function te(t,e,o){try{return s.writeSync(t,e,o,e.length-o)}catch(n){throw a("write",n)}}function bt(t,e){let o=0;for(;o<e.length;){let n=te(t,e,o);if(n<=0)throw a("write",new Error("zero-byte write"));o+=n}}function yt(t){try{return s.fsyncSync(t),null}catch(e){return a("fsync",e)}}function q(t){try{return s.closeSync(t),null}catch(e){return a("close",e)}}function R(t,e){e&&t.push(e)}function gt(t){try{return t().toISOString()}catch(e){throw a("timestamp",e)}}function ee(t,e){return{schema_version:wt,type:"run_header",root_run_id:t.rootRunId,session_id:t.sessionId,agent_slot:t.agentSlot,seq:0,ts:e,resolved_cwd:t.resolvedCwd,canonical_instruction_sha256:t.canonicalInstructionSha256,model_visible_prompt_sha256:t.modelVisiblePromptSha256,system_prompt_sha256:t.systemPromptSha256,tool_manifest_sha256:t.toolManifestSha256,plugin_manifest_sha256:t.pluginManifestSha256,model_execution_identity_hash:t.modelExecutionIdentityHash,role_tool_surface_hash:t.roleToolSurfaceHash,bundle_manifest_hash:t.bundleManifestHash}}function oe(t,e,o,n){return{schema_version:wt,type:"event",root_run_id:e.rootRunId,session_id:t.sessionId,agent_slot:t.agentSlot,seq:o,ts:n,backend:t.backend,provider:t.provider,requested_model:t.requestedModel,reported_model:t.reportedModel,model_execution_identity_hash:e.modelExecutionIdentityHash,role_tool_surface_hash:e.roleToolSurfaceHash,bundle_manifest_hash:e.bundleManifestHash,event:t.event}}var L=class{path;identity;now;fd;nextSeq=1;count=0;constructor(e,o,n,r){this.path=e,this.identity=n,this.now=r,this.fd=o}get eventCount(){return this.count}writeEvent(e){let o;try{let n=this.requireOpenFd();o=oe(e,this.identity,this.nextSeq,gt(this.now)),bt(n,xt(o))}catch(n){St("event write",n)}return this.nextSeq+=1,this.count+=1,o}sha256(){let e=this.fd===null?null:yt(this.fd);if(e)throw m("journal hash flush",[e]);return ae(this.path)}closeSync(){if(this.fd===null)return;let e=this.fd;this.fd=null;let o=[];if(R(o,yt(e)),R(o,q(e)),o.length>0)throw m("journal close",o)}requireOpenFd(){if(this.fd!==null)return this.fd;let e=a("write",new Error("journal is closed"));throw m("event write",[e])}};function ne(t){return{rootRunId:t.rootRunId,modelExecutionIdentityHash:t.modelExecutionIdentityHash,roleToolSurfaceHash:t.roleToolSurfaceHash,bundleManifestHash:t.bundleManifestHash}}function re(t){try{let e=s.constants.O_WRONLY|s.constants.O_CREAT|s.constants.O_EXCL|s.constants.O_APPEND;return s.openSync(t,e,384)}catch(e){throw a("open",e)}}function ie(t,e){let o=[e];throw R(o,q(t)),m("journal open",o)}function Et(t){let e;try{e=re(t.path)}catch(r){St("journal open",r)}let o=t.now??(()=>new Date),n=ee(t.header,gt(o));try{bt(e,xt(n))}catch(r){ie(e,r)}return new L(t.path,e,ne(t.header),o)}function se(t){let e=Qt("sha256"),o=Buffer.allocUnsafe(Zt);for(;;){let n=s.readSync(t,o,0,o.length,null);if(n===0)return e.digest("hex");e.update(o.subarray(0,n))}}function ae(t){let e;try{e=s.openSync(t,"r")}catch(r){throw m("journal hash",[a("open",r)])}let o=null,n=[];try{o=se(e)}catch(r){n.push(a("read",r))}if(R(n,q(e)),n.length>0)throw m("journal hash",n);return o}var jt="cortex-production-attempt-journal/1",ce=/^[a-f0-9]{64}$/,kt=["schema_version","attempt_id","execution_id","journal_path","journal_sha256","event_count","closed_at"],y=null,x=null;function le(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ue(t){let e=new Set(kt);return kt.every(o=>Object.hasOwn(t,o))&&Object.keys(t).every(o=>e.has(o))}function T(t){return typeof t=="string"&&t.length>0}function de(t){return ue(t)&&t.schema_version===jt&&T(t.attempt_id)&&T(t.execution_id)&&T(t.journal_path)&&b.isAbsolute(t.journal_path)&&typeof t.journal_sha256=="string"&&ce.test(t.journal_sha256)&&Number.isInteger(t.event_count)&&Number(t.event_count)>=0&&T(t.closed_at)&&!Number.isNaN(Date.parse(t.closed_at))}function he(t,e){let o;try{o=JSON.parse(t)}catch{throw new Error(`Production attempt journal store malformed at line ${e}`)}if(!le(o)||!de(o))throw new Error(`Production attempt journal store invalid at line ${e}`);return o}function me(t){let e=h.readFileSync(t);if(e.length===0||e.at(-1)!==10)throw new Error(`Production attempt journal is empty or incomplete: ${t}`);let n=e.toString("utf8").trimEnd().split(`
|
|
6
|
+
`).map((r,i)=>{try{return JSON.parse(r)}catch{throw new Error(`Production attempt journal malformed at ${t}:${i+1}`)}});if(n[0]?.type!=="run_header")throw new Error(`Production attempt journal header missing: ${t}`);return{sha256:G("sha256").update(e).digest("hex"),eventCount:n.slice(1).filter(r=>r.type==="event").length}}function Pt(t){let e=me(t.journal_path);if(e.sha256!==t.journal_sha256)throw new Error(`Production attempt journal digest mismatch: ${t.execution_id}`);if(e.eventCount!==t.event_count)throw new Error(`Production attempt journal event count mismatch: ${t.execution_id}`)}function U(t,e){return JSON.stringify(t)===JSON.stringify(e)}var z=class{filePath;byExecution=new Map;byAttempt=new Map;constructor(e){this.filePath=e,this.load()}load(){let e;try{e=h.readFileSync(this.filePath,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}e.split(`
|
|
7
|
+
`).filter(Boolean).forEach((o,n)=>{let r=he(o,n+1);Pt(r),this.remember(r)})}remember(e){let o=this.byExecution.get(e.execution_id),n=this.byAttempt.get(e.attempt_id);if(o&&!U(o,e)||n&&!U(n,e))throw new Error(`Production attempt journal identity collision: ${e.execution_id}`);if(o)return o;let r=Object.freeze({...e});return this.byExecution.set(e.execution_id,r),this.byAttempt.set(e.attempt_id,r),r}get(e){return this.byExecution.get(e)??null}append(e){let o=this.get(e.execution_id);if(o){if(!U(o,e))throw new Error(`Production attempt journal changed for execution ${e.execution_id}`);return o}Pt(e),h.mkdirSync(b.dirname(this.filePath),{recursive:!0,mode:448});let n=h.openSync(this.filePath,"a",384);try{h.writeFileSync(n,`${JSON.stringify(e)}
|
|
8
|
+
`,"utf8"),h.fsyncSync(n)}finally{h.closeSync(n)}return this.remember(e)}};function fe(t){return`${G("sha256").update(t.attempt_id).digest("hex")}.ndjson`}function Ot(t){return G("sha256").update(t,"utf8").digest("hex")}function pe(t){let e=O(t.spec,t.canonicalInstruction);if(k(e)!==t.identity.role_tool_surface_hash)throw new Error("Production attempt journal role identity drifted before open");return{canonicalInstructionSha256:Ot(t.canonicalInstruction),modelVisiblePromptSha256:Ot(t.message),systemPromptSha256:e.systemPromptSha256,toolManifestSha256:d(e.tools),pluginManifestSha256:d({plugin_dirs:e.pluginDirs,skills:e.skills})}}function _e(t){let{identity:e,spec:o}=t;return{rootRunId:e.root_run_id,sessionId:e.session_id,agentSlot:J,resolvedCwd:Q(o.cwd),...pe(t),modelExecutionIdentityHash:e.model_execution_identity_hash,roleToolSurfaceHash:e.role_tool_surface_hash,bundleManifestHash:e.bundle_manifest_hash}}function ye(t){if(t.type!=="tool_result"||!t.images)return t;let{images:e,...o}=t;return o}function we(t){return"model"in t&&typeof t.model=="string"&&t.model.length>0?t.model:null}var B=class{identity;journal;repo;closed=!1;writeFailure=null;constructor(e,o,n){this.identity=e,this.journal=o,this.repo=n}onEvent(e){try{this.journal.writeEvent({sessionId:this.identity.session_id,agentSlot:J,backend:this.identity.backend,provider:this.identity.provider,requestedModel:this.identity.requested_model,reportedModel:we(e),event:ye(e)})}catch(o){throw this.writeFailure??=o,o}}onClose(){if(!this.closed){if(this.closed=!0,this.journal.closeSync(),this.writeFailure)throw this.writeFailure;this.repo.append(Object.freeze({schema_version:jt,attempt_id:this.identity.attempt_id,execution_id:this.identity.execution_id,journal_path:b.resolve(this.journal.path),journal_sha256:this.journal.sha256(),event_count:this.journal.eventCount,closed_at:new Date().toISOString()}))}}};function Rt(t){x=b.resolve(t.journalDir),y=new z(t.storePath)}function V(){y=null,x=null}function Ro(t){if(!y||!x)throw new Error("Production attempt journal store is not initialized");if(y.get(t.identity.execution_id))throw new Error(`Production attempt journal already exists for execution ${t.identity.execution_id}`);h.mkdirSync(x,{recursive:!0,mode:448});let e=Et({path:b.join(x,fe(t.identity)),header:_e(t)});return new B(t.identity,e,y)}function To(t){return y?.get(t)??null}var X="cortex-production-attempt-identity/5",Se=/^[a-f0-9]{64}$/,xe=g.join(Z,"benchmark-attempt-identities.jsonl"),be=["schema_version","trial_id","root_run_id","attempt_id","root_attempt_id","spawn_parent_attempt_id","execution_id","session_id","thinking","mode","backend","provider","requested_model","model_execution_identity_hash","role_tool_surface_hash","bundle_manifest_hash","frozen_at"],c=null;function ge(t){return new Error(`Production benchmark evidence context invalid: ${t}`)}function Tt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ee(t,e){let o=new Set(e);return e.every(n=>Object.hasOwn(t,n))&&Object.keys(t).every(n=>o.has(n))}function At(t,e){if(typeof t!="string"||t.length===0)throw ge(e);return t}function ke(t){return t===null||typeof t=="string"&&t.length>0}function Pe(t){let e=["trial_id","root_run_id","attempt_id","root_attempt_id","execution_id","session_id","mode","requested_model","model_execution_identity_hash","role_tool_surface_hash","bundle_manifest_hash","frozen_at"],o=["spawn_parent_attempt_id","provider","thinking"],n=[t.model_execution_identity_hash,t.role_tool_surface_hash,t.bundle_manifest_hash];return Ee(t,be)&&t.schema_version===X&&e.every(r=>typeof t[r]=="string"&&String(t[r]).length>0)&&o.every(r=>ke(t[r]))&&(t.backend==="claude"||t.backend==="pi")&&n.every(r=>typeof r=="string"&&Se.test(r))}function Oe(t,e){let o;try{o=JSON.parse(t)}catch{throw new Error(`Production attempt identity store malformed at line ${e}`)}if(Tt(o)&&typeof o.schema_version=="string"&&o.schema_version!==X)return null;if(!Tt(o)||!Pe(o))throw new Error(`Production attempt identity store invalid at line ${e}`);return o}function je(t,e){return JSON.stringify(t)===JSON.stringify(e)}function W(t,e){return t.trial_id===e.trial_id&&t.root_run_id===e.root_run_id}var K=class{filePath;byExecution=new Map;byAttempt=new Map;ordered=[];constructor(e){this.filePath=e,this.load()}load(){let e;try{e=w.readFileSync(this.filePath,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}e.split(`
|
|
9
|
+
`).filter(Boolean).forEach((o,n)=>{let r=Oe(o,n+1);r&&this.remember(r)})}latestSessionAttempt(e){for(let o=this.ordered.length-1;o>=0;o-=1){let n=this.ordered[o];if(W(n,e)&&n.session_id===e.session_id)return n}return null}assertRunSession(e){let o=this.ordered.find(n=>W(n,e));if(o&&o.session_id!==e.session_id)throw new Error("Production attempt identity cross-run session collision")}resolveRootAttemptId(e,o){return this.assertRunSession(e),this.latestSessionAttempt(e)?.root_attempt_id??o}resolveSpawnParentAttemptId(e){return this.assertRunSession(e),this.latestSessionAttempt(e)?.attempt_id??null}assertTopology(e){if(e.attempt_id!==`execution-${e.execution_id}`)throw new Error("Production attempt identity collision between execution and attempt");if(e.spawn_parent_attempt_id===e.attempt_id)throw new Error("Production attempt identity cannot self-link");let o=this.resolveRootAttemptId(e,e.attempt_id),n=this.resolveSpawnParentAttemptId(e);if(e.root_attempt_id!==o||e.spawn_parent_attempt_id!==n)throw new Error("Production attempt spawn topology is invalid")}remember(e){if(this.byExecution.has(e.execution_id)||this.byAttempt.has(e.attempt_id))throw new Error(`Production attempt identity collision: ${e.execution_id}`);this.assertTopology(e);let o=Object.freeze({...e});return this.byExecution.set(e.execution_id,o),this.byAttempt.set(e.attempt_id,o),this.ordered.push(o),o}get(e){return this.byExecution.get(e)??null}list(e){let o=At(e.trialId,"trial identity"),n=At(e.rootRunId,"root run identity"),r=this.ordered.filter(i=>i.trial_id===o&&i.root_run_id===n);if(r.length===0)throw new Error(`No production attempts found for ${o}/${n}`);return Object.freeze([...r])}firstRootAttempt(e){return this.ordered.find(o=>W(o,e))??null}append(e){let o=this.get(e.execution_id);if(o){if(!je(o,e))throw new Error(`Production attempt identity changed for execution ${e.execution_id}`);return o}this.assertTopology(e),w.mkdirSync(g.dirname(this.filePath),{recursive:!0,mode:448});let n=w.openSync(this.filePath,"a",384);try{w.writeFileSync(n,`${JSON.stringify(e)}
|
|
10
|
+
`,"utf8"),w.fsyncSync(n)}finally{w.closeSync(n)}return this.remember(e)}};function Re(t){return t.configurationRevision?.()??null}function $o(t={}){c=null,V();let e=t.storePath??xe,o=g.dirname(e);try{let n=new K(e);Rt({journalDir:g.join(o,"benchmark-attempt-journals"),storePath:g.join(o,"benchmark-attempt-journals.jsonl")}),c={repo:n,revision:Re(t),configurationRevision:t.configurationRevision}}catch(n){throw V(),n}}function Te(t){let e=t.configurationRevision?.()??null;if(JSON.stringify(e)!==JSON.stringify(t.revision))throw new Error("Production benchmark configuration hot-reload drift detected")}function Y(t,e){if(typeof t!="string"||t.length===0)throw new Error(`Production benchmark attempt is missing ${e}`);return t}var It=Object.freeze({deepseek:"https://api.deepseek.com","openai-codex":"https://chatgpt.com/backend-api"});function Ae(t){if(!t)return null;let e=it.findPi(t)?.baseUrl;return e||(Object.hasOwn(It,t)?It[t]:null)}function Ie(t,e){let o=e==="pi"?Ae(t.model.provider):t.env.sets?.ANTHROPIC_BASE_URL??t.route.anthropicBaseUrl;if(!o)return null;try{return new URL(o).host}catch{throw new Error(`Production benchmark resolved route is invalid: ${o}`)}}function Ne(t,e){if(t.model.id!==e.model)throw new Error("Production benchmark resolved model drifted before adapter spawn");if((t.model.thinking??null)!==e.thinking)throw new Error("Production benchmark resolved thinking drifted before adapter spawn");if(e.backend==="pi"&&(t.model.provider??null)!==e.provider)throw new Error("Production benchmark resolved provider drifted before adapter spawn")}function ve(t,e){let o=t.selection;if(!o)throw new Error("Production benchmark attempt is missing selection");if(o.backend!==e.model_execution.cli_name||o.backend!==t.adapterBackend)throw new Error("Production benchmark backend differs from injected CLI identity");return Ne(t.spec,o),o}function He(t,e){let o=e.model_execution.max_output_tokens,n=t.model.benchmarkMaxOutputTokens??null;if(n!==o)throw new Error("Production benchmark max output token identity drifted");return n}function Ce(t,e,o,n,r){let i=Y(o,"execution identity"),l=`execution-${i}`,A={trial_id:n.trial_id,root_run_id:n.root_run_id,session_id:Y(e.session.sessionId,"session identity")};return{attempt_id:l,root_attempt_id:r?.root_attempt_id??t.repo.resolveRootAttemptId(A,l),spawn_parent_attempt_id:r?.spawn_parent_attempt_id??t.repo.resolveSpawnParentAttemptId(A),execution_id:i,session_id:A.session_id}}function De(t,e,o){let n=t.model_execution;return dt({backend:o.backend,requestedModel:o.model,modelAliasPolicy:n.model_alias_policy,providerProtocol:o.provider,configuredRouteBaseHost:Ie(e,o.backend),claudeCliVersion:o.backend==="claude"?n.cli_version:null,cliName:n.cli_name,cliVersion:n.cli_version,reasoningEffort:o.thinking,maxOutputTokens:He(e,t)})}function Fe(t,e){let o=ve(e,t),n=typeof e.request.benchmark?.identityDirective=="string"?e.request.benchmark.identityDirective:"",r=O(e.spec,n);return{thinking:o.thinking,mode:st(o),backend:o.backend,provider:o.provider,requested_model:o.model,model_execution_identity_hash:De(t,e.spec,o),role_tool_surface_hash:k(r)}}function Me(t,e,o,n){return{schema_version:X,trial_id:o.trial_id,root_run_id:o.root_run_id,...Ce(t,e.request,e.executionId,o,n),...Fe(o,e),bundle_manifest_hash:o.bundle_manifest_hash,frozen_at:new Date().toISOString()}}function $e(t,e){let o=t.firstRootAttempt(e);if(!o)return;if(["trial_id","root_run_id","bundle_manifest_hash","thinking","mode","backend","provider","requested_model","model_execution_identity_hash"].some(r=>o[r]!==e[r]))throw new Error("Production benchmark immutable root identity baseline drifted");if(o.role_tool_surface_hash!==e.role_tool_surface_hash)throw new Error("Production benchmark immutable role tool baseline drifted")}function Lo(t){let e=t.request.benchmark?.evidenceContext??null;if(e==null)return null;if(!c)throw new Error("Production benchmark identity store is not initialized");Te(c);let o=lt(e),n=Y(t.executionId,"execution identity"),r=c.repo.get(n),i=Me(c,t,o,r),l=r?{...i,frozen_at:r.frozen_at}:i;return $e(c.repo,l),c.repo.append(l)}function Le(){if(!c)throw new Error("Production benchmark identity store is not initialized");return c.repo}function Jo(t){return Le().list(t)}export{Ve as a,We as b,Ke as c,Ye as d,Xe as e,Qe as f,Ze as g,to as h,S as i,eo as j,oo as k,no as l,ro as m,ht as n,Jt as o,ft as p,lt as q,J as r,Ro as s,To as t,$o as u,Lo as v,Jo as w};
|
|
@@ -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{c as $}from"./chunk-STUHNKQS.js";import{b as j}from"./chunk-TX46YMGI.js";import{a as A}from"./chunk-Q4UGYGU5.js";import{d as _}from"./chunk-AVXDF7AG.js";import{e as L}from"./chunk-VBN2JSER.js";import{i as I}from"./chunk-Z24SBRJK.js";import{readFileSync as de}from"node:fs";import fe from"node:path";var M=Math.floor(Number.MAX_SAFE_INTEGER/864e5);function x(e){return Number.isInteger(e)?e<1e3?"must be at least 1000 milliseconds":e>2147483647?"must be at most 2147483647 milliseconds":null:"must be an integer number of milliseconds"}var V=1024,k=131072;function ae(e){return Number.isInteger(e)?e<V?`must be at least ${V} tokens`:e>k?`must be at most ${k} tokens`:null:"must be a whole number of tokens"}var X=1e5,W=1e6;function le(e){return e===null?null:Number.isInteger(e)?e<X||e>W?`must be between ${X} and ${W} tokens`:null:"must be a whole number of tokens"}function ue(e){return Number.isSafeInteger(e)?e<1?"must be at least 1 day":e>M?`must be at most ${M} days`:null:"must be a safe integer number of days"}var F=24;function ce(e){return Number.isFinite(e)?e<0||e>F?`must be between 0 and ${F} hours`:null:"must be a number of hours"}var d={turnNotify:{envVar:"CORTEX_TURN_NOTIFY",type:"boolean",default:!0,legacyParse:e=>!["0","false","off","no"].includes(e.trim().toLowerCase())},turnNotifyThresholdS:{envVar:"CORTEX_TURN_NOTIFY_THRESHOLD_S",type:"number",default:60,legacyParse:e=>{let t=Number(e.trim());return Number.isFinite(t)&&t>0?t:60}},notifyCompaction:{envVar:"CORTEX_NOTIFY_COMPACTION",type:"boolean",default:!0,legacyParse:e=>!["0","false","off","no"].includes(e.trim().toLowerCase())},showToolCalls:{envVar:"CORTEX_SHOW_TOOL_CALLS",type:"boolean",default:!1,legacyParse:e=>["1","true","yes","on"].includes(e.trim().toLowerCase())},statusNewqButton:{envVar:"CORTEX_STATUS_NEWQ_BUTTON",type:"boolean",default:!1,legacyParse:e=>["1","true","on","yes"].includes(e.trim().toLowerCase())},autoResume:{envVar:"CORTEX_AUTO_RESUME",type:"boolean",default:!0,legacyParse:e=>e!=="0"&&e!=="false"},accountFailover:{type:"boolean",default:!1},showThinking:{envVar:"CORTEX_SHOW_THINKING",type:"boolean",default:!0,legacyParse:e=>!["0","false","off","no"].includes(e.trim().toLowerCase())},streamDeltas:{envVar:"CORTEX_STREAM_DELTAS",type:"boolean",default:!0,legacyParse:e=>e!=="0"},bgContinuation:{envVar:"CORTEX_BG_CONTINUATION",type:"boolean",default:!0,legacyParse:e=>!["0","false","off","no"].includes(e.trim().toLowerCase())},eventLog:{envVar:"CORTEX_EVENT_LOG",type:"boolean",default:!0,legacyParse:e=>e!=="off"},diskMonitor:{envVar:"CORTEX_DISK_MONITOR",type:"boolean",default:!0,legacyParse:e=>!["0","false","off","no"].includes(e.trim().toLowerCase())},disableUserContext:{envVar:"CORTEX_DISABLE_USER_CONTEXT",type:"boolean",default:!1,legacyParse:e=>e==="1"},serverUpdateDisable:{envVar:"CORTEX_SERVER_UPDATE_DISABLE",type:"boolean",default:!1,legacyParse:e=>e==="1"},serverAutoUpdate:{type:"boolean",default:!0},clientHotReloadEnabled:{type:"boolean",default:!0},feishuSkillsInWeb:{type:"boolean",default:!1},teamEnabled:{envVar:"CORTEX_TEAM_ENABLED",type:"boolean",default:!0,legacyParse:e=>e==="1"},telemetryEnabled:{type:"boolean",default:!0},waitpointSweepMs:{envVar:"CORTEX_WAITPOINT_SWEEP_MS",type:"number",default:3e4,legacyParse:e=>{let t=Number.parseInt(e||"",10);return Number.isFinite(t)?t:3e4}},waitpointTtlMs:{envVar:"CORTEX_WAITPOINT_TTL_MS",type:"number",default:10080*60*1e3,legacyParse:e=>{let t=Number.parseInt(e||"",10);return Number.isFinite(t)&&t>0?t:10080*60*1e3}},waitpointMaxWakesPerHour:{envVar:"CORTEX_WAITPOINT_MAX_WAKES_PER_HOUR",type:"number",default:12,legacyParse:e=>{let t=Number.parseInt(e||"",10);return Number.isFinite(t)&&t>0?t:12}},injectWaitMaxS:{envVar:"CORTEX_INJECT_WAIT_MAX_S",type:"number",default:600,legacyParse:e=>Number(e)},providerUsageCollectionEnabled:{type:"boolean",default:!0},providerUsageCollectionIntervalMs:{type:"number",default:300*1e3,validate:x},claudeWindowWarmupEnabled:{type:"boolean",default:!1},providerRateLimits:{type:"provider-rate-limits",default:{}},storeArchiveEnabled:{type:"boolean",default:!0},memoryIndexRegenEnabled:{type:"boolean",default:!0},memoryIndexRegenIntervalMs:{type:"number",default:1440*60*1e3,validate:x},sessionRetentionDays:{type:"number",default:90,validate:ue},piCompactReserveTokens:{envVar:"CORTEX_PI_COMPACT_RESERVE_TOKENS",type:"number",default:16384,legacyParse:e=>{let t=Number.parseInt(e.trim(),10);return Number.isFinite(t)?t:16384},validate:ae},maxContextTokens:{type:"number|null",default:null,validate:le},cacheKeepWarmHours:{type:"number",default:6,validate:ce},coldResumeClearToolResults:{type:"boolean",default:!0},uiCorsOrigins:{envVar:"CORTEX_UI_CORS_ORIGINS",type:"string[]",default:[],legacyParse:e=>e.split(",").map(t=>t.trim()).filter(Boolean)},adminChannel:{envVar:["SLACK_ADMIN_CHANNEL","CORTEX_ADMIN_CHANNEL"],type:"string|null",default:null,legacyParse:e=>e||null},feishuAdminChannel:{envVar:"FEISHU_ADMIN_CHANNEL",type:"string|null",default:null,legacyParse:e=>e||null}};var R=j;function Ge(e,t){return t&&t!==e?t:R}var c=L("settings"),w=fe.join(I,"settings.json"),E=Object.keys(d),be=new Set(["adminChannel","feishuAdminChannel"]),O=new Set,D=new Set,Y=new A,me=new Set(["__proto__","prototype","constructor"]),U=120,H=!1,v={},g=null,B=null,ye=null,y=null,f=!1,pe={boolean:e=>typeof e=="boolean",number:e=>typeof e=="number"&&Number.isFinite(e),"number|null":e=>e===null||typeof e=="number"&&Number.isFinite(e),"string[]":e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),"string|null":e=>e===null||typeof e=="string","provider-rate-limits":u};function u(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function h(e){let t=e.trim();return t.length===0?"provider keys must not be empty":t!==e?"provider keys must not have leading or trailing whitespace":t.length>U?`provider keys must be at most ${U} characters`:me.has(t)?`provider key "${t}" is reserved`:null}function z(e){return typeof e!="number"||!Number.isFinite(e)?"threshold must be a finite number":e<=0?"threshold must be greater than 0":e>1?"threshold must be at most 1":null}function S(e,t){if(typeof e!="string")return`${t} must be a string`;let n=e.trim();return n.length===0?`${t} must not be empty`:n!==e?`${t} must not have leading or trailing whitespace`:null}function J(e,t){if(!Object.hasOwn(e,"threshold"))return null;if(typeof e.enabled!="boolean")return`${t}.enabled must be a boolean`;let n=z(e.threshold);return n?`${t}.${n}`:null}function we(e,t){if(!u(e))return`${t} must be a plain object`;for(let r of Object.keys(e))if(!(r==="type"||r==="label"||r==="enabled"||r==="threshold"))return`${t} has unknown field "${r}"`;let n=S(e.type,"type");if(n)return`${t}.${n}`;if(Object.hasOwn(e,"label")){let r=S(e.label,"label");if(r)return`${t}.${r}`}return typeof e.enabled!="boolean"?`${t}.enabled must be a boolean`:J(e,t)}function Ee(e,t){return`${e}\0${t??""}`}function q(e,t,n=`providerRateLimits.${t}.windows`){if(!Array.isArray(e))return`${n} must be an array`;let r=new Set;for(let[o,i]of e.entries()){let s=`${n}.${o}`,a=we(i,s);if(a)return a;let l=Ee(i.type,i.label);if(r.has(l))return`${s} duplicates an existing window identity`;r.add(l)}return null}function he(e,t){if(!u(e))return`providerRateLimits.${t}.accounts must be a plain object`;for(let[n,r]of Object.entries(e)){let o=`providerRateLimits.${t}.accounts.${n}`,i=h(n);if(i)return`${o}: ${i.replace("provider keys","account keys")}`;if(!u(r))return`${o} must be a plain object`;let s=Object.keys(r).find(l=>l!=="windows");if(s)return`${o} has unknown field "${s}"`;let a=q(r.windows,t,`${o}.windows`);if(a)return a}return null}function Te(e,t){if(!u(e))return`providerRateLimits.${t} must be a plain object`;for(let r of Object.keys(e))if(!(r==="enabled"||r==="threshold"||r==="windows"||r==="accounts"))return`providerRateLimits.${t} has unknown field "${r}"`;if(Object.hasOwn(e,"enabled")&&typeof e.enabled!="boolean")return`providerRateLimits.${t}.enabled must be a boolean`;let n=J(e,`providerRateLimits.${t}`);if(n)return n;if(Object.hasOwn(e,"windows")){let r=q(e.windows,t);if(r)return r}if(Object.hasOwn(e,"accounts")){let r=he(e.accounts,t);if(r)return r}return typeof e.enabled=="boolean"||Object.hasOwn(e,"windows")||Object.hasOwn(e,"accounts")?null:`providerRateLimits.${t} must declare enabled, windows or accounts`}function Q(e){if(!u(e))return"must be a plain object";for(let[t,n]of Object.entries(e)){let r=h(t);if(r)return r;let o=Te(n,t);if(o)return o}return null}function Z(e,t){let n=S(e,t);if(n)throw new TypeError(n);return e.trim()}function _e(e){if(e!=null)return Z(e,"label")}function Oe(e){let t=e.provider.trim(),n=h(t);if(n)throw new TypeError(n);if(typeof e.enabled!="boolean")throw new TypeError("enabled must be a boolean");if(e.threshold!==null){let s=z(e.threshold);if(s)throw new TypeError(s)}let r=e.windowType===void 0?void 0:Z(e.windowType,"type"),o=_e(e.windowLabel);if(o&&!r)throw new TypeError("windowLabel requires windowType");let i=ge(e.account);if(i&&!r)throw new TypeError("account requires windowType");return{provider:t,enabled:e.enabled,threshold:e.threshold,...r?{windowType:r,account:i??R}:{},...o?{windowLabel:o}:{}}}function ge(e){if(e==null)return;if(typeof e!="string")throw new TypeError("account must be a string");let t=h(e.trim());if(t)throw new TypeError(t.replace("provider keys","account keys"));return e.trim()}function ee(e){return{type:e.type,...e.label?{label:e.label}:{},enabled:e.enabled,...Object.hasOwn(e,"threshold")?{threshold:e.threshold}:{}}}function Se(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{windows:n.windows.map(ee)}]))}function C(e){return{...typeof e.enabled=="boolean"?{enabled:e.enabled}:{},...Object.hasOwn(e,"threshold")?{threshold:e.threshold}:{},...e.windows?{windows:e.windows.map(ee)}:{},...e.accounts?{accounts:Se(e.accounts)}:{}}}function te(e){let t=Q(e);if(t)throw new TypeError(t);return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,C(r)]))}function Ne(e){return Object.hasOwn(e,"providerRateLimits")?te(e.providerRateLimits):{}}function ne(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("settings.json must contain a JSON object");for(let t of E){if(!Object.hasOwn(e,t))continue;let n=d[t];if(!pe[n.type](e[t]))throw new TypeError(`settings.json key "${t}" must have type ${n.type}`);if(n.type==="provider-rate-limits"){let o=Q(e[t]);if(o)throw new TypeError(`settings.json key "${t}" ${o}`);continue}let r=n.validate?.(e[t]);if(r)throw new TypeError(`settings.json key "${t}" ${r}`)}}function T(){try{let e=JSON.parse(de(w,"utf8"));return ne(e),e}catch(e){if(e?.code==="ENOENT")return{};throw e}}function Ye(){T()}function Re(e,t){D.has(t)||(D.add(t),c.warn(`Deprecated env ${t} supplies settings.${e}; move it to settings.json`))}function ve(e,t){return e!=="providerRateLimits"?t[e]:te(t[e])}function re(e,t,n,r){let o=d[e];if(Object.hasOwn(t,e))return{key:e,value:ve(e,t),source:"file"};let i=o.envVar===void 0?[]:typeof o.envVar=="string"?[o.envVar]:o.envVar;for(let s of i){let a=n[s];if(!(a===void 0||be.has(e)&&a.length===0))return r&&Re(e,s),{key:e,value:o.legacyParse(a),source:"env"}}return{key:e,value:o.default,source:"default"}}function P(e,t=process.env){return ne(e),E.map(n=>re(n,e,t,!1))}function N(e){return Object.fromEntries(E.map(t=>{let n=re(t,e,process.env,!0);return[t,n.value]}))}function p(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>p(n,t[r]));if(u(e)&&u(t)){let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((o,i)=>o===r[i]&&p(e[o],t[o]))}return Object.is(e,t)}function Ce(e,t){return E.filter(n=>!p(e[n],t[n]))}function Pe(e,t){let n=Ce(e,t);if(n.length!==0)for(let r of O)try{r(n)}catch(o){c.error("Settings change callback failed:",o)}}function oe(e){return Object.fromEntries(e.map(t=>[t.key,t.value]))}function Ae(e,t){return P(e).map(n=>({key:n.key,value:t[n.key],source:n.source}))}function b(e,t,n=Ae(e,t)){let r=g;v=e,g=t,B=n,r&&Pe(r,t)}function ie(){y&&clearTimeout(y),y=setTimeout(()=>{y=null,Ie()},300)}function Ie(){if(f)return ie();try{let e=T();if(p(v,e))return;b(e,N(e)),c.info("Hot-reload: settings.json reloaded")}catch(e){c.error(`Hot-reload settings.json failed: ${e.message} \u2014 keeping previous settings`)}}function Le(){ye=$({label:"settings.json",filePath:w,onChange:ie,warn:e=>c.error(e),unref:!0})}function m(){if(!H){H=!0,Le();try{let e=T();b(e,N(e))}catch(e){c.error(`Load settings.json failed: ${e.message} \u2014 using env/default settings`),b({},N({}))}}}function Be(){return m(),g}function ze(){return m(),B}function Je(e){return m(),O.add(e),()=>O.delete(e)}function se(){try{return T()}catch(e){return c.error(`Update settings.json read failed: ${e.message} \u2014 using previous settings`),v}}function K(e,t){return e.type===t.windowType&&e.label===t.windowLabel}function $e(e){return{type:e.windowType,...e.windowLabel?{label:e.windowLabel}:{},enabled:e.enabled,...e.threshold!==null?{threshold:e.threshold}:{}}}function G(e){let t=C(e);t.windows?.length||delete t.windows;for(let[n,r]of Object.entries(t.accounts??{}))r.windows.length===0&&delete t.accounts[n];return t.accounts&&Object.keys(t.accounts).length===0&&delete t.accounts,t.enabled===void 0&&t.threshold===void 0&&!t.windows&&!t.accounts?null:t}function je(e){return e.enabled===!1||e.threshold!==void 0}function Me(e,t){let n=C(e??{});if(!t.windowType)return delete n.enabled,delete n.threshold,(!t.enabled||t.threshold!==null)&&(n.enabled=t.enabled),t.threshold!==null&&(n.threshold=t.threshold),G(n);let r=t.account??R,o=n.accounts??{},i=o[r]?.windows.filter(l=>!K(l,t))??[],s=je(n)||!!n.windows?.some(l=>K(l,t)),a=t.enabled&&t.threshold===null&&s;return(!t.enabled||t.threshold!==null||a)&&i.push($e(t)),o[r]={windows:i},n.accounts=o,G(n)}async function qe(e){m();let t={...process.env};await Y.run(async()=>{let n={...se(),...e},r=P(n,t),o=oe(r);f=!0;try{await _(w,`${JSON.stringify(n,null,2)}
|
|
5
|
+
`),b(n,o,r)}finally{f=!1}})}async function Qe(e){m();let t={...process.env},n=Oe(e);return Y.run(async()=>{let r={...se()},o=Ne(r),i=Me(o[n.provider],n);i?o[n.provider]=i:delete o[n.provider],r.providerRateLimits=o;let s=P(r,t),a=oe(s);f=!0;try{await _(w,`${JSON.stringify(r,null,2)}
|
|
6
|
+
`),b(r,a,s)}finally{f=!1}return n})}export{d as a,Ge as b,ne as c,Ye as d,Be as e,ze as f,Je as g,qe as h,Qe as i};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
2
|
const require = __cortexCreateRequire(import.meta.url);
|
|
3
3
|
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a,c as y,d as f}from"./chunk-
|
|
4
|
+
import{a,c as y,d as f}from"./chunk-RDW6FRF5.js";import{e as u}from"./chunk-AVXDF7AG.js";import*as o from"node:fs";import*as d from"node:path";var p=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,v="50-";function c(e,n){return Object.assign(new Error(n),{code:e})}function l(e,n){let t=f(e).find(i=>i.entry.id===n);if(!t)throw c("not-found",`Unknown hook id: '${n}'`);return t}function h(e){if(e.source!=="user")throw c("invalid-args",`Hook '${e.entry.id}' is ${e.source}; only user entries can be edited or removed`)}function k(e){if(typeof e!="object"||e===null)throw c("invalid-args","run must be an object");let n={};return e.script!==void 0&&(n.script=e.script),e.command!==void 0&&(n.command=e.command),e.timeout!==void 0&&(n.timeout=e.timeout),n}function g(e,n){let t={id:e,event:n.event};n.matcher!==void 0&&(t.matcher=n.matcher),t.run=k(n.run),n.scope!==void 0&&(t.scope=n.scope),n.blocking!==void 0&&(t.blocking=n.blocking),n.result!==void 0&&(t.result=n.result),n.enabled!==void 0&&(t.enabled=n.enabled);try{return y(t)}catch(i){throw c("invalid-args",i instanceof Error?i.message:String(i))}}function m(e){return`${JSON.stringify(e,null,2)}
|
|
5
5
|
`}function E(e,n){let t={...e.override??{}};if(delete t.version,e.entry.enabled!==!1===n?delete t.enabled:t.enabled=n,Object.keys(t).length===0){o.rmSync(e.overridePath,{force:!0});return}o.mkdirSync(d.dirname(e.overridePath),{recursive:!0}),u(e.overridePath,`${JSON.stringify(t,null,2)}
|
|
6
6
|
`)}function $(e=a(),n,t){let i=l(e,n),r=i.entry.enabled!==!1!==t;return r?(i.builtin?E(i.builtin,t):u(i.filePath,m({...i.entry,enabled:t})),{changed:r}):{changed:r}}function H(e=a(),n){let t=e.user,i=n.id;if(typeof i!="string"||!p.test(i))throw c("invalid-args",`Hook id '${String(i)}' must start with a letter or digit and contain only letters, digits, '-' and '_'`);if(f(e).some(b=>b.entry.id===i))throw c("invalid-args",`Hook id '${i}' already exists in the registry`);let r=g(i,n),s=d.join(t,`${v}${i}.json`);if(o.existsSync(s))throw c("invalid-args",`${d.basename(s)} already exists`);return o.mkdirSync(t,{recursive:!0}),u(s,m(r)),{id:i,filePath:s}}function P(e=a(),n,t){let i=l(e,n);h(i);let r=g(n,t),s=JSON.stringify(r)!==JSON.stringify(i.entry);return s&&u(i.filePath,m(r)),{changed:s}}function x(e=a(),n){let t=l(e,n);return h(t),o.rmSync(t.filePath,{force:!0}),{removed:!0}}export{$ as a,H as b,P as c,x as d};
|
|
@@ -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{e as a}from"./chunk-VK5J556O.js";import{d as p}from"./chunk-TX46YMGI.js";import{d as n,m as s}from"./chunk-Z24SBRJK.js";import*as o from"path";var c=o.join(n,"data","pi"),j=o.join(n,"logs","sessions-pi");function l(r=c){return o.resolve(r)===o.resolve(c)?a():o.join(r,"auth.json")}function I(r){return o.join(r,"models.json")}function x(r,t=s){if(!p.test(r))throw new Error(`Invalid account id: ${r}`);return o.join(t,r)}import{existsSync as u,readFileSync as f}from"fs";function h(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let t=r;return typeof t.api=="string"&&Array.isArray(t.models)}function A(r){if(!u(r))return{};try{let t=JSON.parse(f(r,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t.providers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return{}}}function E(r){let t={};for(let[e,i]of Object.entries(A(r)))h(i)&&(t[e]=i);return t}export{h as a,A as b,E as c,c as d,j as e,l as f,I as g,x as h};
|