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