@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,5 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{e as m}from"./chunk-AVXDF7AG.js";import{e as x}from"./chunk-VBN2JSER.js";import{i as C}from"./chunk-Z24SBRJK.js";import{readFileSync as I}from"node:fs";import*as k from"node:path";var a=x("connections"),f=k.join(C,"connections.json"),p="subscription",A="plan",d=/^[a-zA-Z0-9_-]+$/;function u(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function c(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n){if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.length>0)}function E(n){if(!u(n))return;let t=Object.entries(n).filter(([,e])=>typeof e=="string");return t.length>0?Object.fromEntries(t):void 0}function K(n){return"api"in n}function h(n){return"type"in n&&n.type==="account"}function B(n){return n.filter(t=>t.backend==="claude"&&!h(t))}function G(n){return n.filter(t=>t.backend==="pi"&&!h(t))}function $(n,t){let e=c(n.key);if(!e||t===p)return null;let r={id:t,backend:"claude",label:c(n.label)??t,authStyle:n.authStyle==="bearer"?"bearer":"x-api-key",key:e,billing:n.billing==="subscription"?"subscription":"metered"},o=c(n.baseUrl);o&&(r.baseUrl=o);let i=S(n.models);return i&&(r.models=i),r}function j(n){return Array.isArray(n)?n.filter(t=>u(t)&&!!c(t.id)):[]}function _(n,t){let e=c(n.provider)??t,r=c(n.baseUrl);if(!d.test(e)||!r)return null;let o={id:e,backend:"pi",provider:e,baseUrl:r},i=c(n.label);i&&(o.label=i);let b=c(n.key);b&&(o.key=b);let y=c(n.api);if(!y)return o;let l={...o,api:y,models:j(n.models)},g=E(n.headers);return g&&(l.headers=g),u(n.compat)&&Object.keys(n.compat).length>0&&(l.compat=n.compat),l}function U(n,t){let e=c(n.label)??t,r=n.pending===!0?{pending:!0}:{};if(n.backend==="claude")return t===p?null:{id:t,backend:"claude",type:"account",label:e,...r};let o=c(n.provider);return!o||!d.test(o)||o===t?null:{id:t,backend:"pi",type:"account",label:e,provider:o,...r}}function L(n){if(!u(n))return null;let t=c(n.id);return!t||!d.test(t)?null:n.type==="account"&&(n.backend==="claude"||n.backend==="pi")?U(n,t):n.backend==="claude"?$(n,t):n.backend==="pi"?_(n,t):null}function s(n){return`${n.backend}:${n.id}`}function T(n){let t=u(n)&&Array.isArray(n.connections)?n.connections:[],e=new Set,r=[];for(let o of t){let i=L(o);if(!i||e.has(s(i))){a.warn("Ignoring an invalid or duplicate entry in connections.json");continue}e.add(s(i)),r.push(i)}return r}function O(n=f){let t;try{t=I(n,"utf8")}catch(e){return e.code!=="ENOENT"&&a.warn(`Could not read ${n}: ${e.message}`),[]}try{return T(JSON.parse(t))}catch(e){return a.warn(`Ignoring corrupt ${n}: ${e.message}`),[]}}function N(n,t=f){m(t,`${JSON.stringify({version:1,connections:n},null,2)}
|
|
5
|
+
`,{mode:384})}function J(n,t=f){let e=s(n),r=O(t),o=r.findIndex(i=>s(i)===e);o>=0?r[o]=n:r.push(n),N(r,t)}function v(n,t=f){let e=s(n),r=O(t),o=r.filter(i=>s(i)!==e);return o.length===r.length?!1:(N(o,t),!0)}function z(n){return n&&n!==p?n:null}function W(n){return n?n.length<12?"\u2022\u2022\u2022\u2022":`${n.slice(0,3)}\u2026${n.slice(-4)}`:null}function P(n,t){return n!=="claude"||typeof t!="string"||!t?null:t===A?p:t}function Y(n){if(!u(n)||!("mode"in n)||"connection"in n)return n;let{mode:t,...e}=n;return{...e,connection:P(e.backend,t)}}export{f as a,p as b,A as c,d,K as e,h as f,B as g,G as h,s as i,O as j,N as k,J as l,v as m,z as n,W as o,P as p,Y as q};
|
|
@@ -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{a as c,g as p}from"./chunk-T73GHMFB.js";import{readFileSync as l}from"fs";var a="openai",f=Object.freeze({supportsMidConvoEffort:!1,supportsLongCacheRetention:!1});function u(e){let t;try{t=JSON.parse(l(e,"utf8"))}catch{return new Map}if(!t||typeof t!="object")return new Map;let r=new Map;for(let[n,o]of Object.entries(t))(o?.type==="oauth"||o?.type==="api_key")&&r.set(n,o.type);return r}function v(e){return new Set([...u(e)].filter(([,t])=>t==="oauth").map(([t])=>t))}function C(e,t){return u(e).get(t)??null}import{existsSync as O,readFileSync as h,renameSync as S,unlinkSync as _,writeFileSync as I,mkdirSync as T,chmodSync as P}from"fs";import*as i from"path";var m="runtime-keys.json",R={deepseek:{supportsDeveloperRole:!1,maxTokensField:"max_completion_tokens"}};function j(e,t,r){if(c(t))return t;let o=e===a&&r.has(e)?f:{},d=t.compat&&typeof t.compat=="object"?t.compat:{},s={...R[e],...d,...o};return Object.keys(s).length>0?{...t,compat:s}:t}function w(e,t){let r={};for(let[n,o]of Object.entries(e.providers))r[n]=j(n,o,t);return r}function y(e,t){T(i.dirname(e),{recursive:!0});let r=`${e}.tmp.${process.pid}.${Date.now()}`;try{I(r,t,{encoding:"utf8",mode:384}),P(r,384),S(r,e)}catch(n){try{O(r)&&_(r)}catch{}throw n}}function G(e,t){let r=w(e,t.oauthProviders);y(p(t.agentDir),`${JSON.stringify({providers:r},null,2)}
|
|
5
|
+
`),y(i.join(t.agentDir,m),`${JSON.stringify(e.runtimeKeys,null,2)}
|
|
6
|
+
`)}function A(e){try{let t=JSON.parse(h(i.join(e,m),"utf8"));return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,r])=>typeof r=="string"&&r.length>0))}catch{return{}}}async function b(e,t){for(let[r,n]of Object.entries(A(t)))await e.setRuntimeApiKey(r,n)}export{v as a,C as b,G as c,b 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{j as E,k as C}from"./chunk-ETIBCA2S.js";import{a as u,h as d}from"./chunk-OE4KH3NJ.js";import{i as p}from"./chunk-QUXPMNFQ.js";import*as O from"node:http";function T(o,n,e,t={},s=183e4){let c=e===void 0?null:JSON.stringify(e),f=new URL(n);return new Promise((h,_)=>{let i=O.request(m(o,f,c,t,s),l=>{let a=[];l.on("data",b=>a.push(Buffer.from(b))),l.on("end",()=>h({status:l.statusCode??0,body:S(Buffer.concat(a).toString("utf8"))}))});i.on("error",_),i.on("timeout",()=>i.destroy(new Error(`Loopback request timed out after ${s}ms`))),c!==null&&i.write(c),i.end()})}function m(o,n,e,t,s){return{hostname:n.hostname,port:n.port,path:`${n.pathname}${n.search}`,method:o,headers:e===null?t:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(e),...t},timeout:s}}function S(o){if(!o)return null;try{return JSON.parse(o)}catch{return{_raw:o}}}function r(o){return o===void 0||o===""?null:o}function L(o){let n=o.CORTEX_BACKEND,e=r(o.CORTEX_MODEL);return n!=="claude"&&n!=="pi"||!e?null:{backend:n,model:e,provider:n==="pi"?r(o.CORTEX_PROVIDER):null,thinking:r(o.CORTEX_THINKING),connection:r(o.CORTEX_CONNECTION)}}function M(o=process.env){return{channel:r(o.SLACK_CHANNEL)??r(o.FEISHU_CHANNEL),sessionId:r(o.CORTEX_SESSION_ID),selection:L(o),project:r(o.CORTEX_PROJECT),backend:r(o.CORTEX_BACKEND),claudeModel:r(o.CORTEX_CLAUDE_MODEL),subagentPiModels:C(o.CORTEX_SUBAGENT_PI_MODELS),subagentClaudeModels:E(o.CORTEX_SUBAGENT_CLAUDE_MODELS),scheduleTaskId:r(o.CORTEX_SCHEDULE_TASK_ID),callbackSource:r(o.CORTEX_CALLBACK_SOURCE),webhookBaseUrl:p(o,null),webhookToken:o.CORTEX_WEBHOOK_TOKEN||"",slackBotToken:r(o.SLACK_BOT_TOKEN),toolAllowlist:d(o[u])}}function R(o){return{"x-cortex-token":o.webhookToken}}function w(o){return o.sessionId?o.sessionId:o.channel?.startsWith("web:")?o.channel.slice(4):null}var I=async(o,n)=>{let{body:e}=await T("POST",`${o.webhookBaseUrl}/webhook/board`,{sessionId:n,action:"status"},R(o));if(!e?.success)throw new Error(e?.error||"board status failed");let t=e.data;return t?{id:t.id,title:t.title,dir:t.dir??null}:null};async function N(o,n=I){let e={channel:o.channel,sessionId:o.sessionId,model:o.selection?.model??null,thinking:o.selection?.thinking??null,connection:o.selection?.connection??null,project:o.project,backend:o.backend,scheduleTaskId:o.scheduleTaskId,callbackSource:o.callbackSource},t=w(o);if(t)try{e.board=await n(o,t)}catch{}return e}function D(o,n){o.tool("cortex_context","Get current session identity, backend, model, thinking, connection, project, bound board and trigger context.",{},{readOnlyHint:!0},async()=>{try{let e=await N(n),{channel:t,...s}=e;return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){return{content:[{type:"text",text:`Failed to resolve context: ${e.message}`}],isError:!0}}})}export{T as a,M as b,R as c,w as d,N as e,D as f};
|
|
@@ -2,7 +2,7 @@ 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
4
|
import{a as We,c as g}from"./chunk-WHC7AYZD.js";var q=g(P=>{"use strict";var Qt=Symbol.for("yaml.alias"),Li=Symbol.for("yaml.document"),Ge=Symbol.for("yaml.map"),Ei=Symbol.for("yaml.pair"),Wt=Symbol.for("yaml.scalar"),He=Symbol.for("yaml.seq"),F=Symbol.for("yaml.node.type"),ga=s=>!!s&&typeof s=="object"&&s[F]===Qt,ya=s=>!!s&&typeof s=="object"&&s[F]===Li,ba=s=>!!s&&typeof s=="object"&&s[F]===Ge,Sa=s=>!!s&&typeof s=="object"&&s[F]===Ei,Ti=s=>!!s&&typeof s=="object"&&s[F]===Wt,wa=s=>!!s&&typeof s=="object"&&s[F]===He;function Ci(s){if(s&&typeof s=="object")switch(s[F]){case Ge:case He:return!0}return!1}function va(s){if(s&&typeof s=="object")switch(s[F]){case Qt:case Ge:case Wt:case He:return!0}return!1}var ka=s=>(Ti(s)||Ci(s))&&!!s.anchor;P.ALIAS=Qt;P.DOC=Li;P.MAP=Ge;P.NODE_TYPE=F;P.PAIR=Ei;P.SCALAR=Wt;P.SEQ=He;P.hasAnchor=ka;P.isAlias=ga;P.isCollection=Ci;P.isDocument=ya;P.isMap=ba;P.isNode=va;P.isPair=Sa;P.isScalar=Ti;P.isSeq=wa});var ye=g(Gt=>{"use strict";var I=q(),M=Symbol("break visit"),Ii=Symbol("skip children"),K=Symbol("remove node");function Xe(s,e){let t=Pi(e);I.isDocument(s)?ae(null,s.contents,t,Object.freeze([s]))===K&&(s.contents=null):ae(null,s,t,Object.freeze([]))}Xe.BREAK=M;Xe.SKIP=Ii;Xe.REMOVE=K;function ae(s,e,t,i){let n=Mi(s,e,t,i);if(I.isNode(n)||I.isPair(n))return _i(s,i,n),ae(s,n,t,i);if(typeof n!="symbol"){if(I.isCollection(e)){i=Object.freeze(i.concat(e));for(let r=0;r<e.items.length;++r){let a=ae(r,e.items[r],t,i);if(typeof a=="number")r=a-1;else{if(a===M)return M;a===K&&(e.items.splice(r,1),r-=1)}}}else if(I.isPair(e)){i=Object.freeze(i.concat(e));let r=ae("key",e.key,t,i);if(r===M)return M;r===K&&(e.key=null);let a=ae("value",e.value,t,i);if(a===M)return M;a===K&&(e.value=null)}}return n}async function xe(s,e){let t=Pi(e);I.isDocument(s)?await oe(null,s.contents,t,Object.freeze([s]))===K&&(s.contents=null):await oe(null,s,t,Object.freeze([]))}xe.BREAK=M;xe.SKIP=Ii;xe.REMOVE=K;async function oe(s,e,t,i){let n=await Mi(s,e,t,i);if(I.isNode(n)||I.isPair(n))return _i(s,i,n),oe(s,n,t,i);if(typeof n!="symbol"){if(I.isCollection(e)){i=Object.freeze(i.concat(e));for(let r=0;r<e.items.length;++r){let a=await oe(r,e.items[r],t,i);if(typeof a=="number")r=a-1;else{if(a===M)return M;a===K&&(e.items.splice(r,1),r-=1)}}}else if(I.isPair(e)){i=Object.freeze(i.concat(e));let r=await oe("key",e.key,t,i);if(r===M)return M;r===K&&(e.key=null);let a=await oe("value",e.value,t,i);if(a===M)return M;a===K&&(e.value=null)}}return n}function Pi(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}function Mi(s,e,t,i){if(typeof t=="function")return t(s,e,i);if(I.isMap(e))return t.Map?.(s,e,i);if(I.isSeq(e))return t.Seq?.(s,e,i);if(I.isPair(e))return t.Pair?.(s,e,i);if(I.isScalar(e))return t.Scalar?.(s,e,i);if(I.isAlias(e))return t.Alias?.(s,e,i)}function _i(s,e,t){let i=e[e.length-1];if(I.isCollection(i))i.items[s]=t;else if(I.isPair(i))s==="key"?i.key=t:i.value=t;else if(I.isDocument(i))i.contents=t;else{let n=I.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Gt.visit=Xe;Gt.visitAsync=xe});var Ht=g(Di=>{"use strict";var $i=q(),Na=ye(),Aa={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},qa=s=>s.replace(/[!,[\]{}]/g,e=>Aa[e]),be=class s{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},s.defaultYaml,e),this.tags=Object.assign({},s.defaultTags,t)}clone(){let e=new s(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new s(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:s.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},s.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:s.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},s.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[r,a]=i;return this.tags[r]=a,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[r]=i;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;{let a=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,a),!1}}default:return t(0,`Unknown directive ${n}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let a=e.slice(2,-1);return a==="!"||a==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),a)}let[,i,n]=e.match(/^(.*!)([^!]*)$/s);n||t(`The ${e} tag has no suffix`);let r=this.tags[i];if(r)try{return r+decodeURIComponent(n)}catch(a){return t(String(a)),null}return i==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,i]of Object.entries(this.tags))if(e.startsWith(i))return t+qa(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(e&&i.length>0&&$i.isNode(e.contents)){let r={};Na.visit(e.contents,(a,o)=>{$i.isNode(o)&&o.tag&&(r[o.tag]=!0)}),n=Object.keys(r)}else n=[];for(let[r,a]of i)r==="!!"&&a==="tag:yaml.org,2002:"||(!e||n.some(o=>o.startsWith(a)))&&t.push(`%TAG ${r} ${a}`);return t.join(`
|
|
5
|
-
`)}};be.defaultYaml={explicit:!1,version:"1.2"};be.defaultTags={"!!":"tag:yaml.org,2002:"};Di.Directives=be});var ze=g(Se=>{"use strict";var Bi=q(),Oa=ye();function La(s){if(/[\x00-\x19\s,[\]{}]/.test(s)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}function Ki(s){let e=new Set;return Oa.visit(s,{Value(t,i){i.anchor&&e.add(i.anchor)}}),e}function ji(s,e){for(let t=1;;++t){let i=`${s}${t}`;if(!e.has(i))return i}}function Ea(s,e){let t=[],i=new Map,n=null;return{onAnchor:r=>{t.push(r),n??(n=Ki(s));let a=ji(e,n);return n.add(a),a},setAnchors:()=>{for(let r of t){let a=i.get(r);if(typeof a=="object"&&a.anchor&&(Bi.isScalar(a.node)||Bi.isCollection(a.node)))a.node.anchor=a.anchor;else{let o=new Error("Failed to resolve repeated object (this should not happen)");throw o.source=r,o}}},sourceObjects:i}}Se.anchorIsValid=La;Se.anchorNames=Ki;Se.createNodeAnchors=Ea;Se.findNewAnchor=ji});var Xt=g(Fi=>{"use strict";function we(s,e,t,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let a=i[n],o=we(s,i,String(n),a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=we(s,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=we(s,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=we(s,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}return s.call(e,t,i)}Fi.applyReviver=we});var Y=g(Ui=>{"use strict";var Ta=q();function Ri(s,e,t){if(Array.isArray(s))return s.map((i,n)=>Ri(i,String(n),t));if(s&&typeof s.toJSON=="function"){if(!t||!Ta.hasAnchor(s))return s.toJSON(e,t);let i={aliasCount:0,count:1,res:void 0};t.anchors.set(s,i),t.onCreate=r=>{i.res=r,delete t.onCreate};let n=s.toJSON(e,t);return t.onCreate&&t.onCreate(n),n}return typeof s=="bigint"&&!t?.keep?Number(s):s}Ui.toJS=Ri});var Ze=g(Vi=>{"use strict";var Ca=Xt(),Yi=q(),Ia=Y(),xt=class{constructor(e){Object.defineProperty(this,Yi.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:i,onAnchor:n,reviver:r}={}){if(!Yi.isDocument(e))throw new TypeError("A document argument is required");let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},o=Ia.toJS(this,"",a);if(typeof n=="function")for(let{count:l,res:c}of a.anchors.values())n(c,l);return typeof r=="function"?Ca.applyReviver(r,{"":o},"",o):o}};Vi.NodeBase=xt});var ve=g(Ji=>{"use strict";var Pa=ze(),Ma=ye(),le=q(),_a=Ze(),$a=Y(),zt=class extends _a.NodeBase{constructor(e){super(le.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],Ma.visit(e,{Node:(r,a)=>{(le.isAlias(a)||le.hasAnchor(a))&&i.push(a)}}),t&&(t.aliasResolveCache=i));let n;for(let r of i){if(r===this)break;r.anchor===this.source&&(n=r)}
|
|
5
|
+
`)}};be.defaultYaml={explicit:!1,version:"1.2"};be.defaultTags={"!!":"tag:yaml.org,2002:"};Di.Directives=be});var ze=g(Se=>{"use strict";var Bi=q(),Oa=ye();function La(s){if(/[\x00-\x19\s,[\]{}]/.test(s)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}function Ki(s){let e=new Set;return Oa.visit(s,{Value(t,i){i.anchor&&e.add(i.anchor)}}),e}function ji(s,e){for(let t=1;;++t){let i=`${s}${t}`;if(!e.has(i))return i}}function Ea(s,e){let t=[],i=new Map,n=null;return{onAnchor:r=>{t.push(r),n??(n=Ki(s));let a=ji(e,n);return n.add(a),a},setAnchors:()=>{for(let r of t){let a=i.get(r);if(typeof a=="object"&&a.anchor&&(Bi.isScalar(a.node)||Bi.isCollection(a.node)))a.node.anchor=a.anchor;else{let o=new Error("Failed to resolve repeated object (this should not happen)");throw o.source=r,o}}},sourceObjects:i}}Se.anchorIsValid=La;Se.anchorNames=Ki;Se.createNodeAnchors=Ea;Se.findNewAnchor=ji});var Xt=g(Fi=>{"use strict";function we(s,e,t,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let a=i[n],o=we(s,i,String(n),a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=we(s,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=we(s,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=we(s,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}return s.call(e,t,i)}Fi.applyReviver=we});var Y=g(Ui=>{"use strict";var Ta=q();function Ri(s,e,t){if(Array.isArray(s))return s.map((i,n)=>Ri(i,String(n),t));if(s&&typeof s.toJSON=="function"){if(!t||!Ta.hasAnchor(s))return s.toJSON(e,t);let i={aliasCount:0,count:1,res:void 0};t.anchors.set(s,i),t.onCreate=r=>{i.res=r,delete t.onCreate};let n=s.toJSON(e,t);return t.onCreate&&t.onCreate(n),n}return typeof s=="bigint"&&!t?.keep?Number(s):s}Ui.toJS=Ri});var Ze=g(Vi=>{"use strict";var Ca=Xt(),Yi=q(),Ia=Y(),xt=class{constructor(e){Object.defineProperty(this,Yi.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:i,onAnchor:n,reviver:r}={}){if(!Yi.isDocument(e))throw new TypeError("A document argument is required");let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},o=Ia.toJS(this,"",a);if(typeof n=="function")for(let{count:l,res:c}of a.anchors.values())n(c,l);return typeof r=="function"?Ca.applyReviver(r,{"":o},"",o):o}};Vi.NodeBase=xt});var ve=g(Ji=>{"use strict";var Pa=ze(),Ma=ye(),le=q(),_a=Ze(),$a=Y(),zt=class extends _a.NodeBase{constructor(e){super(le.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],Ma.visit(e,{Node:(r,a)=>{(le.isAlias(a)||le.hasAnchor(a))&&i.push(a)}}),t&&(t.aliasResolveCache=i));let n;for(let r of i){if(r===this)break;r.anchor===this.source&&(n=r)}if(n&&t){let{anchors:r,doc:a,maxAliasCount:o}=t,l=r.get(n);if(l||($a.toJS(n,null,t),l=r.get(n)),l?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(o>=0&&(l.count+=1,l.aliasCount===0&&(l.aliasCount=et(a,n,r)),l.count*l.aliasCount>o)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}}return n}toJSON(e,t){if(!t)return{source:this.source};let i=this.resolve(t.doc,t);if(!i){let n=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(n)}return t.anchors.get(i).res}toString(e,t,i){let n=`*${this.source}`;if(e){if(Pa.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(e.implicitKey)return`${n} `}return n}};function et(s,e,t){if(le.isAlias(e)){let i=e.resolve(s),n=t&&i&&t.get(i);return n?n.count*n.aliasCount:0}else if(le.isCollection(e)){let i=0;for(let n of e.items){let r=et(s,n,t);r>i&&(i=r)}return i}else if(le.isPair(e)){let i=et(s,e.key,t),n=et(s,e.value,t);return Math.max(i,n)}return 1}Ji.Alias=zt});var E=g(Zt=>{"use strict";var Da=q(),Ba=Ze(),Ka=Y(),ja=s=>!s||typeof s!="function"&&typeof s!="object",V=class extends Ba.NodeBase{constructor(e){super(Da.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Ka.toJS(this.value,e,t)}toString(){return String(this.value)}};V.BLOCK_FOLDED="BLOCK_FOLDED";V.BLOCK_LITERAL="BLOCK_LITERAL";V.PLAIN="PLAIN";V.QUOTE_DOUBLE="QUOTE_DOUBLE";V.QUOTE_SINGLE="QUOTE_SINGLE";Zt.Scalar=V;Zt.isScalarValue=ja});var ke=g(Wi=>{"use strict";var Fa=ve(),Z=q(),Qi=E(),Ra="tag:yaml.org,2002:";function Ua(s,e,t){if(e){let i=t.filter(r=>r.tag===e),n=i.find(r=>!r.format)??i[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return t.find(i=>i.identify?.(s)&&!i.format)}function Ya(s,e,t){if(Z.isDocument(s)&&(s=s.contents),Z.isNode(s))return s;if(Z.isPair(s)){let f=t.schema[Z.MAP].createNode?.(t.schema,null,t);return f.items.push(s),f}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:r,schema:a,sourceObjects:o}=t,l;if(i&&s&&typeof s=="object"){if(l=o.get(s),l)return l.anchor??(l.anchor=n(s)),new Fa.Alias(l.anchor);l={anchor:null,node:null},o.set(s,l)}e?.startsWith("!!")&&(e=Ra+e.slice(2));let c=Ua(s,e,a.tags);if(!c){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){let f=new Qi.Scalar(s);return l&&(l.node=f),f}c=s instanceof Map?a[Z.MAP]:Symbol.iterator in Object(s)?a[Z.SEQ]:a[Z.MAP]}r&&(r(c),delete t.onTagObj);let d=c?.createNode?c.createNode(t.schema,s,t):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(t.schema,s,t):new Qi.Scalar(s);return e?d.tag=e:c.default||(d.tag=c.tag),l&&(l.node=d),d}Wi.createNode=Ya});var st=g(tt=>{"use strict";var Va=ke(),j=q(),Ja=Ze();function es(s,e,t){let i=t;for(let n=e.length-1;n>=0;--n){let r=e[n];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){let a=[];a[r]=i,i=a}else i=new Map([[r,i]])}return Va.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:s,sourceObjects:new Map})}var Gi=s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,ts=class extends Ja.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(i=>j.isNode(i)||j.isPair(i)?i.clone(e):i),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Gi(e))this.add(t);else{let[i,...n]=e,r=this.get(i,!0);if(j.isCollection(r))r.addIn(n,t);else if(r===void 0&&this.schema)this.set(i,es(this.schema,n,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(e){let[t,...i]=e;if(i.length===0)return this.delete(t);let n=this.get(t,!0);if(j.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${i}`)}getIn(e,t){let[i,...n]=e,r=this.get(i,!0);return n.length===0?!t&&j.isScalar(r)?r.value:r:j.isCollection(r)?r.getIn(n,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!j.isPair(t))return!1;let i=t.value;return i==null||e&&j.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[t,...i]=e;if(i.length===0)return this.has(t);let n=this.get(t,!0);return j.isCollection(n)?n.hasIn(i):!1}setIn(e,t){let[i,...n]=e;if(n.length===0)this.set(i,t);else{let r=this.get(i,!0);if(j.isCollection(r))r.setIn(n,t);else if(r===void 0&&this.schema)this.set(i,es(this.schema,n,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};tt.Collection=ts;tt.collectionFromPath=es;tt.isEmptyPath=Gi});var Ne=g(it=>{"use strict";var Qa=s=>s.replace(/^(?!$)(?: $)?/gm,"#");function ss(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}var Wa=(s,e,t)=>s.endsWith(`
|
|
6
6
|
`)?ss(t,e):t.includes(`
|
|
7
7
|
`)?`
|
|
8
8
|
`+ss(t,e):(s.endsWith(" ")?"":" ")+t;it.indentComment=ss;it.lineComment=Wa;it.stringifyComment=Qa});var Xi=g(Ae=>{"use strict";var Ga="flow",is="block",nt="quoted";function Ha(s,e,t="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:r=20,onFold:a,onOverflow:o}={}){if(!n||n<0)return s;n<r&&(r=0);let l=Math.max(1+r,1+n-e.length);if(s.length<=l)return s;let c=[],d={},f=n-e.length;typeof i=="number"&&(i>n-Math.max(2,r)?c.push(0):f=n-i);let u,m,y=!1,h=-1,p=-1,S=-1;t===is&&(h=Hi(s,h,e.length),h!==-1&&(f=h+l));for(let v;v=s[h+=1];){if(t===nt&&v==="\\"){switch(p=h,s[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}S=h}if(v===`
|
|
@@ -84,11 +84,9 @@ ${c}
|
|
|
84
84
|
`+a[h][0].slice(l);f[f.length-1]!==`
|
|
85
85
|
`&&(f+=`
|
|
86
86
|
`);break;default:f+=`
|
|
87
|
-
`}let y=i+n.length+e.source.length;return{value:f,type:r,comment:n.comment,range:[i,y,y]}}function Ec({offset:s,props:e},t,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[0],r=n[0],a=0,o="",l=-1;for(let u=1;u<n.length;++u){let m=n[u];if(!o&&(m==="-"||m==="+"))o=m;else{let y=Number(m);!a&&y?a=y:l===-1&&(l=s+u)}}l!==-1&&i(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let c=!1,d="",f=n.length;for(let u=1;u<e.length;++u){let m=e[u];switch(m.type){case"space":c=!0;case"newline":f+=m.source.length;break;case"comment":t&&!c&&i(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=m.source.length,d=m.source.substring(1);break;case"error":i(m,"UNEXPECTED_TOKEN",m.message),f+=m.source.length;break;default:{let y=`Unexpected token in block scalar header: ${m.type}`;i(m,"UNEXPECTED_TOKEN",y);let h=m.source;h&&typeof h=="string"&&(f+=h.length)}}}return{mode:r,indent:a,chomp:o,comment:d,length:f}}function Tc(s){let e=s.split(/\n( *)/),t=e[0],i=t.match(/^( *)/),r=[i?.[1]?[i[1],t.slice(i[1].length)]:["",t]];for(let a=1;a<e.length;a+=2)r.push([e[a],e[a+1]]);return r}Cr.resolveBlockScalar=Lc});var ai=g(Pr=>{"use strict";var ri=E(),Cc=me();function Ic(s,e,t){let{offset:i,type:n,source:r,end:a}=s,o,l,c=(u,m,y)=>t(i+u,m,y);switch(n){case"scalar":o=ri.Scalar.PLAIN,l=Pc(r,c);break;case"single-quoted-scalar":o=ri.Scalar.QUOTE_SINGLE,l=Mc(r,c);break;case"double-quoted-scalar":o=ri.Scalar.QUOTE_DOUBLE,l=_c(r,c);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+r.length,i+r.length]}}let d=i+r.length,f=Cc.resolveEnd(a,d,e,t);return{value:l,type:o,comment:f.comment,range:[i,d,f.offset]}}function Pc(s,e){let t="";switch(s[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${s[0]}`;break}case"@":case"`":{t=`reserved character ${s[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Ir(s)}function Mc(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),Ir(s.slice(1,-1)).replace(/''/g,"'")}function Ir(s){let e,t;try{
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
`?n+=r:r=`
|
|
91
|
-
`:(n+=r+i[1],r=" "),a=t.lastIndex;let o=/[ \t]*(.*)/sy;return o.lastIndex=a,i=o.exec(s),n+r+(i?.[1]??"")}function _c(s,e){let t="";for(let i=1;i<s.length-1;++i){let n=s[i];if(!(n==="\r"&&s[i+1]===`
|
|
87
|
+
`}let y=i+n.length+e.source.length;return{value:f,type:r,comment:n.comment,range:[i,y,y]}}function Ec({offset:s,props:e},t,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[0],r=n[0],a=0,o="",l=-1;for(let u=1;u<n.length;++u){let m=n[u];if(!o&&(m==="-"||m==="+"))o=m;else{let y=Number(m);!a&&y?a=y:l===-1&&(l=s+u)}}l!==-1&&i(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let c=!1,d="",f=n.length;for(let u=1;u<e.length;++u){let m=e[u];switch(m.type){case"space":c=!0;case"newline":f+=m.source.length;break;case"comment":t&&!c&&i(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=m.source.length,d=m.source.substring(1);break;case"error":i(m,"UNEXPECTED_TOKEN",m.message),f+=m.source.length;break;default:{let y=`Unexpected token in block scalar header: ${m.type}`;i(m,"UNEXPECTED_TOKEN",y);let h=m.source;h&&typeof h=="string"&&(f+=h.length)}}}return{mode:r,indent:a,chomp:o,comment:d,length:f}}function Tc(s){let e=s.split(/\n( *)/),t=e[0],i=t.match(/^( *)/),r=[i?.[1]?[i[1],t.slice(i[1].length)]:["",t]];for(let a=1;a<e.length;a+=2)r.push([e[a],e[a+1]]);return r}Cr.resolveBlockScalar=Lc});var ai=g(Pr=>{"use strict";var ri=E(),Cc=me();function Ic(s,e,t){let{offset:i,type:n,source:r,end:a}=s,o,l,c=(u,m,y)=>t(i+u,m,y);switch(n){case"scalar":o=ri.Scalar.PLAIN,l=Pc(r,c);break;case"single-quoted-scalar":o=ri.Scalar.QUOTE_SINGLE,l=Mc(r,c);break;case"double-quoted-scalar":o=ri.Scalar.QUOTE_DOUBLE,l=_c(r,c);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+r.length,i+r.length]}}let d=i+r.length,f=Cc.resolveEnd(a,d,e,t);return{value:l,type:o,comment:f.comment,range:[i,d,f.offset]}}function Pc(s,e){let t="";switch(s[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${s[0]}`;break}case"@":case"`":{t=`reserved character ${s[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Ir(s)}function Mc(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),Ir(s.slice(1,-1)).replace(/''/g,"'")}function Ir(s){let e=/(.*?)\r?\n/sy,t=e.exec(s);if(!t)return s;let i,n;try{i=new RegExp("(?<![ ])[ ]+$"),n=new RegExp("^[ ]+|(?<![ ])[ ]+$","g")}catch{i=/[ \t]+$/,n=/^[ \t]+|[ \t]+$/g}let r=t[1].replace(i,""),a=" ",o=e.lastIndex;for(;t=e.exec(s);){let c=t[1].replace(n,"");c===""?a===`
|
|
88
|
+
`?r+=a:a=`
|
|
89
|
+
`:(r+=a+c,a=" "),o=e.lastIndex}let l=/[ \t]*(.*)/sy;return l.lastIndex=o,t=l.exec(s),r+a+(t?.[1]??"")}function _c(s,e){let t="";for(let i=1;i<s.length-1;++i){let n=s[i];if(!(n==="\r"&&s[i+1]===`
|
|
92
90
|
`))if(n===`
|
|
93
91
|
`){let{fold:r,offset:a}=$c(s,i);t+=r,i=a}else if(n==="\\"){let r=s[++i],a=Dc[r];if(a)t+=a;else if(r===`
|
|
94
92
|
`)for(r=s[i+1];r===" "||r===" ";)r=s[++i+1];else if(r==="\r"&&s[i+1]===`
|
|
@@ -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{e as a}from"./chunk-3CPIMAYX.js";import{e as k}from"./chunk-VBN2JSER.js";import{k as R}from"./chunk-Z24SBRJK.js";import{spawn as Tt}from"node:child_process";import{randomUUID as V}from"node:crypto";var S=1800*1e3,F=200,Z=8,Q="***",tt=k("login-flow"),I=class extends Error{code;name="LoginFlowError";constructor(e,n,r){super(n,r===void 0?void 0:{cause:r}),this.code=e}};function b(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="LoginFlowError"&&typeof e.message=="string"&&typeof e.code=="string"}function et(t){let n=(t instanceof Error?t.message:typeof t=="string"?t:"").split(`
|
|
5
|
+
`).map(r=>r.trim()).find(Boolean)??"";return n.length>F?`${n.slice(0,F-1)}\u2026`:n}function nt(t,e){let n=et(e),r=t.replace(/[.。]\s*$/u,"");return!n||n===t||n===r?t:a("ux.auth.failureDetail",{message:r,detail:n})}var rt=new Set(["done","failed","cancelled"]),l=new Map,d=new Map;function y(t){return`${t.backend}\0${t.provider}\0${t.connection??""}`}function Dt(t){let e=d.get(y(t)),n=e?T(e):null;return!!n&&!p(n)}function f(t){let e=new Error(t);return e.name="AbortError",e}function p(t){return rt.has(t.state.step)}function ot(t){if(!t)return null;let e=t.options?.map(n=>({...n}));return e?{...t,options:e}:{...t}}function it(t){return t?t.kind!=="info"||!t.links?{...t}:{...t,links:t.links.map(e=>({...e}))}:null}function D(t){return t?{...t}:null}function c(t){t.state.revision+=1}function _(t){return{...t.state,pendingPrompt:ot(t.state.pendingPrompt),notice:it(t.state.notice),outcome:D(t.state.outcome)}}function E(t){d.get(t.pairKey)===t.state.flowId&&d.delete(t.pairKey)}function A(t){let e=t.pending;return e?(e.signal?.removeEventListener("abort",e.onAbort),t.pending=null,t.state.pendingPrompt=null,c(t),e):null}function N(t,e){t.controller.signal.aborted||t.controller.abort(f(e))}function U(t){l.get(t.state.flowId)===t&&(l.delete(t.state.flowId),E(t),clearTimeout(t.timer),t.secrets.clear(),p(t)||N(t,"Login flow expired."),A(t)?.reject(f("Login flow expired.")))}function T(t){let e=l.get(t);return e?Date.now()<e.expiresAtMs?e:(U(e),null):null}function st(t){let e=T(t);if(!e)throw new Error(a("ux.auth.flowNotFound"));return e}function C(t){let e=st(t);if(p(e))throw new Error(a("ux.auth.flowNotActive"));return e}function at(t,e){let n={id:e,kind:t.type,message:t.message};return t.type==="select"?n.options=t.options.map(r=>({...r})):t.placeholder&&(n.placeholder=t.placeholder),n}function ut(t,e){t.pending===e&&(A(t),t.state.step==="prompt"&&(t.state.step="running"),e.reject(f("Authentication prompt aborted.")))}async function ct(t,e){let n=C(t);if(n.pending)throw new Error("Login flow already has a pending prompt.");if(e.signal?.aborted)throw f("Authentication prompt aborted.");return c(n),n.state.step="prompt",n.state.pendingPrompt=at(e,n.state.revision),new Promise((r,o)=>{let i={resolve:r,reject:o,signal:e.signal};i.onAbort=()=>ut(n,i),n.pending=i,e.signal?.addEventListener("abort",i.onAbort,{once:!0})})}function lt(t){if(t.type==="info"){let e=t.links?.map(n=>({...n}));return e?{kind:"info",message:t.message,links:e}:{kind:"info",message:t.message}}return t.type==="auth_url"?{kind:"auth_url",url:t.url,instructions:t.instructions}:t.type==="device_code"?{kind:"device_code",userCode:t.userCode,verificationUri:t.verificationUri,intervalSeconds:t.intervalSeconds,expiresInSeconds:t.expiresInSeconds}:{kind:"progress",message:t.message}}function dt(t){return{signal:t.controller.signal,prompt:e=>ct(t.state.flowId,e),notify:e=>{let n=C(t.state.flowId);n.state.notice=lt(e),c(n)}}}function H(t){return l.get(t.state.flowId)===t&&!p(t)}var w=new Set;function Nt(t){return w.add(t),()=>{w.delete(t)}}function ft(t){for(let e of w)try{e(t)}catch{}}function pt(t,e){H(t)&&(t.state.step="done",t.state.pendingPrompt=null,c(t),t.state.outcome=D(e),t.state.error=null,t.state.errorCode=null,t.secrets.clear(),E(t),ft({backend:t.state.backend,provider:e.provider||t.state.provider||"",connection:t.state.connection,authType:e.authType}))}function m(t,e){return[...e].filter(r=>r.length>=Z).sort((r,o)=>o.length-r.length).reduce((r,o)=>r.split(o).join(Q),t)}function ht(t,e,n){e!=="secret"&&e!=="manual_code"||(t.secrets.add(n),t.secrets.add(n.trim()))}function gt(t){let e=b(t)&&t.cause!==void 0?t.cause:t;return e instanceof Error?b(e)?e.message:e.stack??e.message:String(e)}function mt(t,e){if(!H(t))return;let n=b(e)?e:null,r=`login ${t.state.backend}/${t.state.provider} failed (${n?.code??"unexpected"}):`;tt.warn(r,m(gt(e),t.secrets)),t.state.step="failed",t.state.pendingPrompt=null,c(t),t.state.outcome=null;let o=n?.message??nt(a("ux.auth.loginFailed"),e);t.state.error=m(o,t.secrets),t.state.errorCode=n?.code??null,t.secrets.clear(),E(t)}function _t(t,e){Promise.resolve().then(()=>e(dt(t))).then(n=>pt(t,n),n=>mt(t,n))}function Et(t){let e=d.get(y(t));if(!e)return null;let n=T(e);return!n||p(n)?null:n}function j(t){let e=A(t);t.state.step="cancelled",c(t),t.state.outcome=null,t.state.error=null,t.state.errorCode=null,t.secrets.clear(),E(t),N(t,"Login flow cancelled."),e?.reject(f("Login flow cancelled."))}function At(t){let e=Date.now(),o={state:{flowId:V(),revision:0,backend:t.backend,provider:t.provider,connection:t.connection??null,authType:t.authType,step:"running",pendingPrompt:null,notice:null,channel:t.channel,sessionId:t.sessionId,createdAt:new Date(e).toISOString(),expiresAt:new Date(e+S).toISOString(),outcome:null,error:null,errorCode:null},pairKey:y(t),expiresAtMs:e+S,controller:new AbortController,pending:null,secrets:new Set};return o.timer=setTimeout(()=>U(o),S),o.timer.unref(),o}async function Ut(t,e){let n=Et(t);n&&j(n);let r=At(t);return l.set(r.state.flowId,r),d.set(r.pairKey,r.state.flowId),_t(r,e),_(r)}async function Ht(t,e,n){let r=C(t);if(n!==void 0&&r.state.pendingPrompt&&r.state.pendingPrompt.id!==n)throw new I("stale_prompt",a("ux.auth.flowNotWaiting"));let o=r.state.pendingPrompt?.kind,i=A(r);if(!i)throw new Error(a("ux.auth.flowNotWaiting"));return o&&ht(r,o,e),r.state.step="running",i.resolve(e),_(r)}async function jt(t){let e=C(t);return j(e),_(e)}function Gt(t){let e=T(t);return e?_(e):null}var Ct=1800*1e3,G=64*1024,$=200,z="Paste code here if prompted >",B=/https:\/\/claude\.com\/cai\/oauth\/authorize\?[^\s\x1b]+/,St=/\x1B\[[0-?]*[ -/]*[@-~]/g,It=/\x1B\][^\x07]*(?:\x07|\x1B\\)/g,bt=["HOME","PATH","SHELL","USER","LOGNAME","LANG","LC_ALL","LC_CTYPE","TERM","TZ","TMPDIR","TMP","TEMP","XDG_CONFIG_HOME","XDG_CACHE_HOME","XDG_DATA_HOME","HTTPS_PROXY","HTTP_PROXY","NO_PROXY","https_proxy","http_proxy","no_proxy","SSL_CERT_FILE","SSL_CERT_DIR","NODE_EXTRA_CA_CERTS"],L=class extends Error{code;name="ClaudeAuthCliError";constructor(e,n){super(n),this.code=e}};function u(t,e){return new L(t,e)}function X(t,e){return e?`${t.replace(/\.$/,"")}: ${e}`:t}function wt(t=process.env,e=R){let n={BROWSER:"true",CLAUDE_CONFIG_DIR:e};for(let r of bt)t[r]!==void 0&&(n[r]=t[r]);return n}function x(t,e){return(e.spawn??Tt)(e.executable??"claude",t,{env:wt(e.env,e.configDir),stdio:["pipe","pipe","pipe"]})}function h(t,e=""){return u(t,X({claude_auth_login_failed:"Claude authentication login failed.",claude_auth_logout_failed:"Claude authentication logout failed.",claude_auth_status_failed:"Claude authentication status check failed."}[t]??"Claude authentication command failed.",e))}var P=class{child;options;resolve;reject;settled=!1;timer;onAbort=()=>this.stop(u("claude_auth_cancelled","Claude authentication was cancelled."));constructor(e,n,r,o,i){this.child=e,this.options=r,this.resolve=o,this.reject=i,this.timer=setTimeout(()=>this.stop(u("claude_auth_timeout","Claude authentication timed out.")),n.timeoutMs??Ct),r.signal?.addEventListener("abort",this.onAbort,{once:!0}),e.once("error",s=>this.finish(h(r.failureCode,s.message))),e.once("close",s=>this.finish(s===0?void 0:h(r.failureCode,W(r.output)))),r.signal?.aborted&&this.onAbort()}cleanup(){clearTimeout(this.timer),this.options.signal?.removeEventListener("abort",this.onAbort)}finish(e){this.settled||(this.settled=!0,this.cleanup(),e?this.reject(e):this.resolve())}stop(e){if(!this.settled){this.settled=!0,this.cleanup(),this.options.onStop?.(e);try{this.child.kill("SIGTERM")}catch{}this.reject(e)}}};function M(t,e,n){return new Promise((r,o)=>{new P(t,e,n,r,o)})}function v(t,e){let n=t+String(e);return n.length<=G?n:n.slice(-G)}function K(t){return t.replace(It,"").replace(St,"")}function yt(t){let e=t.trim();return e&&!/[\r\n]/.test(e)?e:null}function O(t){let e={text:"",secrets:[]},n=r=>{e.text=v(e.text,r)};return t.stdout.on("data",n),t.stderr.on("data",n),e}function W(t){let e=K(t.text).split(z).join(`
|
|
6
|
+
`).split(/\r\n|\r|\n/).map(r=>r.trim()).filter(r=>r&&!B.test(r)),n=m(e.at(-1)??"",t.secrets);return n.length>$?`${n.slice(0,$-1)}\u2026`:n}async function Lt(t,e){let n=x(["auth","status","--json"],t),r="";n.stdout.on("data",i=>{r=v(r,i)});let o=O(n);return await M(n,t,{signal:e,failureCode:"claude_auth_status_failed",output:o}),r}function Pt(t){try{let e=JSON.parse(t.trim());if(typeof e.loggedIn!="boolean")throw new Error("missing loggedIn");return{loggedIn:e.loggedIn,authMethod:typeof e.authMethod=="string"?e.authMethod:null,apiProvider:typeof e.apiProvider=="string"?e.apiProvider:null}}catch{throw u("claude_auth_status_invalid","Claude authentication status was invalid.")}}async function Y(t={},e){return Pt(await Lt(t,e))}function q(t,e,n){if(!t.settled){if(t.settled=!0,n)try{t.child.kill("SIGTERM")}catch{}t.reject(e)}}function xt(t,e){t.settled=!0,t.output.secrets.push(e);try{t.child.stdin.write(`${e}
|
|
7
|
+
`),t.options.onCodeSubmitted?.(),t.resolve()}catch{try{t.child.kill("SIGTERM")}catch{}t.reject(h("claude_auth_login_failed"))}}async function Mt(t,e){try{let n=yt(await t.options.onAuthorization(e));if(!n)throw h("claude_auth_login_failed");if(t.settled||t.options.signal?.aborted)return;xt(t,n)}catch{q(t,h("claude_auth_login_failed"),!0)}}function vt(t,e){t.buffer=v(t.buffer,e);let n=K(t.buffer),r=n.match(B)?.[0];t.started||!r||!n.includes(z)||(t.started=!0,Mt(t,r))}function Ot(t,e,n,r){return new Promise((o,i)=>{let s={child:t,options:e,output:n,buffer:"",started:!1,settled:!1,resolve:o,reject:i},g=J=>vt(s,J);t.stdout.on("data",g),t.stderr.on("data",g),t.once("close",()=>q(s,r()??u("claude_auth_login_protocol",X("Claude authentication did not complete browser authorization.",W(n))),!1))})}async function Kt(t,e={}){let n=x(["auth","login","--claudeai"],e),r=O(n),o=null,i=Ot(n,t,r,()=>o);await Promise.all([i,M(n,e,{signal:t.signal,failureCode:"claude_auth_login_failed",output:r,onStop:g=>{o=g}})]);let s=await Y(e,t.signal);if(!s.loggedIn)throw u("claude_auth_not_logged_in","Claude Code did not persist the login.");return s}async function Wt(t={}){let e=x(["auth","logout"],t),n=O(e);if(await M(e,t,{failureCode:"claude_auth_logout_failed",output:n}),(await Y(t)).loggedIn)throw u("claude_auth_still_logged_in","Claude Code remained logged in after logout.")}export{S as a,I as b,b as c,nt as d,Dt as e,Nt as f,m as g,gt as h,Ut as i,Ht as j,jt as k,Gt as l,L as m,wt as n,Y as o,Kt as p,Wt as q};
|
|
@@ -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
|
+
function r(n){let t=n.split(".")[1];if(!t)return null;try{return JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{return null}}function i(n){let t=[n];for(;t.length>0;){let e=t.shift();if(!e||typeof e!="object")continue;let o=e;if(typeof o.chatgpt_account_id=="string")return o.chatgpt_account_id;t.push(...Object.values(o))}}function c(n,t){let e=[n];for(;e.length>0;){let o=e.shift();if(!o||typeof o!="object")continue;let u=o;if(typeof u[t]=="string")return u[t];e.push(...Object.values(u))}return null}function a(n){let t=r(n);return{email:c(t,"email"),plan:c(t,"chatgpt_plan_type")}}export{r as a,i as b,a as c};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
2
|
const require = __cortexCreateRequire(import.meta.url);
|
|
3
3
|
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{
|
|
4
|
+
import{z as c}from"./chunk-Z24SBRJK.js";import o from"node:fs";import g from"node:path";function S(t=process.env){return t.DEBUG==="1"}function _(t=process.env){let e=Number(t.CORTEX_DEBUG_TOOL_WARNING_CHARS);return Number.isSafeInteger(e)&&e>0?e:1e4}function N(t,e=process.env){return t>_(e)}process.stderr.on("error",()=>{});process.stdout.on("error",()=>{});var d=14,m=100*1024*1024,p=2,i={consoleToStderr:!1,files:!0,console:!0};function k(t){let e=i;return i=t,()=>{i=e}}var D="",n=null,y="";function R(){let t=new Date;return[t.getFullYear(),String(t.getMonth()+1).padStart(2,"0"),String(t.getDate()).padStart(2,"0")].join("")}function T(){let t=R();return(t!==D||!n)&&(n?.end(),o.mkdirSync(c,{recursive:!0}),D=t,n=o.createWriteStream(g.join(c,`server-${t}.log`),{flags:"a"}),y!==t&&(y=t,O())),n.bytesWritten>=m&&(n.end(),n=h(t)),n}function h(t){let e=g.join(c,`server-${t}`);for(let r=p;r>=1;r--){let u=`${e}.${r}.log`,s=`${e}.${r+1}.log`;try{if(r===p)try{o.unlinkSync(s)}catch{}o.renameSync(u,s)}catch{}}try{o.renameSync(`${e}.log`,`${e}.1.log`)}catch{}return o.createWriteStream(`${e}.log`,{flags:"a"})}function O(){try{let t=Date.now()-d*864e5;for(let e of o.readdirSync(c)){let r=e.match(/^server-(\d{4})(\d{2})(\d{2})\.log$/);if(!r)continue;new Date(+r[1],+r[2]-1,+r[3]).getTime()<t&&o.unlinkSync(g.join(c,e))}}catch{}}function A(t){if(t instanceof Error)return t.stack||t.message;if(typeof t=="object"&&t!==null)try{return JSON.stringify(t)}catch{return String(t)}return String(t)}var a=null,l=!1;function C(t){a=t}function L(t,e){if(!(!a||l)){l=!0;try{a(t,e)}catch{}finally{l=!1}}}function $(t,e,r){if(i.consoleToStderr)return console.error(e,...r);if(t==="ERROR")return console.error(e,...r);if(t==="WARN")return console.warn(e,...r);if(t==="DEBUG")return console.debug(e,...r);console.log(e,...r)}function f(t,e,r){let u=new Date().toLocaleTimeString("en-GB",{hour12:!1}),s=`[${e} ${u}]`;if(i.console!==!1)try{$(t,s,r)}catch{}if(!i.files)return;let E=`${s} ${t} ${r.map(A).join(" ")}
|
|
5
5
|
`;try{T().write(E)}catch{}}function U(t){return{info:(...e)=>f("INFO",t,e),warn:(...e)=>f("WARN",t,e),error:(...e)=>{f("ERROR",t,e),L(t,e)},debug:(...e)=>{S()&&f("DEBUG",t,e)}}}process.on("exit",()=>{n?.end()});export{S as a,N as b,k as c,C as d,U as e};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{b as _}from"./chunk-QEL6CMLE.js";import{a as x}from"./chunk-IA6IODY3.js";import{A as D,g as T,j as S}from"./chunk-RF4JLYBX.js";import{c as w}from"./chunk-MGYYSX7Y.js";import{q as g}from"./chunk-TX46YMGI.js";import{j as d}from"./chunk-Z24SBRJK.js";function b(e){if(!e||typeof e=="object")return!1;let t=typeof e=="string"?e:String(e);return!(!t.trim()||t==="null"||t==="undefined")}function Q(e,t){return e.some(n=>n.status==="running"&&n.kind==="scheduled"&&n.scheduleTaskId===t)}var E=["interval","daily","weekly","once"],A={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6},a=class extends Error{field;value;constructor(t,n,r){super(n),this.field=t,this.value=r,this.name="ScheduleSpecError"}},N={s:1e3,m:6e4,h:36e5,d:864e5};function $(e){let t=e?.trim().match(/^(\d+(?:\.\d+)?)(s|m|h|d)$/i);return t?Math.round(parseFloat(t[1])*N[t[2].toLowerCase()]):null}function l(e,t){if(e===void 0||e==="")throw new a(t,`${t} is required (e.g. 30m, 2h, 1d)`);let n=typeof e=="number"?Math.round(e):$(e);if(n===null||!Number.isFinite(n)||n<=0)throw new a(t,`invalid ${t}: '${e}' (use 30s, 5m, 2h, 1d)`,e);return n}function f(e){if(!e)throw new a("time","time is required (HH:MM, 24-hour)");let t=e.trim().match(/^(\d{2}):(\d{2})$/);if(!t||Number(t[1])>23||Number(t[2])>59)throw new a("time",`invalid time: '${e}' (use HH:MM, 24-hour)`,e);return t[0]}function I(e){if(e===void 0||e==="")throw new a("dayOfWeek","dayOfWeek is required (sun..sat or 0-6)");let t=typeof e=="string"?e.trim().toLowerCase():e,n=typeof t=="number"||/^\d+$/.test(t)?Number(t):A[t];if(!Number.isInteger(n)||n<0||n>6)throw new a("dayOfWeek",`invalid dayOfWeek: '${e}' (use sun..sat or 0-6)`,e);return n}function O(e){let t=typeof e=="string"?e.trim():"";if(!b(t))throw new a("message","message must be a non-empty prompt",e);return t}function L(e){return E.includes(e)}var H={interval:e=>({type:"interval",intervalMs:l(e.interval,"interval")}),daily:e=>({type:"daily",time:f(e.time)}),weekly:e=>({type:"weekly",dayOfWeek:I(e.dayOfWeek),time:f(e.time)}),once:e=>({type:"once",delayMs:l(e.delay,"delay")})};function te(e){if(!L(e.type))throw new a("type",`invalid type: '${e.type}' (valid: ${E.join(", ")})`,e.type);let t=H[e.type](e),n=e.preCheck?.trim();return{...t,message:O(e.message),projectId:e.projectId?.trim()||"general",selection:e.selection?{...e.selection}:void 0,...n?{preCheck:n}:{}}}var v=new Set(["memory-index-regen"]),F=["message","projectId","selection","dispatchType","preCheck"],W={interval:["intervalMs"],daily:["time"],weekly:["dayOfWeek","time"],once:["runAt"]};function U(e,t){let n=Object.keys(t);if(n.length===0)throw new a("patch","nothing to update \u2014 provide at least one field");let r=new Set([...F,...W[e]]),s=n.filter(i=>!r.has(i));if(s.length)throw new a("patch",`invalid fields for ${e}: ${s.join(", ")}`,s)}function B(e){if(e.dispatchType&&v.has(e.dispatchType))throw new a("dispatchType",`built-in job dispatch type cannot be scheduled: ${e.dispatchType}`);if("intervalMs"in e&&l(e.intervalMs,"intervalMs"),"dayOfWeek"in e&&I(e.dayOfWeek),"runAt"in e&&!(Number.isFinite(e.runAt)&&e.runAt>0))throw new a("runAt","runAt must be a positive epoch ms",e.runAt)}function M(e,t){U(e,t),B(t);let n={...t};return"message"in t&&(n.message=O(t.message)),"time"in t&&(n.time=f(t.time)),n}function V(e,t){let[n,r]=e.split(":").map(Number),s=new Date(t);return s.setHours(n,r,0,0),s.getTime()<=t&&s.setDate(s.getDate()+1),s.getTime()-t}function z(e,t,n){let[r,s]=t.split(":").map(Number),i=new Date(n);i.setHours(r,s,0,0);let o=(e-i.getDay()+7)%7;return o===0&&i.getTime()<=n&&(o=7),i.setDate(i.getDate()+o),i.getTime()-n}function X(e,t=Date.now()){return e.type==="daily"?V(e.time,t):e.type==="weekly"?z(e.dayOfWeek,e.time,t):e.intervalMs||6e4}function u(e,t=Date.now()){e.type!=="once"&&(e.nextRun=e.isPaused?null:t+X(e,t))}function j(e,t,n,r){let{message:s,projectId:i,preCheck:o,selection:h,...c}=e,y={id:t,message:s,projectId:i,selection:{...r},preCheck:o,createdAt:n};if(c.type==="once")return{...y,type:"once",runAt:n+c.delayMs};let k={...y,...c,lastRun:null,nextRun:null};return u(k,n),k}function ue(e,t,n){if(e===void 0&&t===void 0)return;let r={...e!==void 0?S(e):{},...t!==void 0?{thinking:t}:{}},s=D({request:n},r);if(s.ok===!0)return s.selection;if(s.reason==="invalid-thinking"){let i=r.backend??n?.backend??s.base?.backend,o=(s.allowed??[]).join(", ");throw new a("thinking",`Invalid thinking '${t}' for ${i}. Valid values: ${o}`,t)}throw new a("model",`Cannot use model '${e??""}': ${s.reason}`,e)}function Y(e){let t=e.CORTEX_BACKEND;return t!=="claude"&&t!=="pi"||!e.CORTEX_MODEL?null:{backend:t,provider:e.CORTEX_PROVIDER||null,model:e.CORTEX_MODEL}}function ce(e,t,n=process.env){if(!(!e||!t||!n.CORTEX_SESSION_ID))try{_({backend:t.backend,model:x(t),parent:Y(n)})}catch(r){throw new a("model",r.message,e)}}import*as p from"path";import*as R from"fs";var q=p.join(d,"schedules.json"),K=p.join(d,"channel-registry.json");function C(){return{tasks:[]}}function P(e){try{let t=R.readFileSync(e??K,"utf8"),n=JSON.parse(t),r={};for(let[s,i]of Object.entries(n))r[i]=s;return r}catch{return{}}}function pe(e){return P()[e]??null}function G(e){return function(n){if(typeof n!="object"||n===null||!("tasks"in n))return C();let r=n,s=P(e);for(let i of r.tasks){let o=i;"channel"in o&&!("projectId"in o)?(o.projectId=s[String(o.channel)]??"general",delete o.channel):"projectId"in o&&"channel"in o&&delete o.channel}for(let i of r.tasks){let o=i;delete o.target,delete o.fallback,o.selection&&(o.selection=g(o.selection))}return r}}var m=class{_repo;constructor(t=q,n){this._repo=new w({filePath:t,defaultValue:C,migrate:G(n),sharedFile:!0})}async read(){return this._repo.read()}async addTask(t){await this._repo.mutate(n=>(n.tasks.push(t),{next:n,result:void 0}))}async removeTask(t){return this._repo.mutate(n=>{let r=n.tasks.findIndex(s=>s.id===t);return r===-1?{next:n,result:!1}:(n.tasks.splice(r,1),{next:n,result:!0})})}async updateTask(t,n){return this._repo.mutate(r=>{let s=r.tasks.find(i=>i.id===t);return s?(n(s),{next:r,result:s}):{next:r,result:null}})}async findTask(t){return(await this._repo.read()).tasks.find(r=>r.id===t)||null}async mutate(t){return this._repo.mutate(t)}invalidate(){this._repo.invalidate()}flush(){return this._repo.flush()}},he=new m,ye=new Set(["task-dispatch","task-archive"]);import{randomBytes as J}from"crypto";async function Te(e,t,n={}){let r=j(t,J(4).toString("hex"),Date.now(),t.selection??T()),s=n.idempotencyKey;return s&&(r.idempotencyKey=s),e.mutate(i=>{let o=s?i.tasks.find(h=>h.idempotencyKey===s):void 0;return o?{next:i,result:{task:o,created:!1}}:(i.tasks.push(r),{next:i,result:{task:r,created:!0}})})}function Se(e,t,n){return e.updateTask(t,r=>{Object.assign(r,M(r.type,n)),u(r)})}function _e(e,t){return e.updateTask(t,n=>{if(n.type==="once")throw new Error(`cannot pause once schedule ${t}`);n.isPaused||Object.assign(n,{isPaused:!0,pausedAt:Date.now(),pausedBy:"user",nextRun:null})})}function De(e,t){return e.updateTask(t,n=>{if(n.type==="once")throw new Error(`cannot resume once schedule ${t}`);n.isPaused&&(Object.assign(n,{isPaused:!1,pausedAt:null,pausedBy:null}),u(n))})}export{b as a,Q as b,E as c,a as d,l as e,I as f,L as g,te as h,M as i,X as j,ue as k,ce as l,q as m,pe as n,m as o,he as p,ye as q,Te as r,Se as s,_e as t,De as u};
|
|
@@ -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 i}from"./chunk-VBN2JSER.js";import*as s from"node:os";import*as r from"node:path";var o=i("pi-sdk");var l="./core/model-resolver.js",a;function p(){return a??=import("./dist-V5FRMUFH.js"),a}var u="gpt-5.5",c="gpt-6.1-sol";function f(e){return e.openai===u?{...e,openai:c}:e}function P(e){return typeof e=="object"&&e!==null&&Object.values(e).every(t=>typeof t=="string")}async function h(e){try{let t=e??"file:///unused-bundled-entry.js",n=e?await import(new URL(l,t).href):await import("./model-resolver-FVJNZ6NA.js");if(P(n.defaultModelPerProvider))return f(n.defaultModelPerProvider);o.warn("PI default model table has an unexpected shape; using PI model order")}catch(t){o.warn(`PI default model table unavailable; using PI model order: ${t.message}`)}return{}}function g(){let e=Date.now();p().then(()=>o.info(`PI SDK preloaded in ${Date.now()-e}ms`)).catch(t=>o.warn(`PI SDK preload failed; the first PI session will surface the error: ${t.message}`))}function d(){return r.join(s.homedir(),".pi","agent")}function w(){return r.join(d(),"auth.json")}function A(){return r.join(d(),"models.json")}export{p as a,h as b,g as c,d,w as e,A as f};
|
|
@@ -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{a as g,c as _}from"./chunk-WHC7AYZD.js";var D=_((U,O)=>{O.exports={name:"dotenv",version:"16.6.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var S=_((B,d)=>{var E=g("fs"),h=g("path"),T=g("os"),I=g("crypto"),$=D(),m=$.version,A=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function j(e){let r={},n=e.toString();n=n.replace(/\r\n?/mg,`
|
|
5
|
+
`);let s;for(;(s=A.exec(n))!=null;){let i=s[1],t=s[2]||"";t=t.trim();let o=t[0];t=t.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(t=t.replace(/\\n/g,`
|
|
6
|
+
`),t=t.replace(/\\r/g,"\r")),r[i]=t}return r}function k(e){e=e||{};let r=w(e);e.path=r;let n=c.configDotenv(e);if(!n.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${r} for an unknown reason`);throw o.code="MISSING_DATA",o}let s=V(e).split(","),i=s.length,t;for(let o=0;o<i;o++)try{let a=s[o].trim(),u=K(n,a);t=c.decrypt(u.ciphertext,u.key);break}catch(a){if(o+1>=i)throw a}return c.parse(t)}function x(e){console.log(`[dotenv@${m}][WARN] ${e}`)}function v(e){console.log(`[dotenv@${m}][DEBUG] ${e}`)}function b(e){console.log(`[dotenv@${m}] ${e}`)}function V(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function K(e,r){let n;try{n=new URL(r)}catch(a){if(a.code==="ERR_INVALID_URL"){let u=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw u.code="INVALID_DOTENV_KEY",u}throw a}let s=n.password;if(!s){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let i=n.searchParams.get("environment");if(!i){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let t=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[t];if(!o){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${t} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:o,key:s}}function w(e){let r=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let n of e.path)E.existsSync(n)&&(r=n.endsWith(".vault")?n:`${n}.vault`);else r=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else r=h.resolve(process.cwd(),".env.vault");return E.existsSync(r)?r:null}function N(e){return e[0]==="~"?h.join(T.homedir(),e.slice(1)):e}function Y(e){let r=!!(e&&e.debug),n=e&&"quiet"in e?e.quiet:!0;(r||!n)&&b("Loading env from encrypted .env.vault");let s=c._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),c.populate(i,s,e),{parsed:s}}function L(e){let r=h.resolve(process.cwd(),".env"),n="utf8",s=!!(e&&e.debug),i=e&&"quiet"in e?e.quiet:!0;e&&e.encoding?n=e.encoding:s&&v("No encoding is specified. UTF-8 is used by default");let t=[r];if(e&&e.path)if(!Array.isArray(e.path))t=[N(e.path)];else{t=[];for(let f of e.path)t.push(N(f))}let o,a={};for(let f of t)try{let l=c.parse(E.readFileSync(f,{encoding:n}));c.populate(a,l,e)}catch(l){s&&v(`Failed to load ${f} ${l.message}`),o=l}let u=process.env;if(e&&e.processEnv!=null&&(u=e.processEnv),c.populate(u,a,e),s||!i){let f=Object.keys(a).length,l=[];for(let y of t)try{let p=h.relative(process.cwd(),y);l.push(p)}catch(p){s&&v(`Failed to load ${y} ${p.message}`),o=p}b(`injecting env (${f}) from ${l.join(",")}`)}return o?{parsed:a,error:o}:{parsed:a}}function R(e){if(V(e).length===0)return c.configDotenv(e);let r=w(e);return r?c._configVault(e):(x(`You set DOTENV_KEY but you are missing a .env.vault file at ${r}. Did you forget to build it?`),c.configDotenv(e))}function q(e,r){let n=Buffer.from(r.slice(-64),"hex"),s=Buffer.from(e,"base64"),i=s.subarray(0,12),t=s.subarray(-16);s=s.subarray(12,-16);try{let o=I.createDecipheriv("aes-256-gcm",n,i);return o.setAuthTag(t),`${o.update(s)}${o.final()}`}catch(o){let a=o instanceof RangeError,u=o.message==="Invalid key length",f=o.message==="Unsupported state or unable to authenticate data";if(a||u){let l=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw l.code="INVALID_DOTENV_KEY",l}else if(f){let l=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw l.code="DECRYPTION_FAILED",l}else throw o}}function P(e,r,n={}){let s=!!(n&&n.debug),i=!!(n&&n.override);if(typeof r!="object"){let t=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw t.code="OBJECT_REQUIRED",t}for(let t of Object.keys(r))Object.prototype.hasOwnProperty.call(e,t)?(i===!0&&(e[t]=r[t]),s&&v(i===!0?`"${t}" is already defined and WAS overwritten`:`"${t}" is already defined and was NOT overwritten`)):e[t]=r[t]}var c={configDotenv:L,_configVault:Y,_parseVault:k,config:R,decrypt:q,parse:j,populate:P};d.exports.configDotenv=c.configDotenv;d.exports._configVault=c._configVault;d.exports._parseVault=c._parseVault;d.exports.config=c.config;d.exports.decrypt=c.decrypt;d.exports.parse=c.parse;d.exports.populate=c.populate;d.exports=c});export{S as a};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{b as vt}from"./chunk-BDLKI2NT.js";import{L as yt}from"./chunk-JJDEQ6N2.js";import{a as gt,c as _t}from"./chunk-MGYYSX7Y.js";import{a as Nt}from"./chunk-V35MFAUQ.js";import{a as lt}from"./chunk-Q4UGYGU5.js";import{b as dt,d as ht}from"./chunk-AVXDF7AG.js";import{e as h}from"./chunk-3CPIMAYX.js";import{e as mt}from"./chunk-VBN2JSER.js";import{i as pt,j as ft}from"./chunk-Z24SBRJK.js";import{e as $t}from"./chunk-WHC7AYZD.js";import*as I from"path";import E from"node:fs/promises";var Bt=2160*60*60*1e3,J={daily_usd:300,monthly_usd:8e3,projects:{}};function A(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function qt(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[r,n]of Object.entries(t)){if(!r||!n||typeof n!="object")continue;let{daily_usd:o,monthly_usd:s}=n;!A(o)||!A(s)||(e[r]={daily_usd:o,monthly_usd:s})}return e}function Kt(t){let e=t&&typeof t=="object"?t:{};return{daily_usd:A(e.daily_usd)?e.daily_usd:J.daily_usd,monthly_usd:A(e.monthly_usd)?e.monthly_usd:J.monthly_usd,projects:qt(e.projects)}}function Lt(){return process.env.CORTEX_COSTS_FILE||I.join(ft,"costs.jsonl")}function Vt(){return process.env.CORTEX_BUDGET_FILE||I.join(pt,"budget.json")}var W=class{costMutex=new lt;_ready=!1;_cache=null;_budgetRepo=null;_costsPath;_budgetPath;constructor(e={}){this._costsPath=e.costsPath??null,this._budgetPath=e.budgetPath??null}get costFilePath(){return this._costsPath??Lt()}get budgetRepo(){return this._budgetRepo||(this._budgetRepo=new _t({filePath:this._budgetPath??Vt(),defaultValue:()=>({...J,projects:{}}),migrate:Kt})),this._budgetRepo}async _ensureReady(){if(this._ready)return;let e=this.costFilePath;await E.mkdir(I.dirname(e),{recursive:!0});let r=await this._readFileEntries(e),n=Date.now()-Bt,o=r.filter(s=>new Date(s.timestamp).getTime()>n);if(o.length<r.length){let s=o.map(a=>JSON.stringify(a)).join(`
|
|
5
|
+
`)+`
|
|
6
|
+
`;await ht(e,s)}this._ready=!0}async _readEntriesRange(e,r,n){if(n<=r)return{entries:[],consumedTo:r};let o=await E.open(e,"r");try{let s=Buffer.allocUnsafe(n-r),{bytesRead:a}=await o.read(s,0,s.length,r),l=a>0?s.lastIndexOf(10,a-1):-1;return l<0?{entries:[],consumedTo:r}:{entries:s.toString("utf8",0,l+1).split(`
|
|
7
|
+
`).filter(c=>c.trim()!=="").map(c=>JSON.parse(c)),consumedTo:r+l+1}}finally{await o.close()}}async _readFileEntries(e){try{return(await E.readFile(e,"utf8")).split(`
|
|
8
|
+
`).filter(n=>n.trim()!=="").map(n=>JSON.parse(n))}catch(r){if(r.code==="ENOENT")return[];throw r}}async recordEntry(e){await this.costMutex.run(async()=>{await this._ensureReady(),await E.appendFile(this.costFilePath,JSON.stringify(e)+`
|
|
9
|
+
`,"utf8")})}async recordEntryBatch(e){if(e.length===0)return;let r=e.map(n=>JSON.stringify(n)).join(`
|
|
10
|
+
`)+`
|
|
11
|
+
`;await this.costMutex.run(async()=>{await this._ensureReady(),await E.appendFile(this.costFilePath,r,"utf8")})}async readCosts(){await this._ensureReady();let e=this.costFilePath,r,n,o;try{let i=await E.stat(e);r=i.ino,n=i.size,o=i.mtimeMs}catch(i){if(i.code!=="ENOENT")throw i;return this._cache=null,{entries:[]}}let s=this._cache?.path===e&&this._cache.ino===r?this._cache:null;if(s&&n===s.size&&o===s.mtimeMs)return{entries:s.entries.slice()};if(s&&n>s.size){let{entries:i,consumedTo:c}=await this._readEntriesRange(e,s.size,n),d=s.entries.concat(i);return this._cache={path:e,ino:r,size:c,mtimeMs:o,entries:d},{entries:d.slice()}}let{entries:a,consumedTo:l}=await this._readEntriesRange(e,0,n);return this._cache={path:e,ino:r,size:l,mtimeMs:o,entries:a},{entries:a.slice()}}async readBudget(){return this.budgetRepo.read()}async writeBudget(e){await this.budgetRepo.write(e)}invalidateBudget(){this._budgetRepo?.invalidate()}async flush(){await this.costMutex.run(async()=>{}),this._budgetRepo&&await this._budgetRepo.flush()}_testReset(){this._budgetRepo=null,this._ready=!1,this._cache=null}},f=new W;gt(f);var wt=class extends Error{constructor(t){super(t),this.name=new.target.name}};var kt=class extends wt{provider;envName;constructor(t,e){super(e?`Provider '${t}' is not configured. Set ${e} or pass apiKey explicitly.`:`Provider '${t}' is not configured. Pass apiKey explicitly.`),this.provider=t,this.envName=e}};var Yt=class extends Error{status;body;constructor(t,e){super(`HTTP ${t}`),this.name="HTTPStatusError",this.status=t,this.body=e}};function F(t){if(t&&!(typeof process>"u"||!process.env))return process.env[t]}function D(t,e,r){if(!e)throw new kt(t,r);return e}function M(t,e){return`${t.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`}function O(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>O(e)).filter(Boolean).join(`
|
|
12
|
+
`);if(X(t)){if(typeof t.text=="string")return t.text;if("content"in t)return O(t.content)}return""}function X(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function j(t,e={}){let r=new AbortController,n=e.timeoutMs??3e3,o=setTimeout(()=>{r.abort(new Error(`Request timed out after ${n}ms`))},n),s=e.signal,a=()=>{r.abort(s?.reason)};s&&(s.aborted?r.abort(s.reason):s.addEventListener("abort",a,{once:!0}));try{let l=new Headers(e.headers??{}),i=e.body;i!=null&&typeof i!="string"&&!(i instanceof URLSearchParams)&&!(i instanceof FormData)&&!(i instanceof Blob)&&!(i instanceof ArrayBuffer)&&(i=JSON.stringify(i)),typeof i=="string"&&!l.has("content-type")&&l.set("content-type","application/json");let c=await fetch(t,{...e,headers:l,body:i,signal:r.signal}),d=await c.text(),_=d?zt(d):null;if(!c.ok)throw new Yt(c.status,_);return _}finally{clearTimeout(o),s?.removeEventListener("abort",a)}}function zt(t){try{return JSON.parse(t)}catch{return t}}var Ht=$t(Nt(),1);import*as Tt from"os";import*as $ from"path";import{randomUUID as Jt}from"crypto";var Ge=256*1024;var Gt=$.join(Tt.homedir(),".aistatus"),Je=$.join(Gt,"config.yaml");var Z="0.0.11",Wt="https://aistatus.cc",St=100,Xt=1e3,Qt=6e4,Zt=1e4,bt=5e3,Et=Symbol.for(`aistatus.usage-upload-queues@${Z}`);function Q(t,e){return t.length>e?t.slice(0,e):t}async function It(t,e){let r,n=new Promise(o=>{r=setTimeout(o,Math.max(0,e))});try{await Promise.race([t,n])}finally{clearTimeout(r)}}var te=class{constructor(t){this.url=t,setInterval(()=>{this.flush()},Qt).unref?.()}enqueued=0;exitMark=0;records=[];head=null;inflight=null;push(t){this.records.push(t),this.enqueued+=1;let e=(this.head?.records.length??0)+this.records.length-Xt;e>0&&this.records.splice(0,e),this.records.length>=St&&!this.head&&this.flush()}hasWork(){return this.head!==null||this.records.length>0}flush(){return this.inflight??=this.drain().finally(()=>{this.inflight=null}),this.inflight}async flushAll(){this.inflight&&await this.inflight,this.hasWork()&&await this.flush()}async drain(){for(;;){if(!this.head){if(this.records.length===0)return;this.head={id:Jt(),records:this.records.splice(0,St)}}if(!await this.send(this.head))return;this.head=null}}async send(t){let e;try{let s={batch_id:t.id,sdk_version:Z,records:t.records};e=JSON.stringify(s)}catch{return!0}let r=new AbortController,n,o=new Promise((s,a)=>{n=setTimeout(()=>{r.abort(),a(new Error("usage upload timed out"))},Zt),n.unref?.()});try{let s=await Promise.race([fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:e,signal:r.signal}),o]);return await Promise.race([s.text(),o]).catch(()=>{}),!(s.status===429||s.status>=500)}catch{return!1}finally{clearTimeout(n)}}};function tt(){return globalThis[Et]}function ee(t){for(let e of t.values())e.enqueued!==e.exitMark&&e.hasWork()&&(e.exitMark=e.enqueued,e.flush())}function re(t){let e=tt();if(!e){let n=new Map;globalThis[Et]=n,typeof process<"u"&&typeof process.on=="function"&&process.on("beforeExit",()=>ee(n)),e=n}let r=e.get(t);return r||(r=new te(t),e.set(t,r)),r}async function et(t=bt){let e=tt();!e||e.size===0||await It(Promise.all([...e.values()].map(r=>r.flushAll())).then(()=>{}),t)}var rt=class{config;url;constructor(t,e=Wt){this.config=t,this.url=M(e,"/api/usage/upload")}setConfig(t){this.config=t}get enabled(){return!!(this.config.uploadEnabled&&this.config.name&&this.config.email)}upload(t){if(this.enabled)try{re(this.url).push(this.buildRecord(t))}catch{}}async flush(t=bt){let e=tt()?.get(this.url);e&&await It(e.flushAll(),t)}buildRecord(t){return{ts:t.ts,name:Q(this.config.name,200),organization:this.config.org?Q(this.config.org,200):null,email:Q(this.config.email,254),provider:t.provider,model:t.model,input_tokens:t.in??0,output_tokens:t.out??0,cache_creation_input_tokens:t.cache_creation_in??0,cache_read_input_tokens:t.cache_read_in??0,cost_usd:t.cost??0,latency_ms:t.latency_ms??0}}};var N=class{content;modelUsed;providerUsed;wasFallback;fallbackReason;inputTokens;outputTokens;cacheCreationInputTokens;cacheReadInputTokens;costUsd;raw;constructor(t){this.content=t.content,this.modelUsed=t.modelUsed,this.providerUsed=t.providerUsed,this.wasFallback=t.wasFallback,this.fallbackReason=t.fallbackReason??null,this.inputTokens=t.inputTokens??0,this.outputTokens=t.outputTokens??0,this.cacheCreationInputTokens=t.cacheCreationInputTokens??0,this.cacheReadInputTokens=t.cacheReadInputTokens??0,this.costUsd=t.costUsd??0,this.raw=t.raw??null}toString(){return this.content}};var ne={anthropic:"anthropic",openai:"openai",google:"google",openrouter:"openrouter",deepseek:"deepseek",mistral:"mistral",mistralai:"mistral",xai:"xai","x-ai":"xai",groq:"groq",together:"together",moonshot:"moonshot",moonshotai:"moonshot",qwen:"qwen"};function B(t){let e=(t??"").trim().toLowerCase();return ne[e]??e}var nt=class{config;constructor(t){this.config={...t,slug:B(t.slug),aliases:(t.aliases??[]).map(e=>B(e))}}get slug(){return this.config.slug}get aliases(){return this.config.aliases??[]}supportsProvider(t){let e=B(t);return e===this.slug||this.aliases.includes(e)}stripProvider(t){return t.includes("/")?t.slice(t.indexOf("/")+1):t}},oe=new Map;function m(t,e){oe.set(t.toLowerCase(),e)}var v=class extends nt{defaultBaseUrl="https://api.openai.com/v1";defaultEnvVar="OPENAI_API_KEY";_client=null;_clientKey="";getBaseUrl(){return this.config.baseUrl??this.defaultBaseUrl}getApiKey(){return D(this.slug,this.config.apiKey??F(this.config.env??this.defaultEnvVar),this.config.env??this.defaultEnvVar)}getDefaultHeaders(){return{}}buildPayload(t,e,r){let n=e.map(s=>({role:s.role,content:typeof s.content=="string"?s.content:se(s.content),...s.name?{name:s.name}:{},...s.toolCallId?{tool_call_id:s.toolCallId}:{}})),o={...r.providerOptions??{},model:this.stripProvider(t),messages:n};return r.maxTokens!==void 0&&o.max_tokens===void 0&&o.max_completion_tokens===void 0&&(o.max_tokens=r.maxTokens),r.temperature!==void 0&&o.temperature===void 0&&(o.temperature=r.temperature),r.topP!==void 0&&o.top_p===void 0&&(o.top_p=r.topP),r.responseFormat&&o.response_format===void 0&&(o.response_format=r.responseFormat),o}async call(t,e,r,n){let o=this.getApiKey(),a=await this.getClient(o).chatCompletions(this.buildPayload(t,e,n),{timeoutMs:r*1e3,signal:n.signal,headers:{...this.getDefaultHeaders(),...this.config.headers??{},...n.headers??{}}});return this.toResponse(a,t)}getClient(t=this.getApiKey()){let e=`${this.getBaseUrl()}::${t}`;return this._client&&this._clientKey===e?this._client:(this._clientKey=e,this._client={chatCompletions:(r,n)=>j(M(this.getBaseUrl(),"chat/completions"),{method:"POST",headers:{authorization:`Bearer ${t}`,...n.headers??{}},body:r,timeoutMs:n.timeoutMs,signal:n.signal})},this._client)}toResponse(t,e){return new N({content:O(t.choices?.[0]?.message?.content),modelUsed:e,providerUsed:this.slug,wasFallback:!1,inputTokens:t.usage?.prompt_tokens??0,outputTokens:t.usage?.completion_tokens??0,raw:t})}};function se(t){return t.map(e=>{switch(e.type){case"text":return{type:"text",text:e.text};case"image_url":return{type:"image_url",image_url:e.image_url};case"image":return{type:"image_url",image_url:{url:`data:${e.source.media_type};base64,${e.source.data}`}};default:return e}})}m("openai",v);var ae=class extends v{defaultBaseUrl="https://openrouter.ai/api/v1";defaultEnvVar="OPENROUTER_API_KEY";getDefaultHeaders(){return{"HTTP-Referer":"https://aistatus.cc","X-Title":"aistatus"}}};m("openrouter",ae);function xt(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
13
|
+
`)}var ie=class extends nt{defaultBaseUrl="https://api.anthropic.com/v1";defaultEnvVar="ANTHROPIC_API_KEY";_client=null;_clientKey="";async call(t,e,r,n){let o=[],s=e.filter(c=>c.role==="system"?(o.push(xt(c.content)),!1):!0).map(c=>({role:c.role==="assistant"?"assistant":"user",content:typeof c.content=="string"?c.content:ce(c.content)})),a={...n.providerOptions??{},model:this.stripProvider(t),messages:s};if(o.length>0&&a.system===void 0){let c=o.join(`
|
|
14
|
+
|
|
15
|
+
`),d=Mt(n);a.system=d?`${c}
|
|
16
|
+
|
|
17
|
+
${d}`:c}else if(n.responseFormat&&n.responseFormat.type!=="text"){let c=Mt(n);c&&(a.system=c)}a.max_tokens===void 0&&(a.max_tokens=n.maxTokens??4096),n.temperature!==void 0&&a.temperature===void 0&&(a.temperature=n.temperature),n.topP!==void 0&&a.top_p===void 0&&(a.top_p=n.topP);let l=D(this.slug,this.config.apiKey??F(this.config.env??this.defaultEnvVar),this.config.env??this.defaultEnvVar),i=await this.getClient(l).messages(a,{timeoutMs:r*1e3,signal:n.signal,headers:{"anthropic-version":"2023-06-01",...this.config.headers??{},...n.headers??{}}});return new N({content:(i.content??[]).filter(c=>c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
|
|
18
|
+
`),modelUsed:t,providerUsed:this.slug,wasFallback:!1,inputTokens:i.usage?.input_tokens??0,outputTokens:i.usage?.output_tokens??0,cacheCreationInputTokens:i.usage?.cache_creation_input_tokens??0,cacheReadInputTokens:i.usage?.cache_read_input_tokens??0,raw:i})}getClient(t){let e=this.config.baseUrl??this.defaultBaseUrl,r=`${e}::${t}`;return this._client&&this._clientKey===r?this._client:(this._clientKey=r,this._client={messages:(n,o)=>j(M(e,"messages"),{method:"POST",headers:{"x-api-key":t,...o.headers??{}},body:n,timeoutMs:o.timeoutMs,signal:o.signal})},this._client)}};function ce(t){return t.map(e=>{switch(e.type){case"text":return{type:"text",text:e.text};case"image_url":return{type:"image",source:{type:"url",url:e.image_url.url}};case"image":return{type:"image",source:{type:"base64",media_type:e.source.media_type,data:e.source.data}};default:return e}})}function Mt(t){let e=t.responseFormat;return!e||e.type==="text"?null:e.type==="json_object"?"Respond with valid JSON only.":e.type==="json_schema"?`Respond with valid JSON matching this schema:
|
|
19
|
+
${JSON.stringify(e.json_schema.schema,null,2)}`:null}m("anthropic",ie);var ue=class extends nt{defaultBaseUrl="https://generativelanguage.googleapis.com/v1beta";defaultEnvVar="GEMINI_API_KEY";async call(t,e,r,n){let o={...n.providerOptions??{}},s=X(o.generationConfig)?{...o.generationConfig}:{},a=[],l=e.filter(p=>p.role==="system"?(a.push(xt(p.content)),!1):!0).map(p=>({role:p.role==="assistant"?"model":"user",parts:typeof p.content=="string"?[{text:p.content}]:le(p.content)}));if(n.maxTokens!==void 0&&s.maxOutputTokens===void 0&&(s.maxOutputTokens=n.maxTokens),n.temperature!==void 0&&s.temperature===void 0&&(s.temperature=n.temperature),n.topP!==void 0&&s.topP===void 0&&(s.topP=n.topP),n.responseFormat&&s.responseMimeType===void 0){let p=n.responseFormat;p.type==="json_object"?s.responseMimeType="application/json":p.type==="json_schema"&&(s.responseMimeType="application/json",s.responseSchema=p.json_schema.schema)}let i={...o,contents:l};Object.keys(s).length>0&&(i.generationConfig=s),a.length>0&&i.systemInstruction===void 0&&(i.systemInstruction={parts:[{text:a.join(`
|
|
20
|
+
|
|
21
|
+
`)}]});let c=de(this.stripProvider(t)),d=D(this.slug,this.config.apiKey??F(this.config.env??this.defaultEnvVar),this.config.env??this.defaultEnvVar),_=`${this.config.baseUrl??this.defaultBaseUrl}/models/${c}:generateContent`,y=await j(_,{method:"POST",headers:{"x-goog-api-key":d,...this.config.headers??{},...n.headers??{}},body:i,timeoutMs:r*1e3,signal:n.signal});return new N({content:(y.candidates?.[0]?.content?.parts??[]).map(p=>p.text??"").filter(Boolean).join(`
|
|
22
|
+
`),modelUsed:t,providerUsed:this.slug,wasFallback:!1,inputTokens:y.usageMetadata?.promptTokenCount??0,outputTokens:y.usageMetadata?.candidatesTokenCount??0,raw:y})}};function le(t){return t.map(e=>{switch(e.type){case"text":return{text:e.text};case"image_url":return{text:`[image: ${e.image_url.url}]`};case"image":return{inlineData:{mimeType:e.source.media_type,data:e.source.data}};default:return e}})}function de(t){return t.startsWith("models/")?t.slice(7):t}m("google",ue);var he=class extends v{defaultBaseUrl="https://api.deepseek.com";defaultEnvVar="DEEPSEEK_API_KEY"},pe=class extends v{defaultBaseUrl="https://api.mistral.ai/v1";defaultEnvVar="MISTRAL_API_KEY"},fe=class extends v{defaultBaseUrl="https://api.x.ai/v1";defaultEnvVar="XAI_API_KEY"},me=class extends v{defaultBaseUrl="https://api.groq.com/openai/v1";defaultEnvVar="GROQ_API_KEY"},ge=class extends v{defaultBaseUrl="https://api.together.xyz/v1";defaultEnvVar="TOGETHER_API_KEY"},_e=class extends v{defaultBaseUrl="https://api.moonshot.cn/v1";defaultEnvVar="MOONSHOT_API_KEY"},ye=class extends v{defaultBaseUrl="https://dashscope.aliyuncs.com/compatible-mode/v1";defaultEnvVar="DASHSCOPE_API_KEY"};m("deepseek",he);m("mistral",pe);m("xai",fe);m("groq",me);m("together",ge);m("moonshot",_e);m("qwen",ye);var Pt=mt("leaderboard"),ve=3e3,we=["anthropic","openai","google","openrouter"];function ke(t,e){return e.includes("/")?e.split("/",1)[0]:we.find(r=>t.startsWith(r))??t}function Se(t){return t.replace(/\[[^\]]*\]$/,"")}function Te(t){return t.provider?t.provider:t.backend==="claude"?"anthropic":null}function be(t){let e=Te(t);if(!e)return null;let r=t.model?Se(t.model):`${e}/unknown`;return{ts:t.timestamp,provider:ke(e,r),model:r,in:t.input_tokens??0,out:t.output_tokens??0,cache_creation_in:t.cache_creation_tokens??0,cache_read_in:t.cache_read_tokens??0,cost:t.cost_usd??0,...t.duration_s!=null?{latency_ms:Math.round(t.duration_s*1e3)}:{}}}function Ee(t){return{uploadEnabled:t.enabled,name:t.name||null,org:t.org||null,email:t.email||null}}function Ie(t={}){let e=t.readSharing??(()=>vt()),r=t.uploader??null;return{share(n){if(r)try{if(r.setConfig(Ee(e())),!r.enabled)return;let o=be(n);o&&r.upload(o)}catch(o){Pt.warn(`leaderboard upload skipped: ${o?.message??o}`)}}}}var Me={uploadEnabled:!1,name:null,org:null,email:null};function xe(){return dt()?null:new rt(Me)}var Rt=Ie({uploader:xe()});async function Kr(t=ve){await et(t).catch(e=>{Pt.warn(`leaderboard flush failed: ${e?.message??e}`)})}function Pe(t,e){let r=e?t.projects?.[e]:void 0;return r?{daily_usd:r.daily_usd,monthly_usd:r.monthly_usd,scope:"project"}:{daily_usd:t.daily_usd,monthly_usd:t.monthly_usd,scope:"global"}}var Re=["total","api","plan"];function Ue(t,e){let r=t.backend==="pi"?{backend:"pi",provider:t.provider??t.connection??null,connection:null}:{backend:"claude",provider:null,connection:t.connection??null};return e(r)==="subscription"?"plan":"api"}function Ce(t){return t==="plan"||t==="subscription"?"plan":"api"}function x(){return{today:0,week:0,month:0,total:0}}function q(){return Object.fromEntries(Re.map(t=>[t,0]))}function K(t,e,r){t.total+=r,t[e]+=r}async function Gr(t,e=Rt,r=yt.billingOf){let n=t.source||"estimate",o=[t.input_tokens,t.output_tokens,t.cache_read_tokens,t.cache_creation_tokens,t.provider_requests].some(a=>a!=null);if(n==="estimate"&&!t.cost_usd&&!o)return;let s={timestamp:new Date().toISOString(),project:t.project||"general",trigger:t.trigger||"unknown",cost_usd:t.cost_usd??null,num_turns:t.num_turns??null,duration_s:t.duration_s??null,backend:t.backend||"claude",mode:Ue(t,r),...t.connection?{connection:t.connection}:{},source:n,input_tokens:t.input_tokens??null,output_tokens:t.output_tokens??null,cache_read_tokens:t.cache_read_tokens??null,cache_creation_tokens:t.cache_creation_tokens??null,provider_requests:Number.isSafeInteger(t.provider_requests)&&Number(t.provider_requests)>0?t.provider_requests:null,session_id:t.session_id??null,execution_id:t.execution_id??null,attempt_id:t.attempt_id??null,root_attempt_id:t.root_attempt_id??null,trial_id:t.trial_id??null,root_run_id:t.root_run_id??null};t.prompt_tokens!==void 0&&(s.prompt_tokens=t.prompt_tokens),t.provider&&(s.provider=t.provider),t.model&&(s.model=t.model),await f.recordEntry(s),e.share(s)}function ot(){return{input:0,output:0}}var Ut=1440*60*1e3,Ae=14;function Ct(t){let e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${n}`}function P(t,e,r,n,o){t.total+=e,r&&(t.today+=e),n&&(t.week+=e),o&&(t.month+=e)}async function Dt(t,e){let r=await f.readCosts(),n=await f.readBudget(),o=e?.now??Date.now(),s=new Date(o);s.setHours(0,0,0,0);let a=new Date(o-7*Ut),l=new Date(o);l.setDate(1),l.setHours(0,0,0,0);let i=[];for(let u=Ae-1;u>=0;u--){let w=new Date(s);w.setDate(w.getDate()-u),i.push(Ct(w))}let c=new Map(i.map(u=>[u,0])),d={today:q(),week:q(),month:q(),total:q()},_={},y={},p={},R={},U={},k={today:ot(),month:ot(),total:ot()},at=0,it=0;for(let u of r.entries){let w=Ce(u.mode),g=u.cost_usd||0,V=u.source||"estimate",Y=u.backend||"claude",C=new Date(u.timestamp),S=C>=s,b=C>=a,T=C>=l;if(!t||u.project===t){at++,u.cost_usd==null&&it++,K(d.total,w,g),S&&K(d.today,w,g),b&&K(d.week,w,g),T&&K(d.month,w,g);let z=Object.hasOwn(u,"prompt_tokens")?u.prompt_tokens||0:u.input_tokens||0,H=u.output_tokens||0;k.total.input+=z,k.total.output+=H,S&&(k.today.input+=z,k.today.output+=H),T&&(k.month.input+=z,k.month.output+=H);let G=Ct(C);c.has(G)&&c.set(G,c.get(G)+g),p[u.trigger]||(p[u.trigger]=x()),P(p[u.trigger],g,S,b,T)}_[u.project]||(_[u.project]=x()),y[u.trigger]||(y[u.trigger]=x()),R[V]||(R[V]=x()),U[Y]||(U[Y]=x()),P(_[u.project],g,S,b,T),P(y[u.trigger],g,S,b,T),P(R[V],g,S,b,T),P(U[Y],g,S,b,T)}let ct=d.today.total,ut=(o-s.getTime())/Ut,jt=ut>0?ct/ut:ct,L=Pe(n,t);return{today:d.today.total,week:d.week.total,month:d.month.total,total:d.total.total,byMode:d,byProject:_,byTrigger:y,bySource:R,byBackend:U,tokens:k,entryCount:at,unpricedCount:it,dailyBudget:L.daily_usd,monthlyBudget:L.monthly_usd,budgetScope:L.scope,forecastToday:jt,dailyCost:i.map(u=>({date:u,cost:c.get(u)})),byTriggerScoped:p}}async function Jr(t){let e=t??null,r=await Dt(e),{dailyBudget:n,monthlyBudget:o}=r;return{withinBudget:r.today<n&&r.month<o,dailyBudget:n,dailySpent:r.today,dailyRemaining:Math.max(0,n-r.today),monthlyBudget:o,monthlySpent:r.month,monthlyRemaining:Math.max(0,o-r.month),byMode:r.byMode,project:e,scope:r.budgetScope}}async function Wr({daily_usd:t,monthly_usd:e,project:r}){let n=await f.readBudget();if(r){if(t==null||e==null)throw Object.assign(new Error("A per-project budget must set both daily and monthly limits"),{code:"invalid-args"});return n.projects={...n.projects,[r]:{daily_usd:t,monthly_usd:e}},await f.writeBudget(n),{daily_usd:t,monthly_usd:e,scope:"project"}}return t!=null&&(n.daily_usd=t),e!=null&&(n.monthly_usd=e),await f.writeBudget(n),{daily_usd:n.daily_usd,monthly_usd:n.monthly_usd,scope:"global"}}async function Xr(t){let e=await f.readBudget();if(!e.projects?.[t])return!1;let{[t]:r,...n}=e.projects;return e.projects=n,await f.writeBudget(e),!0}async function Qr(){let t=await f.readBudget();return Object.entries(t.projects??{}).map(([e,r])=>({project:e,...r})).sort((e,r)=>e.project.localeCompare(r.project))}function At(t,e){return{today:t.today[e],week:t.week[e],month:t.month[e],total:t.total[e]}}function Ot(t,e){return` - ${h("notice.cost.modeLine",{label:t,today:e.today.toFixed(2),week:e.week.toFixed(2),month:e.month.toFixed(2),total:e.total.toFixed(2)})}`}function Ft(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function Oe(t,e){return`\u2022 ${h("notice.cost.statsLine",{name:t,today:e.today.toFixed(2),month:e.month.toFixed(2),total:e.total.toFixed(2)})}`}function st(t,e,r){t.push(""),t.push(`_${e}_`);for(let[n,o]of Object.entries(r).sort((s,a)=>a[1].total-s[1].total))t.push(Oe(n,o))}function Fe(t,e){if(!t)return`*${h("notice.cost.title")}*`;let r=e==="project"?h("notice.cost.scopeProject"):h("notice.cost.scopeInherited");return`*${h("notice.cost.titleProject",{project:t})}* _(${r})_`}async function Zr(t=null){let e=await Dt(t),r=Math.max(0,e.dailyBudget-e.today),n=Math.max(0,e.monthlyBudget-e.month),o=[];o.push(Fe(t,e.budgetScope)),o.push(`\u2022 ${h("notice.cost.today",{spent:e.today.toFixed(2),budget:e.dailyBudget,remaining:r.toFixed(2)})}`),o.push(`\u2022 ${h("notice.cost.month",{spent:e.month.toFixed(2),budget:e.monthlyBudget,remaining:n.toFixed(2)})}`),o.push(`\u2022 ${h("notice.cost.week",{spent:e.week.toFixed(2)})}`),o.push(`\u2022 ${h("notice.cost.total",{spent:e.total.toFixed(2)})}`),o.push(""),o.push(`_${h("notice.cost.byMode")}_`),o.push(Ot("API",At(e.byMode,"api"))),o.push(Ot("Plan",At(e.byMode,"plan"))),Object.keys(e.bySource).length>0&&st(o,h("notice.cost.bySource"),e.bySource),"pi"in e.byBackend&&st(o,h("notice.cost.byBackend"),e.byBackend);let s=e.tokens;if(s.total.input>0||s.total.output>0){o.push(""),o.push(`_${h("notice.cost.tokenUsage")}_`);for(let[a,l]of[["notice.cost.tokensToday",s.today],["notice.cost.tokensMonth",s.month],["notice.cost.tokensTotal",s.total]])o.push(`\u2022 ${h(a,{input:Ft(l.input),output:Ft(l.output)})}`)}if(!t&&Object.keys(e.byProject).length>0){o.push(""),o.push(`_${h("notice.cost.byProject")}_`);for(let[a,l]of Object.entries(e.byProject).sort((i,c)=>c[1].month-i[1].month))o.push(`\u2022 ${h("notice.cost.projectLine",{name:a,today:l.today.toFixed(2),month:l.month.toFixed(2)})}`)}return Object.keys(e.byTrigger).length>0&&st(o,h("notice.cost.byTrigger"),e.byTrigger),o.join(`
|
|
23
|
+
`)}export{f as a,Kr as b,Gr as c,Dt as d,Jr as e,Wr as f,Xr as g,Qr as h,Ft as i,Zr as j};
|