@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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
2
|
const require = __cortexCreateRequire(import.meta.url);
|
|
3
3
|
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as
|
|
4
|
+
import{a as Ue,b as C,c as L,e as h,f as Me,g as je}from"./chunk-RO4C2MJP.js";import{a as p,b as a,c as O,d as Be,e as Ye,f as ce,g as T,h as u,i as le,j as qe,k as ze,l as ve}from"./chunk-VW7TLY3P.js";import"./chunk-WHC7AYZD.js";import*as b from"node:fs/promises";import*as oe from"node:fs";import*as v from"node:path";import*as We from"node:child_process";import*as St from"node:crypto";import*as gt from"node:readline";function P(o){if(o.inputSchema.type!=="object")throw new Error(`JSON schema for tool "${o.name}" must be an object, but got ${o.inputSchema.type}`);return{type:"custom",name:o.name,input_schema:o.inputSchema,description:o.description,run:o.run,parse:n=>n,...o.close?{close:o.close}:{}}}var W=L.promises,Z=448,kt=384;function fe(o,n){let e=h.relative(o,n);return e===""||!e.startsWith(".."+h.sep)&&e!==".."&&!h.isAbsolute(e)}async function ke(o,n){for(let e of o)if(fe(await J(h.resolve(e)),n))return e}var Rt=40;function Q(o){let n=o?.code;return typeof n=="string"?n:void 0}async function J(o){let n=[],e=o,t=0;for(;;){let i;try{i=await W.realpath(e)}catch(r){let s;try{s=(await W.lstat(e)).isSymbolicLink()}catch(c){let l=Q(c);if(l!=="ENOENT"&&l!=="ENOTDIR")throw c;let d=h.dirname(e);if(d===e)throw c;n.push(h.basename(e)),e=d;continue}if(!s)throw r;if(++t>Rt)throw Object.assign(new Error("too many levels of symbolic links"),{code:"ELOOP"});e=h.resolve(h.dirname(e),await W.readlink(e));continue}return n.length?h.join(i,...n.reverse()):i}}async function Ge(o,n,e){let t=e?.allowedRoots??[],i=await J(h.resolve(o)),r;try{r=await J(h.resolve(i,n))}catch(c){throw new u(z(c,`path ${JSON.stringify(n)}`))}if(fe(i,r)||await ke(t,r)!==void 0)return r;let s=t.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new u(`path ${JSON.stringify(n)} is outside ${s}`)}async function Re(o,n){let e=h.dirname(o),t=h.join(e,`.tmp-${process.pid}-${C.randomUUID()}`),i=await W.stat(o).then(s=>s.mode&511,()=>{}),r;try{r=await W.open(t,"wx",kt),i!==void 0&&await r.chmod(i),await r.writeFile(n,"utf-8"),await r.sync(),await r.close(),r=void 0,await W.rename(t,o)}catch(s){throw r&&await r.close().catch(()=>{}),await W.unlink(t).catch(()=>{}),s}}function z(o,n){let e=Q(o);switch(e){case"ENOENT":return`${n}: no such file or directory`;case"EACCES":case"EPERM":return`${n}: permission denied`;case"ENOTDIR":return`${n}: not a directory`;case"EISDIR":return`${n}: is a directory`;case"ELOOP":return`${n}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${n}: file name too long`;case"ENOSPC":return`${n}: no space left on device`;case"EMFILE":case"ENFILE":return`${n}: too many open files`;default:return`${n}: ${e!==void 0?`i/o error (${e})`:"i/o error"}`}}var I=L.promises,It=je.promisify(Ue.execFile);async function Nt(o){let{client:n,sessionId:e}=o;if(!n)return async()=>{};let t=ce(n),i=o.session;if(!i){if(e===void 0)return async()=>{};t.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),i=await n.beta.sessions.retrieve(e)}let r=h.resolve(o.workdir,"skills"),s=[];for(let c of i.agent.skills)try{let l=await n.beta.skills.versions.retrieve(c.version,{skill_id:c.skill_id}),d=h.basename(l.name.trim());(d===""||d==="."||d==="..")&&(d=c.skill_id);let f=h.resolve(r,d);if(f!==r&&!f.startsWith(r+h.sep)){t.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:l.name});continue}let m=await n.beta.skills.versions.download(l.id,{skill_id:c.skill_id});await I.rm(f,{recursive:!0,force:!0}),await I.mkdir(f,{recursive:!0,mode:Z}),s.push(f),await Ve(m,f),t.info("downloaded skill",{component:"agent-tool-context",skill_id:c.skill_id,version:l.id,dest:f})}catch(l){t.warn("failed to download skill",{component:"agent-tool-context",skill_id:c.skill_id,error:String(l)})}return async()=>{for(let c of s)await I.rm(c,{recursive:!0,force:!0}).catch(l=>{t.warn("failed to clean up skill",{component:"agent-tool-context",dest:c,error:String(l)})})}}function Tt(o){for(let n of o){let e=n.trim();if(e&&(h.isAbsolute(e)||e.split(/[\\/]/).includes("..")))throw new O(`refusing to extract unsafe archive member: ${e}`)}}var Ne="skill archive listing is inconsistent; refusing to extract",Lt={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function He(o){let n=o.split(`
|
|
5
5
|
`);return n[n.length-1]===""&&n.pop(),n}function $t(o,n){return/^[\x20-\x7E]+$/.test(n)&&!/[\\^#]/.test(n)&&!(o==="unzip"&&n.startsWith("-"))}function At(o,n,e){let t=He(n),i=He(e);if(t.length!==i.length)throw new O(Ne);let r=[],s=[];return t.forEach((c,l)=>{if(Lt[o].has(i[l].charAt(0))){r.push(c);return}if(!$t(o,c))throw new O(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(c)}`);s.push(c)}),{plain:r,special:s}}async function Ke(o){for(let n of await I.readdir(o,{withFileTypes:!0}))if(n.isDirectory())await Ke(h.join(o,n.name));else if(!n.isFile())throw new O(Ne)}async function Ie(o,n){try{let{stdout:e}=await It(o,n);return e}catch(e){throw Q(e)==="ENOENT"?new O(`skill extraction requires the \`${o}\` command, but it was not found on PATH`):e}}function xt(o){let n,e=!1;for(let t of o){let i=t.trim().split("/").filter(s=>s!==""&&s!==".");if(i.length===0)continue;let r=i[0];if(n===void 0)n=r;else if(r!==n)return"";i.length>1&&(e=!0)}return n!==void 0&&e?n:""}async function Ve(o,n){let e=h.join(n,`.skill-archive-${process.pid}-${Date.now()}`);if(!o.body)throw new O("skill download response had no body");await Me.promises.pipeline(Me.Readable.fromWeb(o.body),L.createWriteStream(e));let t=h.join(h.dirname(n),`.skill-stage-${process.pid}-${Date.now()}`),i=h.join(h.dirname(n),`.skill-exclude-${process.pid}-${Date.now()}`);try{let r=await Ft(e,4),s=r.length>=4&&r[0]===80&&r[1]===75&&r[2]===3&&r[3]===4,c=s?"unzip":"tar",l=await Ie(c,s?["-Z1",e]:["-tf",e]),d=await Ie(c,s?["-Z","--h","--t",e]:["-tvf",e]),{plain:f,special:m}=At(c,l,d);Tt([...f,...m]);let S=xt(f);await I.mkdir(t,{recursive:!0,mode:Z}),f.length>0&&await Ie(c,await Dt(c,e,t,m,i)),await Ke(t);let E=S?h.join(t,S):t,F=await I.readdir(E).catch(R=>{throw Q(R)==="ENOENT"?new O(Ne):R});for(let R of F)await I.rename(h.join(E,R),h.join(n,R))}finally{await I.rm(e,{force:!0}),await I.rm(i,{force:!0}),await I.rm(t,{recursive:!0,force:!0})}}async function Dt(o,n,e,t,i){let r=t.map(s=>s.replace(/[*?[\\]/g,"\\$&"));return o==="unzip"?["-oq",n,"-d",e,...r.length>0?["-x",...r]:[]]:r.length===0?["-xf",n,"-C",e]:(await I.writeFile(i,r.join(`
|
|
6
6
|
`)+`
|
|
7
7
|
`,{flag:"wx",mode:384}),["-xf",n,"-C",e,"-X",i])}async function Ft(o,n){let e=await I.open(o,"r");try{let t=Buffer.alloc(n),{bytesRead:i}=await e.read(t,0,n,0);return t.subarray(0,i)}finally{await e.close()}}var g=L.promises,G=L.constants,Qe=448,Ct=384,Pt=448,Le=G.O_NOFOLLOW??0,Wt=G.O_NONBLOCK??0,w=(()=>{class o extends Error{constructor(e,t){super(`path ${JSON.stringify(t)} ${e}`),this.name="FileStoreError",this.reason=e,this.relPath=t}}return o.ESCAPES_ROOT="escapes the store root",o.IS_A_SYMLINK="is a symlink",o.NOT_A_FILE="is not a regular file",o.NOT_A_DIRECTORY="is not a directory",o.NOT_UTF8="is not valid utf-8",o.MOVE_DESTINATION_EXISTS="already exists",o})();function $e(o){return o.startsWith("/")&&!o.split("/").includes("..")}var Te=(()=>{class o{constructor(e,t,i=!1){this.hashes=new Map,this.rootPath=e,this.removedOnDispose=t,this.decoder=i?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(e,t){if(!Ut())throw new Error("FileStore requires O_NOFOLLOW support on this platform");let i=!1;try{await g.lstat(e)}catch(r){if(r.code!=="ENOENT")throw r;i=!0}return new o(h.resolve(e),i,t?.utf8??!1)}async createRoot(){await jt(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){this.removedOnDispose&&await g.rm(this.rootPath,{recursive:!0,force:!0})}async put(e,t,i){let r=e.replace(/\\/g,"/");if(r.endsWith("/")||r.endsWith("/.")||r===""||r===".")throw new w(w.NOT_A_FILE,e);let s=this.resolveUnderRoot(e),c=typeof t=="string"?Be(t):t;this.requireUtf8(e,c),await Xe(this.rootPath,h.dirname(s)),await Bt(s,c,i?.executable??!1)}async get(e){let t=this.resolveUnderRoot(e),i;try{i=await et(e,t)}catch(s){if(s.code==="ENOENT")return null;throw s}let r;try{let s=await i.readFile();r=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}finally{await i.close()}return this.requireUtf8(e,r),r}async ls(e="/"){let t=this.resolveUnderRoot(e);return new Set((await Je(this.rootPath,e,t)).map(([i])=>i))}async findSymlinks(e="/"){let t=this.resolveUnderRoot(e);return qt(this.rootPath,e,t)}async hashtree(e="/"){let t=this.resolveUnderRoot(e),i=de.nowNs(),r=Object.create(null);for(let[s,c]of await Je(this.rootPath,e,t)){let l=await this.hashViaCache(s,c,i);l!==null&&(r[s]=l)}return r}async hashFile(e){let t=this.resolveUnderRoot(e),i;try{i=await g.lstat(t,{bigint:!0})}catch(s){if(s.code==="ENOENT")return null;throw s}if(i.isSymbolicLink())throw new w(w.IS_A_SYMLINK,e);if(!i.isFile())throw new w(w.NOT_A_FILE,e);let r=h.relative(this.rootPath,t).split(h.sep).join("/");return this.hashViaCache(r,t,de.nowNs())}async move(e,t){let i=this.resolveUnderRoot(e),r=this.resolveUnderRoot(t);if(i===this.rootPath||r===this.rootPath)return;if(await g.stat(r).then(()=>!0,()=>!1))throw new w(w.MOVE_DESTINATION_EXISTS,t);await Xe(this.rootPath,h.dirname(r)),await g.rename(i,r)}async remove(e){let t=this.resolveUnderRoot(e);if(t===this.rootPath)return;let i;try{i=await g.lstat(t,{bigint:!0})}catch(r){if(r.code==="ENOENT")return;throw r}if(i.isDirectory())await g.rm(t,{recursive:!0,force:!0});else try{await g.unlink(t)}catch(r){if(r.code!=="ENOENT")throw r}}resolveUnderRoot(e){let t=e.replace(/\\/g,"/").replace(/^\/+/,""),i=t.split("/").filter(r=>r!==""&&r!==".");if(h.posix.isAbsolute(t)||i.includes(".."))throw new w(w.ESCAPES_ROOT,e);return i.length===0?this.rootPath:h.join(this.rootPath,...i)}requireUtf8(e,t){if(this.decoder)try{this.decoder.decode(t)}catch{throw new w(w.NOT_UTF8,e)}}async hashViaCache(e,t,i){let r;try{r=await g.lstat(t,{bigint:!0})}catch(l){if(l.code==="ENOENT")return null;throw l}if(!r.isFile())return null;let s=this.hashes.get(e),c;if(s!==void 0&&Gt(s,r))c=s.sha;else try{c=await de.hashFile(t)}catch(l){let d=l.code;if(d==="ENOENT"||l instanceof w||d==="ELOOP"||d==="EMLINK")return null;throw l}return Ht(r,i)&&this.hashes.set(e,{mtimeNs:r.mtimeNs,ctimeNs:r.ctimeNs,size:r.size,sha:c}),c}}return o.isPathLegal=$e,o})();function Ut(){return Le!==0}async function jt(o){let n=[],e=o;for(;;){try{await g.stat(e);break}catch(i){let r=i.code;if(r!=="ENOENT"&&r!=="ENOTDIR"&&r!=="ELOOP")throw i}n.push(e);let t=h.dirname(e);if(t===e)break;e=t}for(let t of n.reverse())try{await g.mkdir(t,{mode:Qe})}catch(i){if(i.code!=="EEXIST")throw i}}async function Xe(o,n){let e=h.relative(o,n);if(e==="")return;let t=o;for(let i of e.split(h.sep)){t=h.join(t,i);try{await g.mkdir(t,{mode:Qe})}catch(r){if(r.code!=="EEXIST")throw r}}}async function Bt(o,n,e){let t=e?Pt:Ct,i=h.join(h.dirname(o),`.fs-${C.randomBytes(8).toString("hex")}.tmp`),r;try{r=await g.open(i,G.O_WRONLY|G.O_CREAT|G.O_EXCL|Le,t),await r.writeFile(n),await r.close(),r=void 0,await g.rename(i,o)}catch(s){throw r&&await r.close().catch(()=>{}),await g.unlink(i).catch(()=>{}),s}}async function et(o,n){let e;try{e=await g.open(n,G.O_RDONLY|Le|Wt)}catch(t){let i=t.code;throw i==="ELOOP"||i==="EMLINK"?new w(w.IS_A_SYMLINK,o):t}try{if(!(await e.stat()).isFile())throw new w(w.NOT_A_FILE,o)}catch(t){throw await e.close().catch(()=>{}),t}return e}async function Yt(o){let n=C.createHash("sha256"),e=await et(h.basename(o),o),t=new Uint8Array(1024*1024);try{for(;;){let{bytesRead:i}=await e.read(t,0,t.length);if(i===0)break;n.update(t.subarray(0,i))}}finally{await e.close()}return n.digest("hex")}async function Je(o,n,e){if(!await zt(n,e))return[];let t=[];return await tt(e,(i,r)=>{r.isFile()&&t.push([h.relative(o,i).split(h.sep).join("/"),i])}),t.sort(),t}async function qt(o,n,e){let t=s=>h.relative(o,s).split(h.sep).join("/"),i;try{i=await g.lstat(e,{bigint:!0})}catch(s){let c=s.code;if(c==="ENOENT"||c==="ENOTDIR")return new Set;throw s}if(i.isSymbolicLink())return new Set([t(e)]);if(!i.isDirectory())throw new w(w.NOT_A_DIRECTORY,n);let r=new Set;return await tt(e,(s,c)=>{c.isSymbolicLink()&&r.add(t(s))}),r}async function zt(o,n){let e;try{e=await g.lstat(n,{bigint:!0})}catch(t){let i=t.code;if(i==="ENOENT"||i==="ENOTDIR")return!1;throw t}if(!e.isDirectory())throw new w(w.NOT_A_DIRECTORY,o);return!0}async function tt(o,n){let e=[o];for(;e.length;){let t=e.pop(),i;try{i=await g.readdir(t,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")continue;throw r}for(let r of i){let s=h.join(t,r.name);n(s,r),r.isDirectory()&&!r.isSymbolicLink()&&e.push(s)}}}function Gt(o,n){return n.mtimeNs===o.mtimeNs&&n.ctimeNs===o.ctimeNs&&n.size===o.size}function Ht(o,n){return(o.mtimeNs>o.ctimeNs?o.mtimeNs:o.ctimeNs)<n-de.timestampTrustMarginNs}var Kt=2000000000n,de={hashFile:Yt,timestampTrustMarginNs:Kt,nowNs:()=>BigInt(Date.now())*1000000n},rt=Te,Ze=Symbol.asyncDispose;Ze&&Object.defineProperty(Te.prototype,Ze,{value:Te.prototype.dispose,configurable:!0,writable:!0});var _,$,he,ee,me,y,H,ue,A,it,pe,nt,ot,Ae,xe,st,at,De,ct,lt,ye,we,ft,dt,Vt=3e4,V=".anthropic-memory-store",mt=1;function ht(o){return C.createHash("sha256").update(`version ${mt}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
2
|
const require = __cortexCreateRequire(import.meta.url);
|
|
3
3
|
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as _,b as w}from"./chunk-XBJOYU5Y.js";import{a as m}from"./chunk-XAXWLYH5.js";import"./chunk-IRWZ7UPF.js";import{a as
|
|
4
|
+
import{a as y}from"./chunk-ILEML5IP.js";import{a as _,b as w}from"./chunk-XBJOYU5Y.js";import{a as m}from"./chunk-XAXWLYH5.js";import"./chunk-IRWZ7UPF.js";import{a as f}from"./chunk-6R73ICDB.js";import"./chunk-WHC7AYZD.js";var l=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&import("node:crypto").then(e=>{l=e.randomBytes});var d="app_EMoamEEZ73f0CkXaXp7hrann",i="https://auth.openai.com",x=`${i}/oauth/authorize`,O=`${i}/oauth/token`,h="http://localhost:1455/auth/callback",S=`${i}/api/accounts/deviceauth/usercode`,T=`${i}/api/accounts/deviceauth/token`,b=`${i}/codex/device`,P=`${i}/deviceauth/callback`,E=900,C="browser",g="device_code",k="openid profile email offline_access",R="https://api.openai.com/auth";function D(){return f("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1"}function U(){if(!l)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");return l(16).toString("hex")}function N(e){let t=e.trim();if(!t)return{};try{let r=new URL(t);return{code:r.searchParams.get("code")??void 0,state:r.searchParams.get("state")??void 0}}catch{}if(t.includes("#")){let[r,o]=t.split("#",2);return{code:r,state:o}}if(t.includes("code=")){let r=new URLSearchParams(t);return{code:r.get("code")??void 0,state:r.get("state")??void 0}}return{code:t}}function $(e){try{let t=e.split(".");if(t.length!==3)return null;let r=t[1]??"",o=atob(r);return JSON.parse(o)}catch{return null}}async function p(e,t){try{return await fetch(e,t)}catch(r){throw t.signal?.aborted?new Error("Login cancelled"):r}}async function I(e,t){if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`OpenAI Codex token ${t} failed (${e.status}): ${n||e.statusText}`)}let o=await e.json();if(!o?.access_token||!o.refresh_token||typeof o.expires_in!="number")throw new Error(`OpenAI Codex token ${t} response missing fields: ${JSON.stringify(o)}`);return{access:o.access_token,refresh:o.refresh_token,expires:Date.now()+o.expires_in*1e3}}async function L(e,t,r,o){let n=await p(O,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:d,code:e,code_verifier:t,redirect_uri:r}),signal:o});return I(n,"exchange")}async function J(e,t){let r;try{r=await fetch(O,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:d}),signal:t})}catch(o){throw new Error(`OpenAI Codex token refresh error: ${o instanceof Error?o.message:String(o)}`)}return I(r,"refresh")}async function z(e){let t=await p(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:d}),signal:e});if(!t.ok){if(t.status===404)throw new Error("OpenAI Codex device code login is not enabled for this server. Use browser login or verify the server URL.");let a=await t.text().catch(()=>"");throw new Error(`OpenAI Codex device code request failed with status ${t.status}${a?`: ${a}`:""}`)}let o=await t.json(),n=typeof o?.interval=="string"?Number(o.interval.trim()):o?.interval;if(!o?.device_auth_id||!o.user_code||typeof n!="number"||!Number.isFinite(n)||n<0)throw new Error(`Invalid OpenAI Codex device code response: ${JSON.stringify(o)}`);return{deviceAuthId:o.device_auth_id,userCode:o.user_code,intervalSeconds:n}}async function j(e,t){return y({intervalSeconds:e.intervalSeconds,expiresInSeconds:E,signal:t,poll:async()=>{let r=await p(T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_auth_id:e.deviceAuthId,user_code:e.userCode}),signal:t});if(r.ok){let s=await r.json();return!s?.authorization_code||!s.code_verifier?{status:"failed",message:`Invalid OpenAI Codex device auth token response: ${JSON.stringify(s)}`}:{status:"complete",value:{authorizationCode:s.authorization_code,codeVerifier:s.code_verifier}}}if(r.status===403||r.status===404)return{status:"pending"};let o=await r.text().catch(()=>""),n;try{let s=JSON.parse(o)?.error;n=typeof s=="object"?s?.code:s}catch{}return n==="deviceauth_authorization_pending"?{status:"pending"}:n==="slow_down"?{status:"slow_down"}:{status:"failed",message:`OpenAI Codex device auth failed with status ${r.status}${o?`: ${o}`:""}`}}})}async function V(e="pi"){let{verifier:t,challenge:r}=await m(),o=U(),n=new URL(x);return n.searchParams.set("response_type","code"),n.searchParams.set("client_id",d),n.searchParams.set("redirect_uri",h),n.searchParams.set("scope",k),n.searchParams.set("code_challenge",r),n.searchParams.set("code_challenge_method","S256"),n.searchParams.set("state",o),n.searchParams.set("id_token_add_organizations","true"),n.searchParams.set("codex_cli_simplified_flow","true"),n.searchParams.set("originator",e),{verifier:t,state:o,url:n.toString()}}function B(e){let o=$(e)?.[R]?.chatgpt_account_id;return typeof o=="string"&&o.length>0?o:null}function v(e){let t=B(e.access);if(!t)throw new Error("Failed to extract accountId from token");return{type:"oauth",access:e.access,refresh:e.refresh,expires:e.expires,accountId:t}}async function A(e,t,r,o){return v(await L(e,t,r,o))}async function F(e){let t=await z(e.signal);e.notify({type:"device_code",userCode:t.userCode,verificationUri:b,intervalSeconds:t.intervalSeconds,expiresInSeconds:E});let r=await j(t,e.signal);return A(r.authorizationCode,r.codeVerifier,P,e.signal)}async function H(e,t){let{verifier:r,state:o,url:n}=await V(t?.agentName),a=await _({providerName:"OpenAI",host:D(),port:1455,path:"/auth/callback",state:o,complete:async s=>s,signal:e.signal}).catch(()=>{});e.notify({type:"auth_url",url:n,instructions:"A browser window should open. Complete login to finish."});try{let s=await w(e,a,{message:"Complete login in your browser, or paste the authorization code / redirect URL here:",placeholder:h}),c;if(s.type==="callback")c=s.value;else{let u=N(s.input);if(u.state&&u.state!==o)throw new Error("State mismatch");c=u.code}if(!c)throw new Error("Missing authorization code");return await A(c,r,h,e.signal)}finally{a?.close()}}async function M(e,t){return v(await J(e,t))}var Z={name:"OpenAI (ChatGPT Plus/Pro)",isSubscription:!0,async login(e,t){let r=await e.prompt({type:"select",message:"Select OpenAI Codex login method:",options:[{id:C,label:"Browser login (default)"},{id:g,label:"Device code login (headless)"}]});if(r===g)return F(e);if(r!==C)throw new Error(`Unknown OpenAI Codex login method: ${r}`);return H(e,t)},refresh:(e,t)=>M(e.refresh,t),async toAuth(e){return{apiKey:e.access}}};export{Z as openaiCodexOAuth};
|
|
@@ -0,0 +1,12 @@
|
|
|
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 ce}from"./chunk-5F3A62YS.js";import{a as he}from"./chunk-DQJ6LLAS.js";import{a as me,b as H,c as ye,d as K}from"./chunk-FE7HH5JS.js";import{a as pe}from"./chunk-XIECJESP.js";import{a as be}from"./chunk-ZSV6TO7Q.js";import"./chunk-V3AQJSWR.js";import{a as ae}from"./chunk-OIV4DIMB.js";import"./chunk-BWDJS6A4.js";import"./chunk-6R73ICDB.js";import{h as de,k as le}from"./chunk-7TYSMLUV.js";import{C as se,I as ie,o as re,v as ne,z as oe}from"./chunk-DE5EGVKG.js";import{a as q,c as Q,d as ee}from"./chunk-D6VMBA4C.js";import"./chunk-USBJFDJ6.js";import{a as ue,c as fe}from"./chunk-ZD4O6NPV.js";import{a as J}from"./chunk-K4NTZEDJ.js";import{h as te}from"./chunk-3XLHL5YT.js";import"./chunk-X2TKJ7KR.js";import"./chunk-NW4GW47L.js";import{b as Z}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var Be="https://chatgpt.com/backend-api",Pe="https://api.openai.com/auth",Ie=0,we=1e3,Fe=6e4,Ue=15e3,$e=3,ve=new Set(["openai","openai-codex","opencode"]),ze=1009,Je="websocket_connection_limit_reached",He="previous_response_not_found",Ke=16,Ge="medium",je=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function ge(e){if(e.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(e.stopReason==="error"||e.stopReason==="aborted")throw new Error(e.errorMessage||"An unknown error occurred")}function Ve(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function Xe(e,r){return e===429&&Ve(r)?!1:e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(r)}function Ye(e){let r=e.get("retry-after-ms");if(r!==null){let s=Number(r);if(Number.isFinite(s))return Math.max(0,s)}let t=e.get("retry-after");if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*1e3);let i=Date.parse(t);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}var F=class extends Error{};function Ze(e,r){let t=r?.maxRetryDelayMs??Fe;if(t>0&&e>t)throw new F(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(t/1e3)}s)`);return e}function Ee(e,r){return new Promise((t,n)=>{if(r?.aborted){n(new Error("Request was aborted"));return}let i=()=>{clearTimeout(s),n(new Error("Request was aborted"))},s=setTimeout(()=>{r?.removeEventListener("abort",i),t()},e);r?.addEventListener("abort",i,{once:!0})})}function Se(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function Qe(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function et(e){let r=Qe();if(!r||typeof r.zstdCompressSync!="function")return null;try{let t=r.zstdCompressSync(e,{params:{[r.constants.ZSTD_c_compressionLevel]:$e}});return new Uint8Array(t)}catch{return null}}var tt=(e,r,t)=>{let n=new Z,i=ne(r,e.compat?.supportsMidConvoSystemMessages);return(async()=>{let s=rt(e,t),o={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,...s===void 0?{}:{providerThinkingLevel:s},usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let c=t?.apiKey;if(!c)throw new Error(`No API key for provider: ${e.provider}`);let a=Mt(c),p=de(oe(i.messages),e.compat?.supportsOpenAIGrammarTools??!1),d=t?.cacheRetention==="none"?void 0:t?.sessionId,u=pe(d),f=nt(e,i,t,u,p,s),l=await t?.onPayload?.(f,e);l!==void 0&&(f=l);let m=u||ce(),h={originator:"pi",...te(e,t?.identity)},g=Lt(h,e.headers,t?.headers,a,c,u),x=Wt(h,e.headers,t?.headers,a,c,m),y=JSON.stringify(f),S=Se(t?.timeoutMs),C=Se(t?.websocketConnectTimeoutMs),b=t?.transport||"auto",T=!1,O=b!=="sse"&&Me(d);if(O&&_e(d),b!=="sse"&&!O){let E=!1,k=!1,A=!1;for(;;){E=!1;try{if(await Ot(st(e.baseUrl),f,x,o,n,e,()=>{E=!0,T||(T=!0,n.push({type:"start",partial:o}))},S,C,d,a,p,t),t?.signal?.aborted)throw new Error("Request was aborted");ge(o),n.push({type:"done",reason:o.stopReason,message:o}),n.end();return}catch(v){let N=t?.signal?.aborted,D=!E&&ct(v),L=ut(v);if(!N&&L&&!A){A=!0;continue}if(!N&&D&&!k){k=!0;continue}if(N||at(v)&&!D||(ee(o,Q("provider_transport_failure",v,{configuredTransport:b,...E?{}:{fallbackTransport:"sse"},eventsEmitted:E,phase:E?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(y).byteLength})),ht(d,v),E))throw v;_e(d);break}}}let Y=et(y);Y&&g.set("content-encoding","zstd");let De=Y??y,_,W,z=t?.maxRetries??Ie;for(let E=0;E<=z;E++){if(t?.signal?.aborted)throw new Error("Request was aborted");try{let k=S!==void 0&&S>0?AbortSignal.timeout(S):void 0,A=he([t?.signal,k]);try{_=await(t?.fetch??globalThis.fetch)(Oe(e.baseUrl),{method:"POST",headers:g,body:De,signal:A.signal})}catch(L){throw k?.aborted&&!t?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${S}ms`):L}finally{A.cleanup()}if(await t?.onResponse?.({status:_.status,headers:J(_.headers)},e),_.ok)break;let v=await _.text();if(E<z&&Xe(_.status,v)){let L=Ye(_.headers),qe=L===void 0?we*2**E:Ze(L,t);await Ee(qe,t?.signal);continue}let N=new Response(v,{status:_.status,statusText:_.statusText}),D=await At(N);throw new Error(D.friendlyMessage||D.message)}catch(k){if(k instanceof Error&&(k.name==="AbortError"||k.message==="Request was aborted"))throw new Error("Request was aborted");if(W=k instanceof Error?k:new Error(String(k)),E<z&&!(W instanceof F)&&!W.message.includes("usage limit")){let A=we*2**E;await Ee(A,t?.signal);continue}throw W}}if(!_?.ok)throw W??new Error("Failed after retries");if(!_.body)throw new Error("No response body");if(T||(T=!0,n.push({type:"start",partial:o})),await it(_,o,n,e,p,t),t?.signal?.aborted)throw new Error("Request was aborted");ge(o),n.push({type:"done",reason:o.stopReason,message:o}),n.end()}catch(c){o.stopReason=t?.signal?.aborted?"aborted":"error",o.errorMessage=fe(ue(c)),n.push({type:"error",reason:o.stopReason,error:o}),n.end()}})(),n},Vt=(e,r,t)=>{let n=t?.apiKey;if(!n)throw new Error(`No API key for provider: ${e.provider}`);let i={...le(e,r,t,n),toolChoice:t?.toolChoice},s=t?.reasoning?ie(e,t.reasoning):"off",o=s!=="off"?s:e.reasoning?"none":void 0;return tt(e,r,{...i,reasoningEffort:o})};function rt(e,r){if(!(!e.compat?.supportsMidConvoEffort||r?.reasoningEffort===void 0))return Re(e,r.reasoningEffort)??void 0}function Re(e,r){return r==="none"?e.thinkingLevelMap?.off===void 0?"none":e.thinkingLevelMap.off:e.thinkingLevelMap?.[r]??r}function nt(e,r,t,n,i,s){let o=e.compat?.supportsStrictMode??!0,c=e.compat?.supportsOpenAIGrammarTools??!1,a=e.compat?.supportsAdditionalTools??!1,p=e.compat?.supportsToolSearch??!1,d=se(r.messages,me({supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:a,supportsToolSearch:p})),u=H(e,r,ve,{grammarToolInputProperties:i,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:a,supportsToolSearch:p,toolOptions:{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:c},configurationUpdateEffort:s}),f={model:e.id,store:!1,stream:!0,input:u,text:{verbosity:t?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:t?.toolChoice??"auto",parallel_tool_calls:!0};if(t?.maxTokens&&(e.compat?.supportsMaxOutputTokens??!0)&&(f.max_output_tokens=Math.max(t.maxTokens,Ke)),t?.temperature!==void 0&&(f.temperature=t.temperature),t?.serviceTier!==void 0&&(f.service_tier=t.serviceTier),d.requestTools.length>0&&(f.tools=ye(d.requestTools,{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:c})),t?.reasoningEffort!==void 0){let l=s===void 0?Re(e,t.reasoningEffort):Ge;l!==null&&(f.reasoning={effort:l,summary:t.reasoningSummary??"auto"})}else e.reasoning&&e.thinkingLevelMap?.off!==null&&(f.reasoning={effort:e.thinkingLevelMap?.off??"none"});return f}function ot(e,r){switch(r){case"flex":return .5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function xe(e,r,t){let n=ot(t,r);n!==1&&(e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function Ce(e,r){return e==="default"&&(r==="flex"||r==="priority")?r:e??r}function Oe(e){let t=(e&&e.trim().length>0?e:Be).replace(/\/+$/,"");return t.endsWith("/codex/responses")?t:t.endsWith("/codex")?`${t}/responses`:`${t}/codex/responses`}function st(e){let r=new URL(Oe(e));return r.protocol==="https:"&&(r.protocol="wss:"),r.protocol==="http:"&&(r.protocol="ws:"),r.toString()}async function it(e,r,t,n,i,s){await K(Ae(lt(e,s?.signal),r,n,s?.onProviderStreamEvent),r,t,n,{serviceTier:s?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:Ce,applyServiceTierPricing:(o,c)=>xe(o,c,n)})}var M=class extends Error{code;payload;constructor(r,t){super(r),this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},B=class extends Error{payload;constructor(r,t){super(r),this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}},U=class extends Error{constructor(r){super(q(r)),this.name="ProviderStreamEventCallbackError",this.cause=r}};function at(e){return e instanceof M||e instanceof B||e instanceof U}function ct(e){return e instanceof M&&e.code===Je}function ut(e){return e instanceof M&&e.code===He}function ft(e){let r=e.error&&typeof e.error=="object"?e.error:void 0;return{code:typeof e.code=="string"?e.code:typeof r?.code=="string"?r.code:void 0,message:typeof e.message=="string"?e.message:typeof r?.message=="string"?r.message:void 0}}async function*Ae(e,r,t,n){for await(let i of e){try{await n?.(i,t)}catch(o){throw new U(o)}let s=typeof i.type=="string"?i.type:void 0;if(s){if(s==="error"){let{code:o,message:c}=ft(i);throw new M(`Codex error: ${c||o||JSON.stringify(i)}`,{code:o,payload:i})}if(s==="response.failed"){let o=i.response,c=o?.error?.code,a=o?.error?.message;throw new M(a||"Codex response failed",{code:c,payload:i})}if(s==="response.done"||s==="response.completed"||s==="response.incomplete"){let o=i.response;typeof o?.end_turn=="boolean"&&(r.endTurn=o.end_turn);let c=o&&{...o,status:dt(o.status)};yield{...i,type:"response.completed",response:c};return}yield i}}}function dt(e){if(typeof e=="string")return je.has(e)?e:void 0}async function*lt(e,r){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,i="",s=()=>{t.cancel().catch(()=>{})};r?.addEventListener("abort",s,{once:!0});try{for(;;){if(r?.aborted)throw new Error("Request was aborted");let{done:o,value:c}=await t.read();if(r?.aborted)throw new Error("Request was aborted");i+=o?n.decode():n.decode(c,{stream:!0}),o&&i.trim()&&(i+=`
|
|
5
|
+
|
|
6
|
+
`);let a=i.indexOf(`
|
|
7
|
+
|
|
8
|
+
`);for(;a!==-1;){let p=i.slice(0,a);i=i.slice(a+2);let d=p.split(`
|
|
9
|
+
`).filter(u=>u.startsWith("data:")).map(u=>u.slice(5).trim());if(d.length>0){let u=d.join(`
|
|
10
|
+
`).trim();if(u&&u!=="[DONE]")try{yield JSON.parse(u)}catch(f){throw new B(`Invalid Codex SSE JSON: ${q(f)}`,{cause:f,payload:u})}}a=i.indexOf(`
|
|
11
|
+
|
|
12
|
+
`)}if(o)break}}finally{r?.removeEventListener("abort",s);try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}var pt="responses_websockets=2026-02-06",mt=300*1e3,yt=2700*1e3,w=new Map,P=new Map,$=new Set;function X(e){let r=P.get(e);return r||(r={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},P.set(e,r)),r}function Xt(e){let r=P.get(e);return r?{...r}:void 0}function Yt(e){if(e){P.delete(e),$.delete(e);return}P.clear(),$.clear()}function bt(e){let r=t=>{t.idleTimer&&clearTimeout(t.idleTimer),R(t.socket,1e3,"debug_close")};if(e){for(let t of w.get(e)?.values()??[])r(t);w.delete(e);return}for(let t of w.values())for(let n of t.values())r(n);w.clear()}ae(bt);function Me(e){return e?$.has(e):!1}function _e(e){if(!e)return;let r=X(e);r.sseFallbacks++,r.websocketFallbackActive=Me(e)}function ht(e,r){if(!e)return;$.add(e);let t=X(e);t.websocketFailures++,t.lastWebSocketError=q(r),t.websocketFallbackActive=!0}var G=null;async function wt(e){if(!e&&G)return G;if(typeof process<"u"&&process.versions?.bun){let t=class extends WebSocket{constructor(n,i){let s={};Array.isArray(i)||typeof i=="string"?s={protocols:i}:s={...i};let o=be(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...s,...o?{proxy:o.toString()}:{}})}};return e||(G=t),t}let r=globalThis.WebSocket;return typeof r!="function"?null:r}var V=class extends Error{code;reason;wasClean;constructor(r,t){super(r),this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function gt(e){let r=e.readyState;return typeof r=="number"?r:void 0}function I(e){let r=gt(e);return r===void 0||r===1}function Et(e){return Date.now()-e.createdAt>=yt}function R(e,r=1e3,t="done"){try{e.close(r,t)}catch{}}function ke(e,r,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{if(t.busy)return;R(t.socket,1e3,"idle_timeout");let n=w.get(e);n?.get(r)===t&&n.delete(r),n?.size===0&&w.delete(e)},mt)}async function j(e,r,t,n=Ue,i){let s=await wt(i);if(!s)throw new Error("WebSocket transport is not available in this runtime");let o=J(r);return delete o["OpenAI-Beta"],new Promise((c,a)=>{let p=!1,d,u;try{u=new s(e,{headers:o})}catch(y){a(y instanceof Error?y:new Error(String(y)));return}let f=()=>{d&&(clearTimeout(d),d=void 0),u.removeEventListener("open",m),u.removeEventListener("error",h),u.removeEventListener("close",g),t?.removeEventListener("abort",x)},l=(y,S)=>{p||(p=!0,f(),S&&R(u,1e3,S),a(y))},m=()=>{p||(p=!0,f(),c(u))},h=y=>{l(Le(y))},g=y=>{l(We(y))},x=()=>{l(new Error("Request was aborted"),"aborted")};u.addEventListener("open",m),u.addEventListener("error",h),u.addEventListener("close",g),t?.addEventListener("abort",x),n>0&&(d=setTimeout(()=>{l(new Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n)),t?.aborted&&x()})}async function St(e,r,t,n,i,s,o){if(!t){let u=await j(e,r,i,s,o);return{socket:u,reused:!1,release:()=>R(u)}}let c=w.get(t),a=c?.get(n);if(a){if(a.idleTimer&&(clearTimeout(a.idleTimer),a.idleTimer=void 0),!a.busy&&Et(a))R(a.socket,1e3,"connection_age_limit"),c?.delete(n),c?.size===0&&w.delete(t);else if(!a.busy&&I(a.socket))return a.busy=!0,{socket:a.socket,entry:a,reused:!0,release:({keep:u}={})=>{if(!u||!I(a.socket)){R(a.socket);let f=w.get(t);f?.get(n)===a&&f.delete(n),f?.size===0&&w.delete(t);return}a.busy=!1,ke(t,n,a)}};if(a.busy){let u=await j(e,r,i,s,o);return{socket:u,reused:!1,release:()=>{R(u)}}}I(a.socket)||(R(a.socket),c?.delete(n),c?.size===0&&w.delete(t))}let p=await j(e,r,i,s,o),d={socket:p,busy:!0,createdAt:Date.now()};return c=w.get(t),c||(c=new Map,w.set(t,c)),c.set(n,d),{socket:p,entry:d,reused:!1,release:({keep:u}={})=>{if(!u||!I(d.socket)){R(d.socket),d.idleTimer&&clearTimeout(d.idleTimer);let f=w.get(t);f?.get(n)===d&&f.delete(n),f?.size===0&&w.delete(t);return}d.busy=!1,ke(t,n,d)}}}function Le(e){if(e&&typeof e=="object"){let r="message"in e?e.message:void 0;if(typeof r=="string"&&r.length>0)return new Error(r);let t="error"in e?e.error:void 0;if(t instanceof Error&&t.message.length>0)return t;if(t&&typeof t=="object"&&"message"in t){let n=t.message;if(typeof n=="string"&&n.length>0)return new Error(n)}}return new Error("WebSocket error")}function We(e){if(e&&typeof e=="object"){let r="code"in e?e.code:void 0,t="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,i=typeof r=="number"?` ${r}`:"",s=typeof t=="string"&&t.length>0?` ${t}`:"";return!s&&r===ze&&(s=" message too big"),new V(`WebSocket closed${i}${s}`.trim(),{code:typeof r=="number"?r:void 0,reason:typeof t=="string"&&t.length>0?t:void 0,wasClean:typeof n=="boolean"?n:void 0})}return new Error("WebSocket closed")}async function _t(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let r=e;return new TextDecoder().decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}if(e&&typeof e=="object"&&"arrayBuffer"in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*kt(e,r,t){let n=[],i=null,s=!1,o=null,c=!1,a=()=>{if(!i)return;let l=i;i=null,l()},p=l=>{(async()=>{let m=null;try{if(!l||typeof l!="object"||!("data"in l)||(m=await _t(l.data),!m))return;let h=JSON.parse(m),g=typeof h.type=="string"?h.type:"";(g==="response.completed"||g==="response.done"||g==="response.incomplete")&&(c=!0,s=!0),n.push(h),a()}catch(h){o=new B(`Invalid Codex WebSocket JSON: ${q(h)}`,{cause:h,payload:m}),s=!0,a()}})()},d=l=>{o=Le(l),s=!0,a()},u=l=>{if(c){s=!0,a();return}o||(o=We(l)),s=!0,a()},f=()=>{o=new Error("Request was aborted"),s=!0,a()};e.addEventListener("message",p),e.addEventListener("error",d),e.addEventListener("close",u),r?.addEventListener("abort",f);try{for(;;){if(r?.aborted)throw new Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(s)break;let l;await new Promise((m,h)=>{i=m,t!==void 0&&t>0&&(l=setTimeout(()=>{let g=new Error(`WebSocket idle timeout after ${t}ms`);o=g,s=!0,i=null,R(e,1e3,"idle_timeout"),h(g)},t))}).finally(()=>{l&&clearTimeout(l)})}if(o)throw o;if(!c)throw new Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",p),e.removeEventListener("error",d),e.removeEventListener("close",u),r?.removeEventListener("abort",f)}}function Te(e){let{input:r,previous_response_id:t,...n}=e;return n}function Tt(e,r){return JSON.stringify(e??[])===JSON.stringify(r??[])}function vt(e,r){return JSON.stringify(Te(e))===JSON.stringify(Te(r))}function Rt(e,r){if(!vt(e,r.lastRequestBody))return;let t=e.input??[],n=[...r.lastRequestBody.input??[],...r.lastResponseItems];if(t.length<n.length)return;let i=t.slice(0,n.length);if(Tt(i,n))return t.slice(n.length)}function xt(e,r){let t=e.continuation;if(!t)return r;let n=Rt(r,t);return!n||!t.lastResponseId?(e.continuation=void 0,r):{...r,previous_response_id:t.lastResponseId,input:n}}async function*Ct(e,r){let t=!1;for await(let n of e)t||(t=!0,r()),yield n}async function Ot(e,r,t,n,i,s,o,c,a,p,d,u,f){let{socket:l,entry:m,reused:h,release:g}=await St(e,t,p,d,f?.signal,a,f?.env),x=!0,y=f?.transport==="websocket-cached"||f?.transport==="auto",S=r,C=y&&m?xt(m,S):S,b=p?X(p):void 0;b&&(b.requests++,h?b.connectionsReused++:b.connectionsCreated++,y&&b.cachedContextRequests++,C.store===!0&&b.storeTrueRequests++,b.lastInputItems=C.input?.length??0,C.previous_response_id?(b.deltaRequests++,b.lastDeltaInputItems=C.input?.length??0,b.lastPreviousResponseId=C.previous_response_id):(b.fullContextRequests++,b.lastDeltaInputItems=void 0,b.lastPreviousResponseId=void 0));try{if(l.send(JSON.stringify({type:"response.create",...C})),await K(Ct(Ae(kt(l,f?.signal,c),n,s,f?.onProviderStreamEvent),o),n,i,s,{serviceTier:f?.serviceTier,grammarToolInputProperties:u,resolveServiceTier:Ce,applyServiceTierPricing:(T,O)=>xe(T,O,s)}),f?.signal?.aborted)x=!1;else if(y&&m&&n.responseId){let T=H(s,re({messages:[n]}),ve,{grammarToolInputProperties:u}).filter(O=>O.type!=="function_call_output"&&O.type!=="custom_tool_call_output");m.continuation={lastRequestBody:S,lastResponseId:n.responseId,lastResponseItems:T}}}catch(T){throw m&&(m.continuation=void 0),x=!1,T}finally{g({keep:x})}}async function At(e){let r=await e.text(),t=r||e.statusText||"Request failed",n;try{let s=JSON.parse(r)?.error;if(s){let o=s.code||s.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(o)||e.status===429){let c=s.plan_type?` (${s.plan_type.toLowerCase()} plan)`:"",a=s.resets_at?Math.max(0,Math.round((s.resets_at*1e3-Date.now())/6e4)):void 0,p=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${c}.${p}`.trim()}t=s.message||n||t}}catch{}return{message:t,friendlyMessage:n}}function Mt(e){try{let r=e.split(".");if(r.length!==3)throw new Error("Invalid token");let n=JSON.parse(atob(r[1]))?.[Pe]?.chatgpt_account_id;if(!n)throw new Error("No account ID in token");return n}catch{throw new Error("Failed to extract accountId from token")}}function Ne(e,r,t,n,i){let s=new Headers(e);for(let[o,c]of Object.entries(r||{}))s.set(o,c);for(let[o,c]of Object.entries(t||{}))c===null?s.delete(o):s.set(o,c);return s.set("Authorization",`Bearer ${i}`),s.set("chatgpt-account-id",n),s}function Lt(e,r,t,n,i,s){let o=Ne(e,r,t,n,i);return o.set("OpenAI-Beta","responses=experimental"),o.set("accept","text/event-stream"),o.set("content-type","application/json"),s&&(o.set("session-id",s),o.set("x-client-request-id",s)),o}function Wt(e,r,t,n,i,s){let o=Ne(e,r,t,n,i);return o.delete("accept"),o.delete("content-type"),o.delete("OpenAI-Beta"),o.delete("openai-beta"),o.set("OpenAI-Beta",pt),o.set("x-client-request-id",s),o.set("session-id",s),o}export{bt as closeOpenAICodexWebSocketSessions,Xt as getOpenAICodexWebSocketDebugStats,Yt as resetOpenAICodexWebSocketDebugStats,tt as stream,Vt as streamSimple};
|
|
@@ -0,0 +1,9 @@
|
|
|
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 ve}from"./chunk-XIECJESP.js";import{a as _e}from"./chunk-4SWD4JMP.js";import{a as ie,b as ae}from"./chunk-UPQVWHZ3.js";import{a as he,b as me}from"./chunk-BGYR4ID3.js";import{a as oe}from"./chunk-V3AQJSWR.js";import{f as te}from"./chunk-BWDJS6A4.js";import{a as ee}from"./chunk-6R73ICDB.js";import{a as ue}from"./chunk-23PRJECN.js";import{b as fe,c as le,d as ce,e as pe,f as ge,g as de,h as H,j as ye,k as ke,m as Te,n as Re,q as xe}from"./chunk-7TYSMLUV.js";import{C as j,G as X,I as Y,v as z,z as G}from"./chunk-DE5EGVKG.js";import"./chunk-D6VMBA4C.js";import{a as q}from"./chunk-USBJFDJ6.js";import{a as ne,c as se}from"./chunk-ZD4O6NPV.js";import{a as re}from"./chunk-K4NTZEDJ.js";import{h as Q}from"./chunk-3XLHL5YT.js";import{b as U,c as Z}from"./chunk-X2TKJ7KR.js";import"./chunk-NW4GW47L.js";import{b as V}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";function Ce(e,n){if(!e)return!1;let t=n.toLowerCase();for(let[s,a]of Object.entries(e))if(s.toLowerCase()===t&&a!==null&&a.trim().length>0)return!0;return!1}function Ie(e,n,t){if(n)return n;if(Ce(t,"authorization")||Ce(t,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${e}`)}function Be(e){for(let n of e)if(n.role==="toolResult"||n.role==="assistant"&&n.content.some(t=>t.type==="toolCall"))return!0;return!1}function Me(e){return e.type==="text"}function Le(e){return e.type==="thinking"}function Ne(e){return e.type==="toolCall"}function De(e){return e.type==="image"}function ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e){return(e.id===void 0||e.id===null||typeof e.id=="string")&&(e.format===void 0||typeof e.format=="string")&&(e.index===void 0||typeof e.index=="number")}function K(e){if(!ze(e)||!Ge(e))return!1;switch(e.type){case"reasoning.summary":return typeof e.summary=="string";case"reasoning.encrypted":return typeof e.data=="string";case"reasoning.text":return typeof e.text=="string"&&(e.signature===void 0||e.signature===null||typeof e.signature=="string");default:return!1}}function je(e){if(e)try{let n=JSON.parse(e);return Array.isArray(n)&&n.length>0&&n.every(K)?n:void 0}catch{return}}function He(e){if(e)try{let n=JSON.parse(e);return K(n)&&n.type==="reasoning.encrypted"&&typeof n.id=="string"&&n.id.length>0&&n.data.length>0?n:void 0}catch{return}}function Ae(e,n){e.id??=n.id,e.format||=n.format,e.index??=n.index}function Ke(e,n){let t=e[e.length-1];if(n.type==="reasoning.text"&&t?.type==="reasoning.text"){t.text+=n.text,t.signature||=n.signature,Ae(t,n);return}if(n.type==="reasoning.summary"&&t?.type==="reasoning.summary"){t.summary+=n.summary,Ae(t,n);return}e.push({...n})}var We=["reasoning","reasoning_content","reasoning_text"];function $e(e){return We.includes(e)}function be(e,n){return e||(ee("PI_CACHE_RETENTION",n)==="long"?"long":"short")}var Je=(e,n,t)=>{let s=new V,a=z(n,D(e).supportsMidConvoSystemMessages);return(async()=>{let o={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},m,h=y=>{m!==void 0&&(y.thinkingSignature=JSON.stringify(m))};try{let y=Ie(e.provider,t?.apiKey,t?.headers),R=D(e),x=H(G(a.messages),R.supportsOpenAIGrammarTools),u=be(t?.cacheRetention,t?.env),g=u==="none"?void 0:t?.sessionId,d=Ve(e,a,y,t?.headers,t?.identity,t?.fetch,g,R),l=Ue(e,a,t,R,u,x),r=await t?.onPayload?.(l,e);r!==void 0&&(l=r);let p={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:_,response:A}=await ue(()=>d.chat.completions.create(l,p).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:A.status,headers:re(A.headers)},e),s.push({type:"start",partial:o});let E=null,b=null,w=!1,v=new Map,F=new Map,B=new Map,f=o.content,M=i=>f.indexOf(i),W=i=>({kind:"custom",property:i,buffer:{input:"",started:!1,closed:!1}}),Oe=i=>{let c=M(i);if(c!==-1){if(i.type==="text")s.push({type:"text_end",contentIndex:c,content:i.text,partial:o});else if(i.type==="thinking")h(i),s.push({type:"thinking_end",contentIndex:c,content:i.thinking,partial:o});else if(i.type==="toolCall"){let C=B.get(i).input;if(B.delete(i),C.kind==="custom"){let T=pe(C.buffer,C.property,void 0);T!==void 0&&s.push({type:"toolcall_delta",contentIndex:c,delta:T,partial:o})}else Object.assign(i,C.arguments.finish());s.push({type:"toolcall_end",contentIndex:c,toolCall:i,partial:o})}}},qe=()=>(E||(E={type:"text",text:""},f.push(E),s.push({type:"text_start",contentIndex:M(E),partial:o})),E),$=i=>(b||(b={type:"thinking",thinking:"",thinkingSignature:i},f.push(b),s.push({type:"thinking_start",contentIndex:M(b),partial:o})),b),Pe=i=>{let c=typeof i.index=="number"?i.index:void 0,C=i.function?.name??i.custom?.name??"",T=c!==void 0?v.get(c):void 0;if(!T&&i.id&&(T=F.get(i.id)),!T){let O=i.custom&&!i.function?x.get(C)??"input":void 0;T={type:"toolCall",id:i.id||"",name:C,arguments:O!==void 0?{[O]:""}:{}},B.set(T,{streamIndex:c,input:O!==void 0?W(O):{kind:"json",arguments:new te}}),c!==void 0&&v.set(c,T),i.id&&F.set(i.id,T),f.push(T),s.push({type:"toolcall_start",contentIndex:M(T),partial:o})}let I=B.get(T);if(c!==void 0&&I.streamIndex===void 0&&(I.streamIndex=c,v.set(c,T)),i.id&&F.set(i.id,T),!T.name&&C&&(T.name=C),i.custom&&!i.function&&I.input.kind!=="custom"){let O=x.get(T.name)??"input";T.arguments={[O]:""},I.input=W(O)}return{block:T,state:I}};for await(let i of _){if(await t?.onProviderStreamEvent?.(i,e),!i||typeof i!="object")continue;o.responseId||=i.id,typeof i.model=="string"&&i.model.length>0&&i.model!==e.id&&(o.responseModel||=i.model),i.usage&&(o.usage=Ee(i.usage,e));let c=Array.isArray(i.choices)?i.choices[0]:void 0;if(c){if(!i.usage&&c.usage&&(o.usage=Ee(c.usage,e)),c.finish_reason){o.rawStopReason=c.finish_reason;let C=at(c.finish_reason);o.stopReason=C.stopReason,C.errorMessage&&(o.errorMessage=C.errorMessage),w=!0}if(c.delta){let C=["reasoning_content","reasoning","reasoning_text"],T=c.delta,I=null;for(let k of C){let S=T[k];if(typeof S=="string"&&S.length>0){I=k;break}}if(I){let k=T[I];if(typeof k=="string"&&k.length>0){let S=e.provider==="opencode-go"&&I==="reasoning"?"reasoning_content":I,L=$(S);L.thinking+=k,s.push({type:"thinking_delta",contentIndex:M(L),delta:k,partial:o})}}let O=c.delta.reasoning_details;if(Array.isArray(O))for(let k of O)K(k)&&($(""),m??=[],Ke(m,k));if(c.delta.content!==null&&c.delta.content!==void 0&&c.delta.content.length>0){let k=qe();k.text+=c.delta.content,s.push({type:"text_delta",contentIndex:M(k),delta:c.delta.content,partial:o})}if(c?.delta?.tool_calls)for(let k of c.delta.tool_calls){let{block:S,state:L}=Pe(k);!S.id&&k.id&&(S.id=k.id,F.set(k.id,S));let J=k.function?.name??k.custom?.name;!S.name&&J&&(S.name=J);let N="",P=L.input;k.function?.arguments&&P.kind==="json"?(N=k.function.arguments,S.arguments=P.arguments.append(N)):k.custom?.input&&P.kind==="custom"&&(N=ce(P.buffer,P.property,k.custom.input)??"",S.arguments={[P.property]:P.buffer.input}),s.push({type:"toolcall_delta",contentIndex:M(S),delta:N,partial:o})}}}}for(let i of f)Oe(i);if(t?.signal?.aborted)throw new Error("Request was aborted");if(o.stopReason==="aborted")throw new Error("Request was aborted");if(!w&&!R.supportsFinishReason&&(o.stopReason=o.content.some(i=>i.type==="toolCall")?"toolUse":"stop"),o.stopReason==="error")throw new Error(o.errorMessage||"Provider returned an error stop reason");if(R.supportsFinishReason&&!w||o.stopReason==="pending")throw new Error("Stream ended without finish_reason");s.push({type:"done",reason:o.stopReason,message:o}),s.end()}catch(y){for(let x of o.content)x.type==="thinking"&&h(x);o.stopReason=t?.signal?.aborted?"aborted":"error",o.errorMessage=se(ne(y));let R=y?.error?.metadata?.raw;R&&!o.errorMessage.includes(String(R))&&(o.errorMessage+=`
|
|
5
|
+
${R}`),s.push({type:"error",reason:o.stopReason,error:o}),s.end()}})(),s},Et=(e,n,t)=>{Ie(e.provider,t?.apiKey,t?.headers);let s={...ke(e,n,t,t?.apiKey),toolChoice:t?.toolChoice},a=t?.reasoning?Y(e,t.reasoning):void 0;return Je(e,n,{...s,reasoningEffort:a==="off"?void 0:a,thinkingBudgets:t?.thinkingBudgets})};function Ve(e,n,t,s,a,o,m,h=D(e)){let y={...Q(e,a),...e.headers};if(e.provider==="github-copilot"){let R=he(n.messages),x=me({messages:n.messages,hasImages:R});Object.assign(y,x)}return m&&h.sendSessionAffinityHeaders&&(h.sessionAffinityFormat==="openrouter"?y["x-session-id"]=m:(h.sessionAffinityFormat==="openai"&&(y.session_id=m),y["x-client-request-id"]=m,y["x-session-affinity"]=m)),s&&Object.assign(y,s),new _e({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:o,defaultHeaders:y})}function Ue(e,n,t,s=D(e),a=be(t?.cacheRetention,t?.env),o=H(G(n.messages),s.supportsOpenAIGrammarTools)){let m=j(n.messages,s.supportsMidConvoSystemMessages===!0&&s.supportsMidConvoToolAdditions===!0?"additions":"none"),h=it(e,n,s,{grammarToolInputProperties:o}),y=Ye(s,a),R=s.promptCacheKeyMode??"auto",x=R==="enabled"||R==="auto"&&(e.baseUrl.includes("api.openai.com")||a==="long"&&s.supportsLongCacheRetention),u={model:e.id,messages:h,stream:!0,prompt_cache_key:a!=="none"&&x?ve(t?.sessionId):void 0,prompt_cache_retention:a==="long"&&s.supportsLongCacheRetention?"24h":void 0};s.supportsUsageInStreaming!==!1&&(u.stream_options={include_usage:!0}),s.supportsStore&&(u.store=!1),t?.maxTokens&&(s.maxTokensField==="max_tokens"?u.max_tokens=t.maxTokens:u.max_completion_tokens=t.maxTokens),t?.temperature!==void 0&&(u.temperature=t.temperature),m.requestTools.length>0?(u.tools=Fe(m.requestTools,s),s.zaiToolStream&&(u.tool_stream=!0)):s.requiresToolsWithToolHistory&&Be(n.messages)&&(u.tools=[]),y&&et(h,u.tools,y),t?.toolChoice&&(u.tool_choice=t.toolChoice),s.vllmPriority!==void 0&&(u.priority=s.vllmPriority);let g=Ze(s),d=Qe(e,t,u);if(s.thinkingFormat==="zai"&&e.reasoning){let r=u;if(r.thinking=t?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},t?.reasoningEffort&&s.supportsReasoningEffort){let p=e.thinkingLevelMap?.[t.reasoningEffort],_=p===void 0?t.reasoningEffort:p;typeof _=="string"&&(r.reasoning_effort=_)}}else if(s.thinkingFormat==="qwen"&&e.reasoning){if(u.enable_thinking=!!t?.reasoningEffort,t?.reasoningEffort&&s.supportsReasoningEffort){let r=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;typeof r=="string"&&(u.reasoning_effort=r)}}else if(s.thinkingFormat==="qwen-chat-template"&&e.reasoning)u.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:!0};else if(s.thinkingFormat==="chat-template"&&e.reasoning){let r=Se(e,t,s.chatTemplateKwargs,d);r&&(u.chat_template_kwargs=r)}else if(s.thinkingFormat==="baseten"&&e.reasoning){let r=u,p=Se(e,t,s.chatTemplateArgs,d);if(p&&(r.chat_template_args=p),s.supportsReasoningEffort){let _=t?.reasoningEffort,A=_?e.thinkingLevelMap?.[_]:e.thinkingLevelMap?.off,E=A===void 0?_:A;typeof E=="string"&&(r.reasoning_effort=E)}}else if(s.thinkingFormat==="deepseek"&&e.reasoning)t?.reasoningEffort?u.thinking={type:"enabled"}:e.thinkingLevelMap?.off!==null&&(u.thinking={type:"disabled"}),t?.reasoningEffort&&s.supportsReasoningEffort&&(u.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort);else if(s.thinkingFormat==="openrouter"&&e.reasoning){let r=u;t?.reasoningEffort?r.reasoning={effort:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(r.reasoning={effort:e.thinkingLevelMap?.off??"none"})}else if(s.thinkingFormat==="ant-ling"&&e.reasoning&&t?.reasoningEffort){let r=e.thinkingLevelMap?.[t.reasoningEffort];typeof r=="string"&&(u.reasoning={effort:r})}else if(s.thinkingFormat==="together"&&e.reasoning){let r=u;r.reasoning={enabled:!!t?.reasoningEffort},t?.reasoningEffort&&s.supportsReasoningEffort&&(r.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort)}else if(s.thinkingFormat==="string-thinking"&&e.reasoning){let r=u;t?.reasoningEffort?r.thinking=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort:e.thinkingLevelMap?.off!==null&&(r.thinking=e.thinkingLevelMap?.off??"none")}else if(t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort)u.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(!t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort){let r=e.thinkingLevelMap?.off;typeof r=="string"&&(u.reasoning_effort=r)}if(g&&d!==void 0&&Object.assign(u,{[g]:d}),e.compat?.openRouterRouting&&(u.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){let r=e.compat.vercelGatewayRouting;if(r.only||r.order){let p={};r.only&&(p.only=r.only),r.order&&(p.order=r.order),u.providerOptions={gateway:p}}}let l=ye(e,t?.reasoningEffort??"off",t?.samplingParams);return l&&Object.assign(u,l),u}function Ze(e){if(e.thinkingTokenBudgetField)return e.thinkingTokenBudgetField;if(e.supportsThinkingTokenBudget)return"thinking_token_budget"}function Qe(e,n,t){if(!n?.reasoningEffort||!e.reasoning)return;let s=t.max_tokens??t.max_completion_tokens??e.maxTokens,a=Re(Te(n.reasoningEffort,n.thinkingBudgets),s);return a>0?a:void 0}function Se(e,n,t,s){let a={};for(let[o,m]of Object.entries(t)){let h=Xe(e,n,m,s);h!==void 0&&(a[o]=h)}return Object.keys(a).length>0?a:void 0}function Xe(e,n,t,s){if(typeof t!="object"||t===null)return t;let a=n?.reasoningEffort;if(!a&&t.omitWhenOff)return;if(t.$var==="thinking.enabled")return!!a;if(t.$var==="thinking.budget")return s;let o=a?e.thinkingLevelMap?.[a]:e.thinkingLevelMap?.off;return o===void 0?a:typeof o=="string"?o:void 0}function Ye(e,n){if(e.cacheControlFormat!=="anthropic"||n==="none")return;let t=n==="long"&&e.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...t?{ttl:t}:{}}}function et(e,n,t){tt(e,t),st(n,t),nt(e,t)}function tt(e,n){for(let t of e)if(t.role==="system"||t.role==="developer"){ot(t,n);return}}function nt(e,n){for(let t=e.length-1;t>=0;t--){let s=e[t];if((s.role==="user"||s.role==="assistant"||s.role==="tool")&&rt(s,n))return}}function st(e,n){if(!e||e.length===0)return;let t=e[e.length-1];t.cache_control=n}function ot(e,n){return we(e,n)}function rt(e,n){return e.role==="user"||e.role==="assistant"||e.role==="tool"?we(e,n):!1}function we(e,n){let t=e.content;if(typeof t=="string")return t.length===0?!1:(e.content=[{type:"text",text:t,cache_control:n}],!0);if(!Array.isArray(t))return!1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a?.type==="text"){let o=a;return o.cache_control=n,!0}}return!1}function it(e,n,t,s){let a=z(n,t.supportsMidConvoSystemMessages),o=[],m=g=>{if(g.includes("|")){let d=g.indexOf("|"),l=g.slice(0,d).replace(/[^a-zA-Z0-9_-]/g,"_"),r=g.slice(d+1).replace(/[^a-zA-Z0-9_-]/g,"_"),p=r.length>0?`${l}_${r}`:l;if(p.length<=40)return p;let _=oe(g).slice(0,8);return`${l.slice(0,Math.max(1,40-_.length-1))}_${_}`}return e.provider==="openai"&&g.length>40?g.slice(0,40):g},h=xe(a.messages,e,g=>m(g)),y=j(a.messages,t.supportsMidConvoSystemMessages===!0&&t.supportsMidConvoToolAdditions===!0?"additions":"none"),R=e.reasoning&&t.supportsDeveloperRole?"developer":"system",x=null,u=0;for(let g=0;g<h.length;g++){let d=h[g];if(t.requiresAssistantAfterToolResult&&x==="toolResult"&&d.role==="user"&&o.push({role:"assistant",content:"I have processed the tool results."}),d.role==="system"){let l=u++>=y.foldedSystemMessages?d.toolsAdded??[]:[];if(l.length>0){let p={role:"system",tools:Fe(l,t)};o.push(p)}let r=g===0?U(d):Z(d);r.length>0&&o.push({role:R,content:q(r)})}else if(d.role==="user")if(typeof d.content=="string")o.push({role:"user",content:q(d.content)});else{let l=d.content.filter(r=>r.type!=="text"||r.text.length>0).map(r=>r.type==="text"?{type:"text",text:q(r.text)}:{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.data}`}});if(l.length===0)continue;o.push({role:"user",content:l})}else if(d.role==="assistant"){let l={role:"assistant",content:t.requiresAssistantAfterToolResult||t.requiresNonNullAssistantContent?"":null},r=d.content.filter(Me).filter(f=>f.text.trim().length>0).map(f=>({type:"text",text:q(f.text)})),p=r.map(f=>f.text).join(""),_=d.content.filter(Le),A=d.content.filter(Ne),E=_.map(f=>je(f.thinkingSignature)).find(f=>f!==void 0),b=A.map(f=>He(f.thoughtSignature)).filter(f=>f!==void 0),w=E??(b.length>0?b:void 0),v=_.filter(f=>f.thinking.trim().length>0);if(v.length>0){if(t.requiresThinkingAsText){let f=v.map(M=>q(M.thinking)).join(`
|
|
6
|
+
|
|
7
|
+
`);l.content=[{type:"text",text:f},...r]}else if(p.length>0&&(l.content=p),!w){let f=v[0].thinkingSignature;e.provider==="opencode-go"&&f==="reasoning"&&(f="reasoning_content"),f&&$e(f)&&(l[f]=v.map(M=>M.thinking).join(`
|
|
8
|
+
`))}}else p.length>0&&(l.content=p);A.length>0&&(l.tool_calls=A.map(f=>{let M=s?.grammarToolInputProperties?.get(f.name);return M!==void 0?{id:f.id,type:"custom",custom:{name:f.name,input:q(le(f.name,f.arguments,M))}}:{id:f.id,type:"function",function:{name:f.name,arguments:JSON.stringify(f.arguments)}}})),w&&(l.reasoning_details=w),t.requiresReasoningContentOnAssistantMessages&&e.reasoning&&l.reasoning_content===void 0&&(l.reasoning_content="");let F=l.content;if(!(F!=null&&F.length>0)&&!l.tool_calls)continue;o.push(l)}else if(d.role==="toolResult"){let l=[],r=g;for(;r<h.length&&h[r].role==="toolResult";r++){let p=h[r],_=p.content.filter(Me).map(v=>v.text).join(`
|
|
9
|
+
`),A=p.content.some(v=>v.type==="image"),b=_.trim().length>0?_:A?"(see attached image)":"(no tool output)",w={role:"tool",content:q(b),tool_call_id:p.toolCallId};if(t.requiresToolResultName&&p.toolName&&(w.name=p.toolName),o.push(w),A&&e.input.includes("image"))for(let v of p.content)De(v)&&l.push({type:"image_url",image_url:{url:`data:${v.mimeType};base64,${v.data}`}})}g=r-1,l.length>0?(t.requiresAssistantAfterToolResult&&o.push({role:"assistant",content:"I have processed the tool results."}),o.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...l]}),x="user"):x="toolResult";continue}x=d.role}return o}function Fe(e,n){return e.map(t=>{let s=de(t,n.supportsOpenAIGrammarTools);if(s)return{type:"custom",custom:{name:t.name,description:t.description,format:{type:"grammar",grammar:{syntax:s.format,definition:s.definition}}}};let a=ge(t,n.supportsStrictMode!==!1);return{type:"function",function:{name:t.name,description:t.description,parameters:fe(t,a),...n.supportsStrictMode!==!1&&{strict:a??!1}}}})}function Ee(e,n){let t=e.prompt_tokens||0,s=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??e.cached_tokens??0,a=e.prompt_tokens_details?.cache_write_tokens||0,o=Math.max(0,t-s-a),m=e.completion_tokens||0,h={input:o,output:m,cacheRead:s,cacheWrite:a,reasoning:e.completion_tokens_details?.reasoning_tokens||e.reasoning_tokens||0,totalTokens:o+m+s+a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return X(n,h),ie(n)&&ae(h,e),h}function at(e){if(e===null)return{stopReason:"stop"};switch(e){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${e}`}}}function ut(e){let n=e.provider,t=e.baseUrl,s=n==="zai"||n==="zai-coding-cn"||t.includes("api.z.ai")||t.includes("open.bigmodel.cn"),a=n==="together"||t.includes("api.together.ai")||t.includes("api.together.xyz"),o=n==="moonshotai"||n==="moonshotai-cn"||t.includes("api.moonshot."),m=n==="openrouter"||t.includes("openrouter.ai"),h=n==="cloudflare-workers-ai"||t.includes("api.cloudflare.com"),y=n==="cloudflare-ai-gateway"||t.includes("gateway.ai.cloudflare.com"),R=n==="nvidia"||t.includes("integrate.api.nvidia.com"),x=n==="ant-ling"||t.includes("api.ant-ling.com"),u=n==="cerebras"||t.includes("cerebras.ai"),g=n==="deepseek"||t.toLowerCase().includes("deepseek.com"),d=R||u||n==="xai"||t.includes("api.x.ai")||a||t.includes("chutes.ai")||g||s||o||n==="opencode"||t.includes("opencode.ai")||h||y||x,l=t.includes("chutes.ai")||g||o||y||a||R||x||s,r=n==="xai"||t.includes("api.x.ai"),p=n==="openai"||t.includes("api.openai.com"),_=n==="openrouter"&&e.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!d,supportsDeveloperRole:p,supportsReasoningEffort:!r&&!s&&!o&&!a&&!y&&!R&&!x,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:l?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresNonNullAssistantContent:!1,requiresToolsWithToolHistory:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:g,thinkingFormat:g?"deepseek":s?"zai":a?"together":x?"ant-ling":m?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!1,supportsOpenAIGrammarTools:!1,supportsMidConvoSystemMessages:!1,supportsMidConvoToolAdditions:!1,cacheControlFormat:_,sendSessionAffinityHeaders:m,sessionAffinityFormat:m?"openrouter":"openai",supportsLongCacheRetention:!(a||h||y||R||x)}}function D(e){let n=ut(e);return e.compat?{supportsStore:e.compat.supportsStore??n.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??n.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??n.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??n.supportsUsageInStreaming,supportsFinishReason:e.compat.supportsFinishReason??n.supportsFinishReason,maxTokensField:e.compat.maxTokensField??n.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??n.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??n.requiresAssistantAfterToolResult,requiresNonNullAssistantContent:e.compat.requiresNonNullAssistantContent??n.requiresNonNullAssistantContent,requiresToolsWithToolHistory:e.compat.requiresToolsWithToolHistory??n.requiresToolsWithToolHistory,requiresThinkingAsText:e.compat.requiresThinkingAsText??n.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??n.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??n.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??n.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??n.chatTemplateKwargs,chatTemplateArgs:e.compat.chatTemplateArgs??n.chatTemplateArgs,zaiToolStream:e.compat.zaiToolStream??n.zaiToolStream,supportsThinkingTokenBudget:e.compat.supportsThinkingTokenBudget??n.supportsThinkingTokenBudget,thinkingTokenBudgetField:e.compat.thinkingTokenBudgetField??n.thinkingTokenBudgetField,supportsStrictMode:e.compat.supportsStrictMode??n.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??n.supportsOpenAIGrammarTools,supportsMidConvoSystemMessages:e.compat.supportsMidConvoSystemMessages??n.supportsMidConvoSystemMessages,supportsMidConvoToolAdditions:e.compat.supportsMidConvoToolAdditions??n.supportsMidConvoToolAdditions,cacheControlFormat:e.compat.cacheControlFormat??n.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??n.sendSessionAffinityHeaders,sessionAffinityFormat:e.compat.sessionAffinityFormat??n.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??n.supportsLongCacheRetention,promptCacheKeyMode:e.compat.promptCacheKeyMode,vllmPriority:e.compat.vllmPriority}:n}export{it as convertMessages,Je as stream,Et as streamSimple};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
2
|
const require = __cortexCreateRequire(import.meta.url);
|
|
3
3
|
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as c,b as s,c as u,d as $}from"./chunk-
|
|
4
|
+
import{a as c,b as s,c as u,d as $}from"./chunk-J7OBATRN.js";import"./chunk-23PRJECN.js";import"./chunk-DE5EGVKG.js";import"./chunk-D6VMBA4C.js";import{a as p,c as f}from"./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 o="OpenAI Decisions",y=128;function w(r){let t=[r.criteria.true?`True means: ${r.criteria.true}`:"",r.criteria.false?`False means: ${r.criteria.false}`:""].filter(Boolean);return t.length>0?`${r.instructions}
|
|
5
5
|
|
|
6
6
|
${t.join(`
|
|
7
7
|
`)}`:r.instructions}function h(r,t){return t.type==="choice"?{type:"choice",name:r,instructions:t.instructions,choices:Object.entries(t.criteria).map(([e,i])=>i?{value:e,description:i}:{value:e})}:t.type==="score"?{type:"score",name:r,instructions:t.instructions,levels:t.criteria.map(e=>({label:e}))}:{type:"predicate",name:r,instructions:w(t)}}function d(r){let t=JSON.stringify(r.state),e=r.images??[];if(e.length===0)return t;if(e.length>y)throw new Error(`${o} accepts at most ${y} images, got ${e.length}`);return[{role:"user",content:[{type:"input_text",text:t},...e.map(i=>({type:"input_image",image_url:`data:${i.mimeType};base64,${i.data}`}))]}]}function g(r,t){if(!Array.isArray(r))throw new Error(`${o} returned invalid probabilities for ${t}`);return Object.fromEntries(r.map(e=>{if(!c(e)||typeof e.value!="string")throw new Error(`${o} returned invalid probabilities for ${t}`);return[e.value,s(o,e.probability,`probability for ${t}.${e.value}`)]}))}function m(r,t,e){if(e.type==="refusal")throw new Error(`${o} refused to answer ${r}`);if(t.type==="choice"){if(e.type!=="choice"||typeof e.choice!="string")throw new Error(`${o} did not return a choice answer for ${r}`);return{type:"choice",choice:e.choice,probabilities:g(e.probabilities,r),confidence:s(o,e.confidence,`confidence for ${r}`)}}if(t.type==="score"){if(e.type!=="score")throw new Error(`${o} did not return a score answer for ${r}`);return{type:"score",score:s(o,e.score,`score for ${r}`),confidence:s(o,e.confidence,`confidence for ${r}`)}}if(e.type!=="predicate")throw new Error(`${o} did not return a predicate answer for ${r}`);return{type:"bool",probability:s(o,e.probability,`probability for ${r}`)}}function E(r,t){if(!Array.isArray(r))throw new Error(`${o} returned an unexpected response`);let e=new Map;for(let i of r)c(i)&&typeof i.name=="string"&&e.set(i.name,i);return Object.fromEntries(Object.entries(t.questions).map(([i,n])=>{let a=e.get(i);if(!a)throw new Error(`${o} did not return an answer for ${i}`);return[i,m(i,n,a)]}))}var A=[504];function v(r){return r.status===504?`${o} error (504): the request timed out at the gateway. Very large inputs (above roughly 600K tokens) currently exceed its time limit.`:f(p(r),`${o} error`)}var j=async(r,t,e)=>{let i={api:r.api,provider:r.provider,model:r.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(r.api!=="openai-decisions")throw new Error(`Unsupported classifier API: ${r.api}`);let n=await u(o,new URL("decisions",`${r.baseUrl.replace(/\/+$/u,"")}/`),r,{model:r.id,input:d(t),questions:Object.entries(t.questions).map(([b,l])=>h(b,l))},e,A);if(!c(n))throw new Error(`${o} returned an unexpected response`);let a=$(n.usage,r);return a&&(i.usage=a),i.answers=E(n.answers,t),i}catch(n){return i.answers={},i.stopReason=e?.signal?.aborted?"aborted":"error",i.errorMessage=v(n),i}};export{j as classify};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{a as U,b as K,c as N,d as D}from"./chunk-FE7HH5JS.js";import{a as G}from"./chunk-XIECJESP.js";import{a as L}from"./chunk-4SWD4JMP.js";import{a as w,b as x}from"./chunk-BGYR4ID3.js";import"./chunk-V3AQJSWR.js";import"./chunk-BWDJS6A4.js";import{a as S}from"./chunk-6R73ICDB.js";import{a as O}from"./chunk-23PRJECN.js";import{h as I,j as k,k as b}from"./chunk-7TYSMLUV.js";import{C as R,I as E,v as C,z as M}from"./chunk-DE5EGVKG.js";import"./chunk-D6VMBA4C.js";import"./chunk-USBJFDJ6.js";import{a as P,c as _}from"./chunk-ZD4O6NPV.js";import{a as A}from"./chunk-K4NTZEDJ.js";import{h as y}from"./chunk-3XLHL5YT.js";import"./chunk-X2TKJ7KR.js";import"./chunk-NW4GW47L.js";import{b as v}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var V=new Set(["openai","openai-codex","opencode"]),B=16,Q="https://chatgpt.com/settings/usage",Y="You've reached your ChatGPT workspace's usage limit. Ask your workspace admin to increase it at admin.openai.com \u2192 Workspace \u2192 Usage limits.",J="medium";function H(e,t){return e.provider==="openai"&&e.baseUrl==="https://api.openai.com/v1"&&t!==void 0&&!t.startsWith("sk-")}function F(e,t){if(!e)return!1;let r=t.toLowerCase();for(let[s,i]of Object.entries(e))if(s.toLowerCase()===r&&i!==null&&i.trim().length>0)return!0;return!1}function q(e,t,r){if(t)return t;if(F(r,"authorization")||F(r,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${e}`)}function X(e){return e.provider==="openrouter"||e.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}function W(e,t){return e||(S("PI_CACHE_RETENTION",t)==="long"?"long":"short")}function h(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:e.compat?.sessionAffinityFormat??X(e),promptCacheKeyMode:e.compat?.promptCacheKeyMode??"auto",supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,supportsStrictMode:e.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:e.compat?.supportsAdditionalTools??!1,supportsToolSearch:e.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:e.compat?.supportsExplicitPromptCacheMode??!1,supportsMaxOutputTokens:e.compat?.supportsMaxOutputTokens??!0,supportsMidConvoEffort:e.compat?.supportsMidConvoEffort??!1}}function Z(e,t,r){if(!(!r.supportsMidConvoEffort||!t?.reasoningEffort||H(e,t.apiKey)))return e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}function ee(e,t){return t==="long"&&e.supportsLongCacheRetention&&!e.supportsExplicitPromptCacheMode?"24h":void 0}function re(e,t){if(e.supportsExplicitPromptCacheMode){if(t==="none")return{mode:"explicit"};if(t==="long"&&e.supportsLongCacheRetention)return{ttl:"30m"}}}var te=(e,t,r)=>{let s=new v,i=C(t,h(e).supportsMidConvoSystemMessages);return(async()=>{let u=h(e),p=Z(e,r,u),o={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,...p===void 0?{}:{providerThinkingLevel:p},usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let n=q(e.provider,r?.apiKey,r?.headers),f=W(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,a=I(M(i.messages),u.supportsOpenAIGrammarTools),m=se(e,i,n,r?.headers,r?.identity,r?.fetch,f),d=oe(e,i,r,u,a,p),l=await r?.onPayload?.(d,e);l!==void 0&&(d=l);let g={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},{data:$,response:T}=await O(()=>m.responses.create(d,g).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});if(await r?.onResponse?.({status:T.status,headers:A(T.headers)},e),s.push({type:"start",partial:o}),await D($,o,s,e,{onProviderStreamEvent:r?.onProviderStreamEvent,serviceTier:r?.serviceTier,grammarToolInputProperties:a,applyServiceTierPricing:(j,z)=>ae(j,z,e)}),r?.signal?.aborted)throw new Error("Request was aborted");if(o.stopReason==="pending")throw new Error("OpenAI Responses stream ended without a stop reason");if(o.stopReason==="aborted"||o.stopReason==="error")throw new Error(o.errorMessage||"An unknown error occurred");s.push({type:"done",reason:o.stopReason,message:o}),s.end()}catch(n){o.stopReason=r?.signal?.aborted?"aborted":"error";let c=_(P(n),`${e.provider==="openai"?"OpenAI":e.provider} API error`);c.includes("subscription_sharing_usage_limit_exceeded")?o.errorMessage=`${c}
|
|
5
|
+
Check your ChatGPT usage: ${Q}`:c.includes("subscription_sharing_workplace_individual_usage_limit_exceeded")?o.errorMessage=`${c}
|
|
6
|
+
${Y}`:o.errorMessage=c,s.push({type:"error",reason:o.stopReason,error:o}),s.end()}})(),s},Me=(e,t,r)=>{q(e.provider,r?.apiKey,r?.headers);let s={...b(e,t,r,r?.apiKey),toolChoice:r?.toolChoice},i=r?.reasoning?E(e,r.reasoning):void 0;return te(e,t,{...s,reasoningEffort:i==="off"?void 0:i})};function se(e,t,r,s,i,u,p){let o=h(e),n={...y(e,i),...e.headers};if(e.provider==="github-copilot"){let c=w(t.messages),f=x({messages:t.messages,hasImages:c});Object.assign(n,f)}return p&&(o.sessionAffinityFormat==="openrouter"?n["x-session-id"]=p:(o.sessionAffinityFormat==="openai"&&(n["session-id"]=p),n["x-client-request-id"]=p)),s&&Object.assign(n,s),new L({apiKey:r,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:u,defaultHeaders:n})}function oe(e,t,r,s,i,u){let p=R(t.messages,U(s)),o=K(e,t,V,{grammarToolInputProperties:i,supportsMidConvoSystemMessages:s.supportsMidConvoSystemMessages,supportsAdditionalTools:s.supportsAdditionalTools,supportsToolSearch:s.supportsToolSearch,toolOptions:{supportsStrictMode:s.supportsStrictMode,supportsOpenAIGrammarTools:s.supportsOpenAIGrammarTools},configurationUpdateEffort:u}),n=W(r?.cacheRetention,r?.env),c=n!=="none"&&s.promptCacheKeyMode!=="disabled",f=H(e,r?.apiKey),a={model:e.id,input:o,stream:!0,prompt_cache_key:c?G(r?.sessionId):void 0,prompt_cache_retention:f?void 0:ee(s,n),prompt_cache_options:f?void 0:re(s,n),store:!1};r?.maxTokens&&s.supportsMaxOutputTokens&&!f&&(a.max_output_tokens=Math.max(r.maxTokens,B)),r?.temperature!==void 0&&!f&&(a.temperature=r?.temperature),r?.serviceTier!==void 0&&(a.service_tier=r.serviceTier),p.requestTools.length>0&&(a.tools=N(p.requestTools,{supportsStrictMode:s.supportsStrictMode,supportsOpenAIGrammarTools:s.supportsOpenAIGrammarTools})),r?.toolChoice!==void 0&&(a.tool_choice=r.toolChoice);let m=r?.reasoningEffort??(r?.reasoningSummary?"medium":void 0);if(e.reasoning){if(m){let l=r?.reasoningEffort?e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort:m,g=u===void 0?l:J;a.reasoning={effort:g,summary:r?.reasoningSummary||"auto"},a.include=["reasoning.encrypted_content"]}else e.provider!=="github-copilot"&&e.thinkingLevelMap?.off!==null&&(a.reasoning={effort:e.thinkingLevelMap?.off??"none"});e.provider==="xai"&&(a.include=["reasoning.encrypted_content"])}let d=k(e,m??"off",r?.samplingParams);return d&&Object.assign(a,d),a}function ne(e,t){switch(t){case"flex":return .5;case"priority":case"fast":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function ae(e,t,r){let s=ne(r,t);s!==1&&(e.cost.input*=s,e.cost.output*=s,e.cost.cacheRead*=s,e.cost.cacheWrite*=s,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{te as stream,Me as streamSimple};
|
|
@@ -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 w}from"./chunk-4SWD4JMP.js";import{a as k}from"./chunk-23PRJECN.js";import{a as v}from"./chunk-USBJFDJ6.js";import{a as y,c as R}from"./chunk-ZD4O6NPV.js";import{a as x,b as _}from"./chunk-K4NTZEDJ.js";import{h as l}from"./chunk-3XLHL5YT.js";import"./chunk-X2TKJ7KR.js";import"./chunk-WHC7AYZD.js";var H=async(e,s,t)=>{let r={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let a=t?.apiKey;if(!a)throw new Error(`No API key for provider: ${e.provider}`);let i=P(e,a,t?.headers,t?.fetch,t?.identity),n=b(e,s),c=await t?.onPayload?.(n,e);c!==void 0&&(n=c);let o={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:T,response:g}=await k(()=>i.chat.completions.create(n,o).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:g.status,headers:x(g.headers)},e);let u=T;r.responseId=u.id,u.usage&&(r.usage=M(u.usage,e));let p=u.choices[0];if(p){let m=p.message.content;typeof m=="string"&&m.length>0&&r.output.push({type:"text",text:m});for(let d of p.message.images??[]){let f=typeof d.image_url=="string"?d.image_url:d.image_url?.url;if(!f?.startsWith("data:"))continue;let h=f.match(/^data:([^;]+);base64,(.+)$/);h&&r.output.push({type:"image",mimeType:h[1],data:h[2]})}}return r}catch(a){return r.stopReason=t?.signal?.aborted?"aborted":"error",r.errorMessage=R(y(a)),r}};function P(e,s,t,r,a){return new w({apiKey:s,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:_(l(e,a),e.headers,t)})}function b(e,s){let t=s.input.map(r=>r.type==="text"?{type:"text",text:v(r.text)}:{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.data}`}});return{model:e.id,messages:[{role:"user",content:t}],stream:!1,modalities:e.output.includes("text")?["image","text"]:["image"]}}function M(e,s){let t=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,a=e.prompt_tokens_details?.cache_write_tokens||0,i=a>0?Math.max(0,r-a):r,n=Math.max(0,t-i-a),c=e.completion_tokens||0,o={input:n,output:c,cacheRead:i,cacheWrite:a,totalTokens:n+c+i+a,cost:{input:s.cost.input/1e6*n,output:s.cost.output/1e6*c,cacheRead:s.cost.cacheRead/1e6*i,cacheWrite:s.cost.cacheWrite/1e6*a,total:0,totalFromProvider:!1}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}export{H as generateImages};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{f as w}from"./chunk-BWDJS6A4.js";import{a as y}from"./chunk-6R73ICDB.js";import{c as h,d as p}from"./chunk-D6VMBA4C.js";import{a as b,b as k}from"./chunk-K4NTZEDJ.js";import{h as x}from"./chunk-3XLHL5YT.js";import{d as m}from"./chunk-X2TKJ7KR.js";import{b as f}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var g=class extends Error{code;diagnosticDetails;constructor(t,n,e){super(t),this.name="PiMessagesResponseError",this.code=n,this.diagnosticDetails=e}};function T(r){try{let t=JSON.parse(r),n=t?.error;return t&&typeof n=="object"&&n!==null&&!Array.isArray(n)?t:void 0}catch{return}}function S(r){return r.length>8192?`${m(r,0,8192)}\u2026`:r}function _(r,t,n){let e=typeof n?.error?.message=="string"?n.error.message:void 0,s=typeof n?.error?.code=="string"?n.error.code:void 0,o=e??t,a=s?` (${s})`:"";return`${r.status} ${r.statusText}: ${o}${a}`}function R(r,t,n,e){let s=T(e),o=typeof s?.error?.code=="string"?s.error.code:void 0;return new g(_(n,e,s),o,{version:1,provider:r.provider,model:r.id,url:t.toString(),status:n.status,statusText:n.statusText,...s?.error===void 0?{}:{error:s.error},...s?{}:{body:S(e)},timestampMs:Date.now()})}function M(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function I(r,t){t&&p(r,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...t}})}function O(r){let t={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:M(),stopReason:"pending",timestamp:Date.now()},n=new Map;return e=>{if("contentIndex"in e){let s=e.contentIndex,o=e.type.endsWith("_start")?t.content.length:t.content.length-1;if(typeof s!="number"||!Number.isInteger(s)||s<0||s>o)throw new Error(`Invalid contentIndex ${JSON.stringify(s)} in pi-messages ${e.type} event`)}switch(e.type){case"done":return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),e.responseModel!==void 0&&(t.responseModel=e.responseModel),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),I(t,e.rewrite),{type:"done",reason:e.reason,message:t};case"error":return Object.assign(t,{stopReason:e.reason,usage:e.usage,errorMessage:e.errorMessage,responseId:e.responseId}),e.responseModel!==void 0&&(t.responseModel=e.responseModel),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),I(t,e.rewrite),{type:"error",reason:e.reason,error:t};case"start":break;case"text_start":t.content[e.contentIndex]={type:"text",text:""};break;case"text_delta":t.content[e.contentIndex].text+=e.delta;break;case"text_end":Object.assign(t.content[e.contentIndex],{text:e.content,textSignature:e.contentSignature});break;case"thinking_start":t.content[e.contentIndex]={type:"thinking",thinking:""};break;case"thinking_delta":t.content[e.contentIndex].thinking+=e.delta;break;case"thinking_end":Object.assign(t.content[e.contentIndex],{thinking:e.content,thinkingSignature:e.contentSignature,redacted:e.redacted});break;case"toolcall_start":t.content[e.contentIndex]={type:"toolCall",id:e.id,name:e.toolName,arguments:{}},n.set(e.contentIndex,new w);break;case"toolcall_delta":{let s=n.get(e.contentIndex);s!==void 0&&(t.content[e.contentIndex].arguments=s.append(e.delta));break}case"toolcall_end":return Object.assign(t.content[e.contentIndex],e.toolCall),n.delete(e.contentIndex),{type:"toolcall_end",contentIndex:e.contentIndex,toolCall:t.content[e.contentIndex],partial:t}}return{...e,partial:t}}}async function*$(r){let t=new TextDecoder,n=r.getReader(),e="";try{for(;;){let{done:s,value:o}=await n.read();e+=s?t.decode():t.decode(o,{stream:!0}),e=e.replace(/\r\n/g,`
|
|
5
|
+
`);let a=e.indexOf(`
|
|
6
|
+
|
|
7
|
+
`);for(;a!==-1;){let c=E(e.slice(0,a));c&&(yield c),e=e.slice(a+2),a=e.indexOf(`
|
|
8
|
+
|
|
9
|
+
`)}if(s)break}if(e.trim()){let s=E(e);s&&(yield s)}}finally{n.releaseLock()}}function E(r){let t=r.split(`
|
|
10
|
+
`).find(n=>n.startsWith("data:"))?.slice(5).trim();return t&&t!=="[DONE]"?JSON.parse(t):void 0}function D(r,t,n){let e=n?"aborted":"error",s={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:M(),stopReason:e,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()};return!n&&t instanceof g&&p(s,h("pi_messages_response_failure",t,t.diagnosticDetails)),{type:"error",reason:e,error:s}}function P(r,t){return r||(y("PI_CACHE_RETENTION",t)==="long"?"long":void 0)}var C=(r,t,n)=>{let e=new f,s=O(r);return(async()=>{try{let o=n?.apiKey;if(!o)throw new Error(`No API key provided for provider "${r.provider}"`);let a=new URL(`${r.baseUrl.replace(/\/+$/u,"")}/messages`);n?.debug&&a.searchParams.set("debug","1");let c={model:r.id,context:t,options:{temperature:n?.temperature,maxTokens:n?.maxTokens,reasoning:n?.reasoning,cacheRetention:P(n?.cacheRetention,n?.env),sessionId:n?.sessionId,toolChoice:n?.toolChoice}},l=await n?.onPayload?.(c,r);l!==void 0&&(c=l);let i=await(n?.fetch??globalThis.fetch)(a,{method:"POST",headers:k(x(r,n?.identity),{authorization:`Bearer ${o}`,accept:"text/event-stream","content-type":"application/json"},n?.headers),body:JSON.stringify(c),signal:n?.signal});if(await n?.onResponse?.({status:i.status,headers:b(i.headers)},r),!i.ok){let d=await i.text();throw R(r,a,i,d)}if(!i.body)throw new Error(`${r.provider} response has no body`);for await(let d of $(i.body)){await n?.onProviderStreamEvent?.(d,r);let u=s(d);if(e.push(u),u.type==="done"||u.type==="error")return}throw new Error(`${r.provider} stream ended without a terminal event`)}catch(o){e.push(D(r,o,n?.signal?.aborted??!1))}})(),e},U=(r,t,n)=>{let e=n;return C(r,t,{...n,reasoning:n?.reasoning,toolChoice:n?.toolChoice,debug:e?.debug})};export{g as PiMessagesResponseError,C as stream,U as streamSimple};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{b as v}from"./chunk-DYLBVUAU.js";import{a as d}from"./chunk-RWPO3NZ3.js";import{a as _}from"./chunk-ILEML5IP.js";import{a as w}from"./chunk-XBJOYU5Y.js";import{a as f}from"./chunk-XAXWLYH5.js";import"./chunk-IRWZ7UPF.js";import"./chunk-X2TKJ7KR.js";import"./chunk-WHC7AYZD.js";var y="127.0.0.1",E=1456,O="/oauth/callback",u=`http://${y}:${E}${O}`,S=6e4,g="browser",m="device-code",a="pi-gateway",R="gateway offline_access",U="urn:ietf:params:oauth:grant-type:device_code";async function L(i,r){let e=await fetch(new URL("/v1/oauth",i),{headers:{accept:"application/json"},signal:r});if(!e.ok)throw new Error(`Could not load Radius OAuth config from ${i}: ${e.status} ${await e.text()}`);let t=await e.json(),o=d(t.authorizationEndpoint);if(!o)throw new Error(`Invalid Radius OAuth config from ${i}`);return{authorizationEndpoint:o}}var c=class extends Error{status;oauthError;constructor(r,e,t,o){let n=e?t?`${e}: ${t}`:e:t||String(r);super(`${o}: ${n}`),this.status=r,this.oauthError=e}};async function A(i,r){let e=await i.text().catch(()=>""),t,o;if(e)try{let n=JSON.parse(e);t=typeof n.error=="string"?n.error:void 0,o=typeof n.error_description=="string"?n.error_description:void 0}catch{o=e}return new c(i.status,t,o,r)}async function h(i,r,e){let t;try{t=await fetch(new URL("/v1/oauth/token",i),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:r,signal:e})}catch(n){throw e.aborted?new Error("Login cancelled"):n}if(!t.ok)throw await A(t,"Radius OAuth token request failed");let o=await t.json();return{type:"oauth",access:o.access_token,refresh:o.refresh_token,expires:Date.now()+o.expires_in*1e3-S,scope:o.scope}}async function C(i,r,e){let{verifier:t,challenge:o}=await f(),n=crypto.randomUUID(),l=new URL(r);l.search=new URLSearchParams({response_type:"code",client_id:a,redirect_uri:u,scope:R,code_challenge:o,code_challenge_method:"S256",handoff:"url",state:n}).toString();let p=await w({providerName:"Radius",host:y,port:E,path:O,state:n,complete:s=>h(i,new URLSearchParams({grant_type:"authorization_code",client_id:a,redirect_uri:u,code:s,code_verifier:t}),e.signal),signal:e.signal});e.notify({type:"progress",message:`Listening for OAuth callback on ${u}`}),e.notify({type:"auth_url",url:l.toString(),instructions:"Continue in your browser."});try{let s=await p.wait();if(!s)throw new Error("OAuth callback did not complete.");return s}finally{p.close()}}async function x(i,r){let e;try{e=await fetch(new URL("/v1/oauth/device",i),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:a,scope:R}),signal:r})}catch(n){throw r.aborted?new Error("Login cancelled"):n}if(!e.ok)throw await A(e,"Radius OAuth device authorization failed");let t=await e.json();if(!t.device_code||!t.user_code||!t.verification_uri||!t.expires_in)throw new Error("Radius OAuth device authorization response is missing required fields");let o=d(t.verification_uri);if(!o)throw new Error("Untrusted verification_uri in Radius OAuth device authorization response");return{device_code:t.device_code,user_code:t.user_code,verification_uri:o,expires_in:t.expires_in,interval:t.interval}}async function k(i,r){let e=await x(i,r.signal);return r.notify({type:"device_code",userCode:e.user_code,verificationUri:e.verification_uri,intervalSeconds:e.interval,expiresInSeconds:e.expires_in}),_({intervalSeconds:e.interval,expiresInSeconds:e.expires_in,signal:r.signal,poll:async()=>{try{return{status:"complete",value:await h(i,new URLSearchParams({grant_type:U,client_id:a,device_code:e.device_code}),r.signal)}}catch(t){if(!(t instanceof c))throw t;switch(t.oauthError){case"authorization_pending":return{status:"pending"};case"slow_down":return{status:"slow_down"};case"expired_token":return{status:"failed",message:"Device authorization expired."};case"access_denied":return{status:"failed",message:"Device authorization was denied."};default:throw t}}}})}function I(i){let r=v(i.gateway);return{name:i.name,async login(e){let t=await e.prompt({type:"select",message:`Sign in to ${i.name}:`,options:[{id:g,label:"Sign in with browser (recommended)"},{id:m,label:"Sign in with device code (when signing in from another device)"}]});if(t===m)return k(r,e);if(t===g){let o=await L(r,e.signal);return C(r,o.authorizationEndpoint,e)}throw new Error(`Unknown ${i.name} sign-in method: ${t}`)},async refresh(e,t){return await h(r,new URLSearchParams({grant_type:"refresh_token",client_id:a,refresh_token:e.refresh}),t)},async toAuth(e){return{apiKey:e.access}}}}export{I as createRadiusOAuth};
|
|
@@ -0,0 +1,14 @@
|
|
|
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-5FHETFZM.js";import{a as F,b as L,c as N,d as P,e as K,f as G}from"./chunk-TJ4GQRT6.js";import{a as j,c as R}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 o}from"./chunk-W34AK4SK.js";import{e as v,j as I,v as O}from"./chunk-T54CZKNJ.js";import"./chunk-WHC7AYZD.js";import*as T from"fs";import*as A from"path";import*as Q from"crypto";import{pathToFileURL as re}from"url";var M=class{memoryCache=new Map;cacheDir;sessionId;constructor(e={}){this.cacheDir=e.cacheDir??F(v),this.sessionId=e.sessionId??process.env.CORTEX_SESSION_ID,N(this.cacheDir)}buildBlocks(e,u,g){if(!u||u.length===0)return[];let d=a=>L(a.deviceId?.trim()||e,a.path);return P(this.cacheDir,this.sessionId,a=>{let p=!1,s=[];for(let t of u)a.get(d(t))!==t.mtimeMs&&(g?.has(t.path)?(a.set(d(t),t.mtimeMs),p=!0):s.push(t));let{included:r,blocks:m,truncated:c}=K(s,t=>this.formatBlock(e,t));for(let t of r)a.set(d(t),t.mtimeMs),p=!0;return{value:(c.length>0?[...m,G(c.map(t=>`${e}:${t.path}`))]:m).map(t=>({type:"text",text:t})),changed:p}},this.memoryCache)}formatBlock(e,u){return`<system-reminder>
|
|
5
|
+
Auto-loaded AGENTS.md from ${e}:${u.path} (ancestor of accessed path on remote device). These instructions apply to files under this directory on that device.
|
|
6
|
+
|
|
7
|
+
`+u.content+`
|
|
8
|
+
</system-reminder>`}},B=null;function q(){return B||(B=new M),B}function H(i,e,u){if(!e||e.length===0)return[];let g;if(u){let d=e.filter(a=>Y(a.path,u));d.length>0&&(g=new Set(d.map(a=>a.path)))}return q().buildBlocks(i,e,g)}function Y(i,e){return i===e?!0:i.replace(/\\/g,"/")===e.replace(/\\/g,"/")}import{readFileSync as ee}from"fs";import*as z from"path";var te=z.join(I,"machines.json");function U(i=te){try{let e=JSON.parse(ee(i,"utf-8"));return Object.entries(e).map(([u,g])=>({name:u,windows:g?.win===!0}))}catch{return[]}}function W(i){return i.length===0?"":` Known devices: ${i.map(u=>u.windows?`${u.name} (Windows)`:u.name).join(", ")}. May be offline; failed calls list currently online devices.`}function J(i,e){return Array.isArray(e)?`${i}. Online devices: ${e.length>0?e.join(", "):"none"}`:i}async function $(i,e,u,g,d){let{body:a}=await j("POST",`${i.webhookBaseUrl}/webhook/remote-command`,{device:e,action:u,params:g,timeout:d},R(i));if(!a.success)throw new Error(J(a.error||"Command failed",a.onlineDevices));return a.data}var X=A.join(O,"tool-results"),oe={remote_bash:3e4,remote_grep:2e4,remote_glob:1e5};function k(i,e){let u=oe[i];if(e.length<=u)return e;T.mkdirSync(X,{recursive:!0});let g=`${i}-${Date.now()}-${Q.randomBytes(4).toString("hex")}`,d=A.join(X,`${g}.txt`);T.writeFileSync(d,e,"utf8");let a=(e.length/1024).toFixed(2),p=e.slice(0,2e3);return["<persisted-output>",`Output too large (${a} KB). Full output saved to local file:`,` ${d}`,"","Preview (first 2 KB):",p,"...","</persisted-output>"].join(`
|
|
9
|
+
`)}var w=null;try{w=(await import("sharp")).default}catch{}var C=25e3,V=1568;function E(i){return Math.ceil(i*.125)}async function ne(i,e,u,g){if(!w)return{data:i,mimeType:e,width:u||0,height:g||0};let d=Buffer.from(i,"base64"),a=await w(d).metadata(),p=a.width||u||0,s=a.height||g||0,r=e,m=Math.max(p,s),c=d;if(m>V){let y=V/m;p=Math.round(p*y),s=Math.round(s*y),c=await w(d).resize(p,s,{fit:"inside",withoutEnlargement:!0}).toBuffer()}let n;r==="image/png"?n=await w(c).png({compressionLevel:6}).toBuffer():r==="image/webp"?n=await w(c).webp({quality:85}).toBuffer():(n=await w(c).jpeg({quality:85}).toBuffer(),r="image/jpeg");let t=n.toString("base64"),l=E(t.length);if(l>C){(r==="image/png"||r==="image/webp")&&(n=await w(n).jpeg({quality:80}).toBuffer(),r="image/jpeg",t=n.toString("base64"),l=E(t.length));let y=[70,55,40,30];for(let b of y){if(l<=C)break;n=await w(c).resize(p,s,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:b}).toBuffer(),r="image/jpeg",t=n.toString("base64"),l=E(t.length)}let x=[.75,.5,.35];for(let b of x){if(l<=C)break;let f=Math.round(p*b),_=Math.round(s*b);n=await w(d).resize(f,_,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:30}).toBuffer(),t=n.toString("base64"),l=E(t.length)}}let h=await w(n).metadata();return{data:t,mimeType:r,width:h.width||p,height:h.height||s}}var Z=1800,ie=" `<device>:<path>` refers to a path on that device.";function $e(i,e){let g=["remote_bash","remote_read","remote_write","remote_edit","remote_glob","remote_grep"].find(s=>!e.toolAllowlist||e.toolAllowlist.has(s)),d=W(U()),a=(s,r)=>r+(s===g?ie+d:""),p=(s,r,m)=>e.clean?[]:H(s,r,m);i.tool("remote_bash",a("remote_bash","Run a remote shell command via cortex-client; Windows uses git-bash."),{device:o.string().describe("Target device name."),command:o.string().describe("Shell command to execute"),timeout:o.number().int().min(1).max(Z).optional().describe(`Timeout in seconds (default: 120, max: ${Z})`),description:o.string().optional().describe("Command summary for logging"),run_in_background:o.boolean().optional().describe("Run command in background, return PID immediately; timeout is ignored")},async({device:s,command:r,timeout:m,description:c,run_in_background:n})=>{try{let t=(m??120)*1e3,l=await $(e,s,"bash",{command:r,timeout:t,run_in_background:n||!1},t+5e3),h=[];l.stdout&&h.push(l.stdout),l.stderr&&h.push(`[stderr]
|
|
10
|
+
${l.stderr}`),l.exitCode!==0&&h.push(`[exit code: ${l.exitCode}]`);let y=h.join(`
|
|
11
|
+
`)||"(no output)",x=k("remote_bash",y),b=l.exitCode!==void 0&&l.exitCode!==0;return{content:[{type:"text",text:x}],...b?{isError:!0}:{}}}catch(t){return{content:[{type:"text",text:`remote_bash error: ${t.message}`}],isError:!0}}}),i.tool("remote_read",a("remote_read","Read a remote absolute path: numbered text, inline images (PNG/JPEG/GIF/WebP/BMP), or PDF documents."),{device:o.string().describe("Target device name."),file_path:o.string().describe("Absolute path to the file to read"),offset:o.number().optional().describe("Line number to start reading from (0-based)"),limit:o.number().optional().describe("Number of lines to read")},{readOnlyHint:!0},async({device:s,file_path:r,offset:m,limit:c})=>{try{if(!S(r))return{content:[{type:"text",text:"file_path must be absolute"}],isError:!0};let n=await $(e,s,"read",{file_path:r,offset:m,limit:c}),t=p(s,n.cortexMDs,r);if(n.image){let{data:l,mimeType:h,width:y,height:x,originalSize:b}=n.image;try{let f=await ne(l,h,y,x),_=E(f.data.length),D=[`Image: ${r}`,`Original: ${y||"?"}x${x||"?"} ${h} (${(b/1024).toFixed(1)} KB)`];return f.width!==y||f.height!==x||f.mimeType!==h?D.push(`Processed: ${f.width}x${f.height} ${f.mimeType} (~${_} tokens)`):D.push(`~${_} tokens`),{content:[{type:"text",text:D.join(`
|
|
12
|
+
`)},{type:"image",data:f.data,mimeType:f.mimeType},...t]}}catch(f){return{content:[{type:"text",text:`Image detected (${h}, ${y||"?"}x${x||"?"}, ${(b/1024).toFixed(1)} KB) but processing failed: ${f.message}`},...t]}}}if(n.pdf){let{data:l,originalSize:h}=n.pdf;return{content:[{type:"text",text:`PDF: ${r} (${(h/1024).toFixed(1)} KB)`},{type:"resource",resource:{uri:re(r).href,mimeType:"application/pdf",blob:l}},...t]}}return{content:[{type:"text",text:n.content||"(empty file)"},...t]}}catch(n){return{content:[{type:"text",text:`remote_read error: ${n.message}`}],isError:!0}}}),i.tool("remote_write",a("remote_write","Write/overwrite a remote file at an absolute path; creates parent directories."),{device:o.string().describe("Target device name."),file_path:o.string().describe("Absolute path to the file to write"),content:o.string().describe("Content to write to the file")},async({device:s,file_path:r,content:m})=>{try{if(!S(r))return{content:[{type:"text",text:"file_path must be absolute"}],isError:!0};let c=await $(e,s,"write",{file_path:r,content:m}),n=p(s,c?.cortexMDs,r);return{content:[{type:"text",text:`File written: ${r}`},...n]}}catch(c){return{content:[{type:"text",text:`remote_write error: ${c.message}`}],isError:!0}}}),i.tool("remote_edit",a("remote_edit","Replace text in a remote file at an absolute path. old_string must be unique unless replace_all=true."),{device:o.string().describe("Target device name."),file_path:o.string().describe("Absolute path to the file to edit"),old_string:o.string().describe("The text to replace"),new_string:o.string().describe("The replacement text"),replace_all:o.boolean().optional().describe("Replace all occurrences (default: false)")},async({device:s,file_path:r,old_string:m,new_string:c,replace_all:n})=>{try{if(!S(r))return{content:[{type:"text",text:"file_path must be absolute"}],isError:!0};let t=await $(e,s,"edit",{file_path:r,old_string:m,new_string:c,replace_all:n||!1}),l=p(s,t?.cortexMDs,r);return{content:[{type:"text",text:`File edited: ${r}`},...l]}}catch(t){return{content:[{type:"text",text:`remote_edit error: ${t.message}`}],isError:!0}}}),i.tool("remote_glob",a("remote_glob","List remote file paths matching a glob."),{device:o.string().describe("Target device name."),pattern:o.string().describe("Glob pattern to match files against"),path:o.string().optional().describe("Directory to search in (absolute path)")},{readOnlyHint:!0},async({device:s,pattern:r,path:m})=>{try{let c=await $(e,s,"glob",{pattern:r,path:m}),n=c.files||[];if(n.length===0)return{content:[{type:"text",text:"No files matched the pattern."}]};let t=n.join(`
|
|
13
|
+
`);return c.truncated&&(t+=`
|
|
14
|
+
[... truncated at ${n.length} results]`),{content:[{type:"text",text:k("remote_glob",t)}]}}catch(c){return{content:[{type:"text",text:`remote_glob error: ${c.message}`}],isError:!0}}}),i.tool("remote_grep",a("remote_grep","Search remote file contents with ripgrep; return matching lines, paths, or counts."),{device:o.string().describe("Target device name."),pattern:o.string().describe("Regex pattern to search for"),path:o.string().optional().describe("File or directory to search in"),glob:o.string().optional().describe('Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}")'),type:o.string().optional().describe('File type to search (e.g. "js", "py", "rust")'),output_mode:o.enum(["content","files_with_matches","count"]).optional().describe("Output mode (default: files_with_matches)"),"-A":o.number().optional().describe("Lines to show after each match"),"-B":o.number().optional().describe("Lines to show before each match"),"-C":o.number().optional().describe("Context lines before and after each match"),context:o.number().optional().describe("Alias for -C"),"-i":o.boolean().optional().describe("Case insensitive search"),"-n":o.boolean().optional().describe("Show line numbers (default: true for content mode)"),head_limit:o.number().optional().describe("Limit output entries (default: 250, 0 for unlimited)"),offset:o.number().optional().describe("Skip first N entries before applying head_limit"),multiline:o.boolean().optional().describe("Enable multiline matching (pattern can span lines)")},{readOnlyHint:!0},async({device:s,pattern:r,path:m,glob:c,type:n,output_mode:t,context:l,head_limit:h,offset:y,multiline:x,...b})=>{try{let _=(await $(e,s,"grep",{pattern:r,path:m,glob:c,type:n,output_mode:t,"-A":b["-A"],"-B":b["-B"],"-C":b["-C"],context:l,"-i":b["-i"],"-n":b["-n"],head_limit:h,offset:y,multiline:x})).output||"(no matches)";return{content:[{type:"text",text:k("remote_grep",_)}]}}catch(f){return{content:[{type:"text",text:`remote_grep error: ${f.message}`}],isError:!0}}})}export{$e as registerRemoteOpsTools};
|
|
@@ -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,b,c,d}from"./chunk-VOAKRJ4R.js";import"./chunk-ZYQ4TDTT.js";import"./chunk-IVZ7QUEG.js";import"./chunk-TJ4GQRT6.js";import"./chunk-Y3AOGNDT.js";import"./chunk-LMDWRRX4.js";import"./chunk-3EZNVLBF.js";import"./chunk-IA6IODY3.js";import"./chunk-UHXPRU6G.js";import"./chunk-B3XBQEFM.js";import"./chunk-CMSOOLJB.js";import"./chunk-ZNAMETPQ.js";import"./chunk-4KQHDDC5.js";import"./chunk-QXFWIL4C.js";import"./chunk-Y6ZEVVL5.js";import"./chunk-R6CGBSTC.js";import"./chunk-WZYS2HAK.js";import"./chunk-TMV2ZDOI.js";import"./chunk-IOWBF7UK.js";import"./chunk-2ABET62E.js";import"./chunk-2WFL62UO.js";import"./chunk-PG7452XE.js";import"./chunk-RW2F2QNP.js";import"./chunk-HVN37UXD.js";import"./chunk-Y6DGVTKM.js";import"./chunk-OZXMPBUX.js";import"./chunk-V7K3KNDM.js";import"./chunk-5T7IX5KN.js";import"./chunk-VHX2GHBF.js";import"./chunk-C6YVF7EI.js";import"./chunk-ITGCWQFK.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-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import"./chunk-BVEDNESB.js";import"./chunk-KST6OY76.js";import"./chunk-AXYAZTTN.js";import"./chunk-SM45TH22.js";import"./chunk-R2CCD4OF.js";import"./chunk-KRXTI4JO.js";import"./chunk-W34AK4SK.js";import"./chunk-LIIZI3HY.js";import"./chunk-Q4UGYGU5.js";import"./chunk-TRXLIL7V.js";import"./chunk-7GGPYU5E.js";import"./chunk-7W7VYUTK.js";import"./chunk-JGUEIW2W.js";import"./chunk-T54CZKNJ.js";import"./chunk-WHC7AYZD.js";export{d as _test,c as parentQuotaPurpose,b as runSubagent,a as supportsSubagents};
|
|
@@ -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,b,c,d,e,f}from"./chunk-G4JYZFEO.js";import"./chunk-24DH4IR5.js";import"./chunk-EQIMHXC4.js";import"./chunk-IRWZ7UPF.js";import"./chunk-6G3OYMCV.js";import"./chunk-CEJIYYVE.js";import"./chunk-2BVUA256.js";import"./chunk-AWFUHWQK.js";import"./chunk-B3XBQEFM.js";import"./chunk-WHC7AYZD.js";export{b as McpOAuthCredentialStore,f as McpServerConnection,d as McpServerLog,a as McpSignInCancelledError,e as createDefaultTransport,c as signInMcpServer};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{c as S,d as w,e as p,f as v,h as g,k as h,l as m,p as A,r as j,s as C,t as M,u as D}from"./chunk-KJUQCCB5.js";import"./chunk-IVZ7QUEG.js";import"./chunk-IA6IODY3.js";import{g as O}from"./chunk-Q7BZLPBU.js";import"./chunk-Y6DGVTKM.js";import"./chunk-C6YVF7EI.js";import"./chunk-ITGCWQFK.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-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import{b as E,c as x}from"./chunk-PMG4YGDU.js";import"./chunk-SM45TH22.js";import"./chunk-LIIZI3HY.js";import"./chunk-Q4UGYGU5.js";import"./chunk-TRXLIL7V.js";import"./chunk-7GGPYU5E.js";import"./chunk-7W7VYUTK.js";import"./chunk-T54CZKNJ.js";import"./chunk-WHC7AYZD.js";var f=["list","get","add","edit","pause","resume","remove"],_={"--type":"type","--interval":"interval","--time":"time","--day":"day","--delay":"delay","--message":"message","--project":"project","--model":"model","--thinking":"thinking","--pre-check":"preCheck","--idempotency-key":"idempotencyKey"},I=["interval","time","day","delay","message","project","model","thinking","preCheck"],L={list:["project"],get:[],add:["type",...I,"idempotencyKey"],edit:I,pause:[],resume:[],remove:[]},T={interval:["interval"],daily:["time"],weekly:["day","time"],once:["delay"]},N=new Set(["get","edit","pause","resume","remove"]),c=class extends Error{validValues;hint;constructor(t,n,r="cortex schedule --help"){super(t),this.validValues=n,this.hint=r}};function y(e){return Object.entries(_).filter(([,t])=>e.includes(t)).map(([t])=>t)}function R(e,t,n,r){let i=_[t[n]];if(!i||!L[e].includes(i)){let o=[...y(L[e]),...e==="remove"?["--dry-run"]:[]];throw new c(`Unknown option for '${e}': '${t[n]}'.`,o.length?o:["(none)"])}if(t[n+1]===void 0||t[n+1].startsWith("--"))throw new c(`Missing value for ${t[n]}.`);r[i]=t[n+1]}function b(e,t,n){let r={id:"",flags:{},dryRun:!1},i=[];for(let s=0;s<t.length;s+=1)e==="remove"&&t[s]==="--dry-run"?r.dryRun=!0:t[s].startsWith("-")?R(e,t,s++,r.flags):i.push(t[s]);let o=N.has(e)?1:0;if(i.length!==o)throw new c(o?`'${e}' takes one schedule id.`:`Unexpected argument: '${i[0]}'.`,void 0,o?`cortex schedule ${e} <id>`:void 0);return r.id=i[0]??"",r.flags.message==="-"&&(r.flags.message=n()),r}var G=["createdAt","nextRun","lastRun","runAt","pausedAt","lastSkipped"];function k(e){let t={...e};for(let n of G)typeof e[n]=="number"&&(t[n]=new Date(e[n]).toISOString());return t}function u(e,t){if(!e)throw new c(`Schedule not found: '${t}'.`,void 0,"cortex schedule list");return k(e)}async function W({flags:e},t){if(!e.type)throw new c("Missing --type.",[...S]);let n=h(e.model,e.thinking);m(e.model,n);let r=g({type:e.type,message:e.message,projectId:e.project,selection:n,preCheck:e.preCheck,interval:e.interval,time:e.time,dayOfWeek:e.day,delay:e.delay}),i=T[r.type],o=["interval","time","day","delay"].filter(d=>e[d]!==void 0&&!i.includes(d));if(o.length)throw new c(`${y(o).join(", ")} does not apply to --type ${r.type}.`,y(i));let{task:s,created:l}=await j(t,r,{idempotencyKey:e.idempotencyKey});return{ok:!0,created:l,schedule:k(s)}}var K={message:e=>({message:e}),project:e=>({projectId:e}),preCheck:e=>({preCheck:e}),interval:e=>({intervalMs:p(e,"interval")}),time:e=>({time:e}),day:e=>({dayOfWeek:v(e)}),delay:e=>({runAt:Date.now()+p(e,"delay")})};async function U({id:e,flags:t},n){let r=await n.findTask(e);u(r,e);let{model:i,thinking:o,...s}=t,l=Object.assign({},...Object.entries(s).map(([$,F])=>K[$](F))),d=h(i,o,r?.selection);return m(i,d),d&&(l.selection=d),{ok:!0,schedule:u(await C(n,e,l),e)}}async function V({id:e,dryRun:t},n){return t?{ok:!0,dry_run:!0,would_remove:u(await n.findTask(e),e)}:{ok:!0,id:e,removed:await n.removeTask(e)}}async function H({flags:e},t){let n=(await t.read()).tasks.filter(r=>!e.project||r.projectId===e.project);return{ok:!0,count:n.length,schedules:n.map(k)}}var P={list:H,get:async({id:e},t)=>({ok:!0,schedule:u(await t.findTask(e),e)}),add:W,edit:U,pause:async({id:e},t)=>({ok:!0,schedule:u(await M(t,e),e)}),resume:async({id:e},t)=>({ok:!0,schedule:u(await D(t,e),e)}),remove:V};function a(e,t,n){return{exitCode:1,stdout:"",stderr:E(e,{validValues:t,hint:n})}}function z(e){return e instanceof c?a(e.message,e.validValues,e.hint):e instanceof w?a(e.message,void 0,"cortex schedule --help"):a(e.message)}async function Z(e,t={}){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:O(),stderr:""};let[n,...r]=e;if(!n)return a("Missing subcommand for 'schedule'.",[...f]);if(!f.includes(n))return a(`Unknown subcommand: '${n}'.`,[...f]);try{let i=b(n,r,t.readStdin??x),o=await P[n](i,t.repo??A);return{exitCode:0,stdout:JSON.stringify(o,null,2),stderr:""}}catch(i){return z(i)}}export{Z as runScheduleCli};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
+
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
+
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
+
import{b as w,c as E}from"./chunk-5FHETFZM.js";import{a as C,e as x}from"./chunk-LE6QPXN6.js";import{a as L}from"./chunk-NT32UURL.js";import"./chunk-I6OPDRVF.js";import"./chunk-ZNAMETPQ.js";import"./chunk-4KQHDDC5.js";import"./chunk-QXFWIL4C.js";import"./chunk-Y6ZEVVL5.js";import"./chunk-LP72AF56.js";import"./chunk-N6BTQN7R.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-7W7VYUTK.js";import"./chunk-T54CZKNJ.js";import{e as T}from"./chunk-WHC7AYZD.js";var k=T(x(),1);import*as S from"fs";import*as b from"path";function v(e){return{slack:e.slackBotToken?new k.WebClient(e.slackBotToken):null,fallbackChannel:e.channel??void 0,ctx:e}}function y(){return new C({globalCapacity:m("CORTEX_SLACK_RL_GLOBAL_CAPACITY",20),globalRefillPerSec:m("CORTEX_SLACK_RL_GLOBAL_REFILL_PER_SEC",1),perChannelCapacity:m("CORTEX_SLACK_RL_CHANNEL_CAPACITY",1),perChannelRefillPerSec:m("CORTEX_SLACK_RL_CHANNEL_REFILL_PER_SEC",1)})}function m(e,t){let l=process.env[e];return l?Number(l):t}var R=null;async function A(e,{channel:t,filePath:l,fileName:s,title:h,initialComment:p}){let a=R??(R=y()),{resolved:o,size:c}=L(l),f=S.readFileSync(o),i=s||b.basename(o),n=w(t,"slack:");p&&(await a.acquire("chat.postMessage",n),await e.chat.postMessage({channel:n,text:p})),await a.acquire("files.getUploadURLExternal",n);let d=await e.files.getUploadURLExternal({filename:i,length:c});if(!d?.upload_url||!d?.file_id)throw new Error("Slack upload initialization failed: missing upload_url or file_id");let u=await fetch(d.upload_url,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:f});if(!u.ok){let _=await u.text().catch(()=>""),g=_?`: ${_.slice(0,300)}`:"";throw new Error(`Slack file upload failed (${u.status} ${u.statusText})${g}`)}return await a.acquire("files.completeUploadExternal",n),await e.files.completeUploadExternal({files:[{id:d.file_id,title:h||i}],channel_id:n}),{path:o,fileName:i,size:c}}function $(e,t){e.tool("slack_send_file","Share a local or remote-device file in the Slack chat.",{file_path:r.string().describe("File path to upload. Local path, or an absolute path on `device`."),file_name:r.string().optional().describe("Optional filename override shown in Slack"),title:r.string().optional().describe("Optional file title shown in Slack"),comment:r.string().optional().describe("Optional comment to accompany the file"),device:r.string().optional().describe("Connected device to read from; omit for this server.")},async({file_path:l,file_name:s,title:h,comment:p,device:a})=>{try{let o=t.fallbackChannel;if(!o)throw new Error("No routing channel available");if(!t.slack)throw new Error("Missing SLACK_BOT_TOKEN");let c=(i,n)=>A(t.slack,{channel:o,filePath:i,fileName:n,title:h,initialComment:p||void 0}),f=a?await E(t.ctx,a,l,i=>c(i.localPath,s||i.name)):await c(l,s);return{content:[{type:"text",text:`File uploaded${a?` from ${a}`:""}: ${f.fileName} (${f.size} bytes)`}]}}catch(o){return{content:[{type:"text",text:`Failed to upload file: ${o.message}`}],isError:!0}}})}export{$ as registerSlackTools,v as slackDepsFor,A as uploadFileToSlack};
|