@cortex-agent/server 2026.11.17 → 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/README.md +5 -5
- package/THIRD_PARTY_NOTICES.txt +860 -294
- package/defaults/hooks/quota-stop.mjs +37 -0
- 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/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-VTL3Z2OP.js → chunk-2ABET62E.js} +1 -1
- package/dist/chunks/chunk-2BVUA256.js +4 -0
- package/dist/chunks/{chunk-4YLAGSDM.js → chunk-2WFL62UO.js} +1 -1
- package/dist/chunks/{chunk-LQTFDC67.js → chunk-335SSANX.js} +1 -1
- package/dist/chunks/chunk-377OPTXX.js +17 -0
- package/dist/chunks/chunk-3EZNVLBF.js +129 -0
- package/dist/chunks/{chunk-V6X7Y62J.js → chunk-3O6ZG5HA.js} +1 -1
- package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
- package/dist/chunks/{chunk-2ATTYCRJ.js → chunk-4HRI75GU.js} +1 -1
- 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-S3MR37DL.js → chunk-5FHETFZM.js} +1 -1
- package/dist/chunks/{chunk-CEGSDGYQ.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-B3NB243Z.js +4 -0
- package/dist/chunks/{chunk-XPPZ6Y3X.js → chunk-BKYP6AGM.js} +1 -1
- package/dist/chunks/{chunk-QUXPMNFQ.js → chunk-BVEDNESB.js} +1 -1
- 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-5PAW3DEU.js → chunk-CI2RHH74.js} +4 -4
- package/dist/chunks/{chunk-OFEPDNRB.js → chunk-CMSOOLJB.js} +1 -1
- 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-ROVKOIHF.js → chunk-DK4UCK7L.js} +1 -1
- package/dist/chunks/chunk-DYLBVUAU.js +4 -0
- package/dist/chunks/{chunk-WBSE3EF3.js → chunk-FDC2GRBK.js} +1 -1
- 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-2VVRTJQN.js → chunk-HVN37UXD.js} +1 -1
- package/dist/chunks/{chunk-53TQNK7Z.js → chunk-IGZWZP7Z.js} +1 -1
- package/dist/chunks/{chunk-AFTBQRPN.js → chunk-IJ7XFQMI.js} +1 -1
- package/dist/chunks/{chunk-U23S37TT.js → chunk-IMMGYDAB.js} +1 -1
- package/dist/chunks/chunk-IOWBF7UK.js +10 -0
- package/dist/chunks/{chunk-MGYYSX7Y.js → chunk-ITGCWQFK.js} +1 -1
- package/dist/chunks/{chunk-QEL6CMLE.js → chunk-IVZ7QUEG.js} +1 -1
- package/dist/chunks/{chunk-EE3WT25T.js → chunk-IWY2HIFK.js} +1 -1
- package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
- package/dist/chunks/{chunk-NXZS5PEW.js → chunk-JGUEIW2W.js} +1 -1
- package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
- package/dist/chunks/{chunk-VIMHSW6J.js → chunk-KJUQCCB5.js} +1 -1
- package/dist/chunks/{chunk-BUZQBTV2.js → chunk-KST6OY76.js} +1 -1
- package/dist/chunks/{chunk-KDPY2YA3.js → chunk-KZSAFVSY.js} +2 -2
- package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
- package/dist/chunks/{chunk-RYLSRII6.js → chunk-LE6QPXN6.js} +1 -1
- package/dist/chunks/{chunk-TX46YMGI.js → chunk-LIIZI3HY.js} +1 -1
- package/dist/chunks/{chunk-3CZPBLB3.js → chunk-MJQ2D2OP.js} +1 -1
- package/dist/chunks/{chunk-P7TVR4GY.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-T73GHMFB.js → chunk-OJ37ZWBG.js} +1 -1
- package/dist/chunks/{chunk-7GEBDPTT.js → chunk-OZXMPBUX.js} +1 -1
- package/dist/chunks/chunk-PG7452XE.js +4 -0
- package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
- package/dist/chunks/{chunk-RA2BUYI3.js → chunk-PTS3J4DQ.js} +1 -1
- package/dist/chunks/{chunk-2ROGTDM2.js → chunk-PVVEEBUU.js} +1 -1
- package/dist/chunks/{chunk-W6AKCEYF.js → chunk-Q7BZLPBU.js} +1 -1
- package/dist/chunks/{chunk-SY2HV3V5.js → chunk-QC66ZXPP.js} +1 -1
- package/dist/chunks/chunk-QXFWIL4C.js +4 -0
- package/dist/chunks/{chunk-NRD57ICT.js → chunk-R2CCD4OF.js} +1 -1
- package/dist/chunks/{chunk-R52AVUQB.js → chunk-RG5GP4RB.js} +1 -1
- package/dist/chunks/{chunk-IKLTEWA3.js → chunk-RW2F2QNP.js} +1 -1
- package/dist/chunks/{chunk-XEBEWR6Y.js → chunk-RWPO3NZ3.js} +1 -1
- package/dist/chunks/chunk-SDUS2H3E.js +4 -0
- package/dist/chunks/chunk-SIHGKM4E.js +4 -0
- package/dist/chunks/{chunk-NNBSSISP.js → chunk-SKHFU5DI.js} +1 -1
- package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
- package/dist/chunks/chunk-T54CZKNJ.js +6 -0
- package/dist/chunks/chunk-TRXLIL7V.js +4 -0
- package/dist/chunks/{chunk-KUDK7GPS.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-BDLKI2NT.js → chunk-VHX2GHBF.js} +1 -1
- package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
- package/dist/chunks/{chunk-FP7ML72L.js → chunk-WU7RNAZD.js} +1 -1
- package/dist/chunks/chunk-WZC4TDDM.js +6 -0
- package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
- package/dist/chunks/{chunk-H4QZ2P3Z.js → chunk-X5ND4H4P.js} +1 -1
- package/dist/chunks/{chunk-5A6CA5TM.js → chunk-Y3AOGNDT.js} +1 -1
- package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
- package/dist/chunks/{chunk-LP7T32PW.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-CZH7AYZ7.js → easter-egg-3d-XR5S2O3T.js} +1 -1
- package/dist/chunks/execution-repo-5TLV2NM4.js +4 -0
- package/dist/chunks/{executions-BN6OLLVM.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-ABBD7DO5.js → install-cli-FALWKQYO.js} +1 -1
- package/dist/chunks/{interaction-ask-EE2UPR3Q.js → interaction-ask-O5HGF6CH.js} +1 -1
- package/dist/chunks/{interaction-plan-C446T2GZ.js → interaction-plan-JTVDN3BC.js} +1 -1
- package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
- package/dist/chunks/{llama-cpp-classify-IA2F2H7A.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
- package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
- package/dist/chunks/memory-cli-DIT4DQF3.js +11 -0
- 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/openai-codex-responses-U6DGMGDK.js +12 -0
- package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
- package/dist/chunks/{openai-decisions-P5UX7BWY.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/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-6PLXHSTB.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-W5M3BE55.js → waitpoint-M6JZBSLT.js} +1 -1
- package/dist/chunks/workers-SQ2R32TK.js +4 -0
- package/dist/client-bundle/client.mjs +229 -62
- 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 +1 -1
- package/dist/entry/app.js +138 -556
- package/dist/entry/browser-cli.js +1 -1
- package/dist/entry/cli.js +1 -1
- package/dist/entry/cortex-cli.js +1 -1
- package/dist/entry/daemon.js +3 -3
- package/dist/entry/hook-cli.js +1 -1
- 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 +1 -1
- package/dist/tui/index.js +1 -1
- package/package.json +1 -1
- 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-BgIyUG-C.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-C2eMpcuI.js → index-jl30Gy8P.js} +1 -1
- package/web/dist/index.html +2 -2
- package/dist/chunks/anthropic-messages-M732OMEE.js +0 -8
- package/dist/chunks/azure-openai-responses-RAKTV6JY.js +0 -4
- package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +0 -62
- package/dist/chunks/child-runner-MO5RT6FH.js +0 -4
- package/dist/chunks/chunk-3CPIMAYX.js +0 -30
- package/dist/chunks/chunk-3ORG56I5.js +0 -8
- package/dist/chunks/chunk-4EX2JJWB.js +0 -4
- package/dist/chunks/chunk-5DF5WJNM.js +0 -60
- package/dist/chunks/chunk-7GAYFN52.js +0 -18
- package/dist/chunks/chunk-AVXDF7AG.js +0 -4
- package/dist/chunks/chunk-BJGYGEZO.js +0 -6
- package/dist/chunks/chunk-BZDIAI5M.js +0 -125
- package/dist/chunks/chunk-CK3P345X.js +0 -133
- package/dist/chunks/chunk-CVC66CFV.js +0 -33
- package/dist/chunks/chunk-ETIBCA2S.js +0 -4
- package/dist/chunks/chunk-FF7UELTU.js +0 -4
- 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-IYVZHGUQ.js +0 -5
- package/dist/chunks/chunk-JJDEQ6N2.js +0 -4
- package/dist/chunks/chunk-KDYEGGMW.js +0 -4
- package/dist/chunks/chunk-L6VCIGWS.js +0 -11
- package/dist/chunks/chunk-LACGULCN.js +0 -10
- package/dist/chunks/chunk-LAWOWPZX.js +0 -363
- package/dist/chunks/chunk-NNTQUHLO.js +0 -877
- package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
- package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
- package/dist/chunks/chunk-PZMGBKUR.js +0 -13
- package/dist/chunks/chunk-QBKCAIJG.js +0 -4
- package/dist/chunks/chunk-QMSSIDRQ.js +0 -70
- package/dist/chunks/chunk-QUUEQRIT.js +0 -4
- package/dist/chunks/chunk-RA6HKFBV.js +0 -4
- package/dist/chunks/chunk-RDW6FRF5.js +0 -4
- package/dist/chunks/chunk-RF4JLYBX.js +0 -6
- package/dist/chunks/chunk-SFX7V5O2.js +0 -10
- package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
- package/dist/chunks/chunk-STCNHXPJ.js +0 -6
- package/dist/chunks/chunk-UT6DGZDO.js +0 -4
- package/dist/chunks/chunk-VBN2JSER.js +0 -5
- package/dist/chunks/chunk-VK5J556O.js +0 -4
- package/dist/chunks/chunk-VPVSKJGX.js +0 -6
- package/dist/chunks/chunk-VQUPKMDR.js +0 -4
- package/dist/chunks/chunk-WEZWKMYU.js +0 -4
- package/dist/chunks/chunk-XYSXL3KX.js +0 -4
- package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
- package/dist/chunks/chunk-YAAKL3QS.js +0 -80
- package/dist/chunks/chunk-YB5LUJHS.js +0 -65
- package/dist/chunks/chunk-YKKEI5GI.js +0 -4
- package/dist/chunks/chunk-Z24SBRJK.js +0 -4
- package/dist/chunks/cli-5DBTRMHU.js +0 -53
- package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
- package/dist/chunks/context-GQKWKFRM.js +0 -4
- package/dist/chunks/cost-OOO32GLC.js +0 -5
- package/dist/chunks/dist-V5FRMUFH.js +0 -4
- package/dist/chunks/execution-repo-XXL4FXC6.js +0 -4
- package/dist/chunks/file-H572PL2Z.js +0 -4
- package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
- package/dist/chunks/google-generative-ai-2G4ITOZL.js +0 -4
- package/dist/chunks/google-vertex-PACHCMRZ.js +0 -4
- package/dist/chunks/init-75F4V7SK.js +0 -4
- package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
- package/dist/chunks/local-client-stop-5YOLXGYT.js +0 -4
- package/dist/chunks/memory-cli-5SSF6YJM.js +0 -11
- package/dist/chunks/meta-KY3LNFV2.js +0 -4
- package/dist/chunks/mistral-conversations-VHP63CDS.js +0 -7
- package/dist/chunks/model-resolver-FVJNZ6NA.js +0 -4
- package/dist/chunks/openai-codex-responses-EHJ4AZBE.js +0 -12
- package/dist/chunks/openai-completions-CRAGQFCE.js +0 -9
- package/dist/chunks/openai-responses-IZ22NVQ7.js +0 -6
- package/dist/chunks/openrouter-images-W2JAMSRH.js +0 -4
- package/dist/chunks/pi-messages-MJEEQU2R.js +0 -10
- package/dist/chunks/radius-ZM7ZRMXF.js +0 -4
- package/dist/chunks/remote-ops-O5CR4RGA.js +0 -14
- package/dist/chunks/runner-S6R3US24.js +0 -4
- package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
- package/dist/chunks/schedule-cli-4T4YC5V5.js +0 -4
- package/dist/chunks/slack-2CGM4SMY.js +0 -4
- package/dist/chunks/start-ui-http-3D7QNHGB.js +0 -43
- package/dist/chunks/subagent-OZGUOV3J.js +0 -4
- package/dist/chunks/tool-shims-IA2WELXJ.js +0 -4
- package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
- package/dist/chunks/ui-board-H4INJD6C.js +0 -5
- package/dist/chunks/ui-decision-6HHNROIT.js +0 -4
- package/dist/chunks/ui-view-6MDU4GXY.js +0 -4
- package/dist/chunks/virtual-modules-OFI7QKYH.js +0 -4
- package/dist/chunks/workers-GTFP75MS.js +0 -4
- 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-9lyu2S6W.css +0 -1
- package/web/dist/assets/index-C-hpzey7.js +0 -532
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
var f=new Set;function g(r){return f.add(r),()=>{f.delete(r)}}function l(r){let t=[];for(let s of f)try{s(r)}catch(e){t.push(e)}if(t.length>0)throw new AggregateError(t,"Failed to cleanup session resources")}var a=(1n<<41n)-1n,u=-1,n;function x(r){let t=r??Date.now();if(!Number.isInteger(t)||t<0||t>0xffffffffffff)throw new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${0xffffffffffff}`);let s=r===void 0?Math.max(t,u):r;r===void 0&&(u=s);let e=new Uint8Array(16);if(globalThis.crypto.getRandomValues(e),n===void 0)n=BigInt(e[1])<<32n|BigInt(e[2])<<24n|BigInt(e[3])<<16n|BigInt(e[4])<<8n|BigInt(e[5]);else{if(n===a)throw new RangeError("UUIDv7 generator sequence exhausted");n++}let c=BigInt(s);for(let o=5;o>=0;o--)e[o]=Number(c>>BigInt((5-o)*8))&255;e[6]=112|Number(n>>37n&0x0fn),e[7]=Number(n>>29n&0xffn),e[8]=128|Number(n>>23n&0x3fn),e[9]=Number(n>>15n&0xffn),e[10]=Number(n>>7n&0xffn),e[11]=Number((n&0x7fn)<<1n)|e[11]&1;let i=Array.from(e,o=>o.toString(16).padStart(2,"0"));return`${i.slice(0,4).join("")}-${i.slice(4,6).join("")}-${i.slice(6,8).join("")}-${i.slice(8,10).join("")}-${i.slice(10).join("")}`}export{g as a,l as b,x as c};
|
|
@@ -1,4 +0,0 @@
|
|
|
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 A}from"./chunk-VPVSKJGX.js";import{e as T}from"./chunk-WHC7AYZD.js";import*as c from"fs";import*as t from"path";import*as _ from"os";import{fileURLToPath as f}from"url";var R=T(A(),1);import{readFileSync as x}from"node:fs";import{homedir as C}from"node:os";import*as n from"node:path";var E="CORTEX_AISTATUS_HOME",l="CORTEX_GATEWAY_HOME";function D(o){try{return(0,R.parse)(x(n.join(o,".env")))}catch(e){if(e.code!=="ENOENT")throw e}return{}}function I(o,e,i){let p=h=>h[E]??h[l],s=p(o)??p(e);if(s===void 0)return n.join(i,".aistatus");if(!n.isAbsolute(s))throw new Error(`${E} must be an absolute path`);return n.join(n.resolve(s),".aistatus")}function O(o,e=process.env,i=C()){return I(e,D(o),i)}var d=t.dirname(f(new URL("dist/core/paths.js",__cortexPackageRoot).href)),u=t.resolve(d,"..",".."),M=t.join(u,"defaults");var H=u;var r=process.env.CORTEX_HOME?t.resolve(process.env.CORTEX_HOME):t.join(_.homedir(),".cortex");function S(){let o=process.env.CORTEX_AGENT_CWD;if(!o)return r;let e=t.resolve(o);if(!t.isAbsolute(o)||!c.existsSync(e)||!c.statSync(e).isDirectory())throw new Error(`CORTEX_AGENT_CWD must be an absolute path to an existing directory: ${o}`);return e}var m=S();function j(o){return t.resolve(o??m)}function g(o){return j(o?.workspaceDir??void 0)}var X=O(t.join(r,"config")),F=t.join(r,"config"),a=t.join(r,"data"),W=t.join(a,"claude"),b=t.join(a,"claude-accounts"),k=t.join(a,"pi-accounts"),y=t.join(_.homedir(),".claude"),K=t.join(a,"daemon.pid"),J=t.join(a,"daemon-child.pid"),V=t.join(a,".restart"),v=t.join(r,"context"),Y=process.env.CORTEX_PROJECTS_DIR?t.resolve(process.env.CORTEX_PROJECTS_DIR):t.join(v,"projects"),P=t.join(r,"tmp"),$=t.join(r,"workspaces");function q(o){let e="workspace/";if(!o.startsWith(e))return null;let i=o.slice(e.length),p=t.resolve(P),s=t.resolve(p,i);return s!==p&&!s.startsWith(p+t.sep)?null:s}var z=t.join(r,"plugins"),B=t.join(r,"prompts"),Q=t.join(r,"hooks"),Z=t.join(r,"logs");export{u as a,M as b,H as c,r as d,m as e,j as f,g,X as h,F as i,a as j,W as k,b as l,k as m,y as n,K as o,J as p,V as q,v as r,Y as s,P as t,$ as u,q as v,z as w,B as x,Q as y,Z as z};
|
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as Y,b as z,c as V,d as B,e as K,f as W}from"./chunk-L6VCIGWS.js";import{c as k,d as _,e as U,g as F,h as H}from"./chunk-HGPBHTVD.js";import"./chunk-Y3GFB5XM.js";import"./chunk-EQIMHXC4.js";import"./chunk-IRWZ7UPF.js";import{g as L,h as R}from"./chunk-RA6HKFBV.js";import"./chunk-FX6MOGLR.js";import{a as x}from"./chunk-3TGQSGG4.js";import{E as h,G as M}from"./chunk-QUUEQRIT.js";import"./chunk-AWFUHWQK.js";import"./chunk-B3XBQEFM.js";import"./chunk-WHC7AYZD.js";import{existsSync as X}from"node:fs";import{join as S}from"node:path";import{createInterface as Z}from"node:readline/promises";var ee=`${x.bold("Usage:")}
|
|
5
|
-
${h} mcp add <server> [options] -- <command> [args...]
|
|
6
|
-
${h} mcp add <server> [options] --url <url>
|
|
7
|
-
${h} mcp remove <server> [-l]
|
|
8
|
-
${h} mcp list [--json]
|
|
9
|
-
${h} mcp login <server> [--timeout <seconds>]
|
|
10
|
-
${h} mcp logout <server>
|
|
11
|
-
|
|
12
|
-
Configure and check MCP servers and sign in to OAuth servers without starting a session.
|
|
13
|
-
Reads ~/${M}/agent/mcp.json and, in trusted projects, ${M}/mcp.json.
|
|
14
|
-
|
|
15
|
-
Commands:
|
|
16
|
-
add <server> Add or replace a server in mcp.json
|
|
17
|
-
remove <server> Remove a server from mcp.json
|
|
18
|
-
list Show state, tools, and errors (exits 1 on failure)
|
|
19
|
-
login <server> Sign in through the browser
|
|
20
|
-
logout <server> Delete the stored OAuth credentials
|
|
21
|
-
|
|
22
|
-
Options for add and remove:
|
|
23
|
-
-l, --local Use ${M}/mcp.json in the current project instead of the global file
|
|
24
|
-
|
|
25
|
-
Options for add:
|
|
26
|
-
--url <url> Streamable HTTP server URL (instead of a command)
|
|
27
|
-
--env <KEY=VALUE> Environment variable for a stdio server (repeatable)
|
|
28
|
-
--cwd <dir> Working directory for a stdio server
|
|
29
|
-
--header <KEY=VALUE> HTTP header (repeatable)
|
|
30
|
-
--bearer-token-env-var <NAME>
|
|
31
|
-
Send "Authorization: Bearer \${NAME}"
|
|
32
|
-
--oauth-client-id <id> Pre-registered OAuth client id
|
|
33
|
-
--oauth-client-secret <secret>
|
|
34
|
-
OAuth client secret (may be \${NAME} or !command)
|
|
35
|
-
--oauth-callback-port <port>
|
|
36
|
-
Fixed OAuth callback port
|
|
37
|
-
--oauth-client-name <name>
|
|
38
|
-
Client name sent when registering with the OAuth server
|
|
39
|
-
--exposure <mode> codemode (default), deferred, direct, or hidden
|
|
40
|
-
--description <text> What the server offers, shown in the system prompt
|
|
41
|
-
|
|
42
|
-
Other options:
|
|
43
|
-
--json Print the list as JSON
|
|
44
|
-
--timeout <seconds> Time limit for the whole sign-in (default: 300)`,b=x.dim(`Use "${h} mcp --help" for usage.`),te=300;function A(o){return o instanceof Error?o.message:String(o)}function re(o){let{config:t}=o;return"url"in t?t.url:[t.command,...t.args??[]].join(" ")}function G(o,t,i){return new W({entry:o,cwd:t.cwd,createTransport:K,credentials:i,log:new B(S(t.agentDir,"mcp.log")),onTools:()=>{}})}var ne=new Map([["-l","--local"]]);function y(o,t,i,c=Number.POSITIVE_INFINITY){let n=[],a=new Map,l=new Map;for(let f=0;f<o.length;f++){let e=ne.get(o[f])??o[f];if(e==="--"||n.length>=c){n.push(...o.slice(e==="--"?f+1:f));break}if(!e.startsWith("--")){n.push(e);continue}let d=e.slice(2),s=t[d];if(!s){i(`Unknown option ${e}.
|
|
45
|
-
${b}`);return}if(s==="flag"){a.set(d,!0);continue}let r=o[++f];if(r===void 0){i(`${e} needs a value.`);return}s==="list"?l.set(d,[...l.get(d)??[],r]):a.set(d,r)}return{positional:n,values:a,lists:l}}async function we(o,t){let i=t.log??(r=>console.log(r)),c=t.error??(r=>console.error(r)),[n,...a]=o;if(n===void 0||n==="help"||o.includes("--help")||o.includes("-h"))return i(ee),0;let l=S(t.cwd,M,"mcp.json");if(n==="add"||n==="remove")return n==="add"?oe(a,l,t,i,c):se(a,l,t,i,c);let f=new k(t.agentDir).get(t.cwd)===!0,e=U({agentDir:t.agentDir,cwd:t.cwd,projectTrusted:f}),d=!f&&X(l)?`${l} is ignored because the project is not trusted. Start ${h} in the project to trust it.`:void 0,s=t.credentials??new Y;switch(n){case"list":{let r=y(a,{json:"flag"},c);return r?r.positional.length>0?(c(`Usage: ${h} mcp list [--json]
|
|
46
|
-
${b}`),1):ie(e,r.values.has("json"),d,t,s,i):1}case"login":case"logout":{let r=y(a,n==="login"?{timeout:"value"}:{},c);if(!r)return 1;let[u,...p]=r.positional;if(!u||p.length>0)return c(`Usage: ${h} mcp ${n} <server>
|
|
47
|
-
${b}`),1;let g=e.servers.find(v=>v.name===u);if(!g)return c(`No MCP server named "${u}".${d?` ${d}`:""} Configured: ${e.servers.map(v=>v.name).join(", ")||"none"}.`),1;let O=G(g,t,s),P=O.oauthUrl;if(!P)return c(`MCP server "${u}" does not use OAuth. Only HTTP servers without an Authorization header do.`),1;if(n==="logout"){let v=s.remove(u,P);return i(v?`Signed out of MCP server "${u}".`:`No stored credentials for MCP server "${u}".`),0}let w=Number(r.values.get("timeout")??te);if(!Number.isFinite(w)||w<=0)return c("--timeout must be a positive number of seconds."),1;try{return await ae(g,O,P,w*1e3,t,s,i,c)}finally{await O.close()}}default:return c(`Unknown mcp command "${n}".
|
|
48
|
-
${b}`),1}}function q(o,t,i){if(!t)return{};let c={};for(let n of t){let a=n.indexOf("=");if(a<=0){i(`--${o} expects KEY=VALUE, got "${n}".`);return}c[n.slice(0,a)]=n.slice(a+1)}return c}function oe(o,t,i,c,n){let a=`Usage: ${h} mcp add <server> [options] (--url <url> | -- <command> [args...])
|
|
49
|
-
${b}`,l=y(o,{local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},n,2);if(!l)return 1;let{positional:f,values:e,lists:d}=l,[s,...r]=f,u=e.get("url");if(!s||u===void 0==(r.length===0))return n(a),1;let p=m=>{let $=e.get(m);return typeof $=="string"?$:void 0},g=p("exposure"),w=(u===void 0?["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"]:["env","cwd"]).find(m=>e.has(m)||d.has(m));if(w)return n(`--${w} only applies to ${u===void 0?"HTTP servers (--url)":"stdio servers"}.`),1;let v;if(typeof u=="string"){let m=q("header",d.get("header"),n);if(!m)return 1;let $=p("bearer-token-env-var");$!==void 0&&(m.Authorization=`Bearer \${${$}}`);let C=p("oauth-callback-port"),D={...p("oauth-client-id")===void 0?{}:{clientId:p("oauth-client-id")},...p("oauth-client-secret")===void 0?{}:{clientSecret:p("oauth-client-secret")},...C===void 0?{}:{callbackPort:Number(C)},...p("oauth-client-name")===void 0?{}:{clientName:p("oauth-client-name")}};v={url:u,...Object.keys(m).length>0?{headers:m}:{},...Object.keys(D).length>0?{oauth:D}:{}}}else{let m=q("env",d.get("env"),n);if(!m)return 1;let[$,...C]=r;v={command:$,...C.length>0?{args:C}:{},...Object.keys(m).length>0?{env:m}:{},...p("cwd")===void 0?{}:{cwd:p("cwd")}}}g!==void 0&&(v.exposure=g);let N=p("description");N!==void 0&&(v.description=N);let j=R(s,v);if(typeof j=="string")return n(j),1;let T=e.has("local"),E=T?t:S(i.agentDir,"mcp.json"),J=T?"project":"global",I;try{I=F(E,s,j)}catch(m){return n(`Could not update ${E}: ${A(m)}`),1}c(`${I?"Replaced":"Added"} ${J} MCP server "${s}" in ${E}.`),T&&new k(i.agentDir).get(i.cwd)!==!0&&c(`The project is not trusted, so ${E} is ignored until you start ${h} in the project and trust it.`);let Q="url"in j&&!Object.keys(j.headers??{}).some(m=>m.toLowerCase()==="authorization");return c(`Check it with: ${h} mcp list${Q?`. If it requires sign-in: ${h} mcp login ${s}`:""}`),0}function se(o,t,i,c,n){let a=y(o,{local:"flag"},n);if(!a)return 1;let[l,...f]=a.positional;if(!l||f.length>0)return n(`Usage: ${h} mcp remove <server> [-l]
|
|
50
|
-
${b}`),1;let e=a.values.has("local"),d=S(i.agentDir,"mcp.json"),s=e?t:d,r=e?"project":"global",u;try{u=H(s,l)}catch(g){return n(`Could not update ${s}: ${A(g)}`),1}if(u)return c(`Removed ${r} MCP server "${l}" from ${s}.`),0;let p=U({agentDir:i.agentDir,cwd:i.cwd,projectTrusted:!0}).servers.find(g=>g.name===l&&g.scope!==r);return n(`No ${r} MCP server named "${l}" in ${s}.${p?` It is defined in ${p.source}${p.scope==="project"?"; use --local":"; omit --local"}.`:""}`),1}async function ie(o,t,i,c,n,a){let l=await Promise.all(o.servers.map(async e=>{let d={name:e.name,scope:e.scope??"global",source:e.source,...e.override?{override:e.override}:{},enabled:e.config.enabled!==!1,exposure:e.config.exposure??"codemode",transport:re(e),state:"disabled",tools:[]};if(!d.enabled)return d;let s=G(e,c,n);try{await s.getClient()}catch{}d.state=s.state,d.tools=s.tools.map(u=>u.name);let r=s.tools.flatMap(u=>{let p=L(e.config,u.name);return p===d.exposure?[]:[[u.name,p]]});return r.length>0&&(d.toolExposure=Object.fromEntries(r)),s.hasResources&&(d.resources=!0),s.state!=="connected"&&s.error&&(d.error=s.error),await s.close(),d})),f=o.errors.length>0||l.some(e=>e.enabled&&e.state!=="connected");if(t)return a(JSON.stringify({servers:l,errors:o.errors,...i?{note:i}:{}},null,2)),f?1:0;l.length===0&&o.errors.length===0&&a(`No MCP servers configured. Add them to ${S(c.agentDir,"mcp.json")} or .pi/mcp.json.`);for(let e of l){let d=e.state==="connected"?`connected, ${e.tools.length} tool${e.tools.length===1?"":"s"}`:e.state==="needs-auth"?"needs sign-in":e.state;if(a(`${e.name}: ${d} (${e.exposure}, ${e.scope})`),a(` ${e.transport}`),e.override&&a(` project override: ${e.override}`),e.state==="needs-auth"&&a(` sign in with: ${h} mcp login ${e.name}`),e.tools.length>0){let s=e.tools.map(r=>{let u=e.toolExposure?.[r];return u?`${r} [${u}]`:r});a(` tools: ${s.join(", ")}`)}e.resources&&a(" offers resources"),e.error&&a(` ${e.error.split(`
|
|
51
|
-
`).join(`
|
|
52
|
-
`)}`)}for(let e of o.errors)a(`config error: ${e}`);return i&&a(i),f?1:0}async function ae(o,t,i,c,n,a,l,f){let{name:e}=o;try{return await t.getClient(),l(`Already signed in to MCP server "${e}" (${t.tools.length} tools).`),0}catch{if(t.state!=="needs-auth")return f(`MCP server "${e}" failed to connect: ${t.error??"unknown error"}`),1}let d=n.openUrl??_,s=process.stdin.isTTY===!0&&n.openUrl===void 0;try{await V({serverUrl:i,store:a.forServer(e,i),settings:t.oauthSettings(),challenge:t.challenge,prompt:{showAuthorizationUrl:r=>{l(`Sign in to MCP server "${e}" in your browser:
|
|
53
|
-
${r.href}`),d(r.href)},promptForRedirectUrl:r=>ce(r,s)},signal:AbortSignal.timeout(c)})}catch(r){return f(r instanceof z?`Sign-in to MCP server "${e}" was cancelled or not completed within ${Math.round(c/1e3)} seconds.`:`Sign-in to MCP server "${e}" failed: ${A(r)}`),1}t.challenge=void 0;try{await t.reconnect()}catch(r){return f(`Signed in, but ${A(r)}`),1}return l(`Signed in to MCP server "${e}" (${t.tools.length} tools).`),0}async function ce(o,t){if(!t){o.aborted||await new Promise(c=>o.addEventListener("abort",c,{once:!0}));return}let i=Z({input:process.stdin,output:process.stderr});try{return await i.question("If the browser cannot reach this machine, paste the URL it was redirected to: ",{signal:o})}catch{return}finally{i.close()}}export{we as runMcpCommand};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as o}from"./chunk-E6BYRULL.js";import{a as n}from"./chunk-KGJZAYQD.js";import"./chunk-FF7UELTU.js";import"./chunk-23PRJECN.js";import"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import"./chunk-K4NTZEDJ.js";import"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var s="Cloudflare Workers AI";function a(e){if(Array.isArray(e)){let r=e.map(t=>n(t)&&typeof t.message=="string"?t.message:void 0).filter(t=>t!==void 0);if(r.length>0)return`${s} error: ${r.join("; ")}`}return`${s} request failed`}var i={api:"cloudflare-workers-ai-system-one",label:s,detectCompat:e=>({imageInput:e.id.startsWith("@cf/cloudflare/clef")?"images":"assets",sendImageOptInHeader:!1}),url:e=>new URL("run",`${e.baseUrl.replace(/\/+$/u,"")}/`),payload:(e,r)=>({model:e.id,input:r}),output:e=>{if(!n(e))throw new Error(`${s} returned an unexpected response`);if(e.success===!1)throw new Error(a(e.errors));let r=e.result;if(!n(r))throw new Error(`${s} returned an unexpected response`);if("answers"in r)return r;if(r.state!=="Completed")throw new Error(`${s} run did not complete (state: ${String(r.state)})`);if(!n(r.result))throw new Error(`${s} returned an unexpected response`);return r.result}},f=(e,r,t)=>o(i,e,r,t);export{f as classify};
|
|
@@ -1,4 +0,0 @@
|
|
|
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 a,c as b,d as c,e as d,f as e}from"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";export{e as registerContextTools,d as resolveCortexContext,a as toolContextFromEnv,c as webSessionId,b as webhookAuthHeaders};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{d as y,i as s}from"./chunk-VTL3Z2OP.js";import"./chunk-BDLKI2NT.js";import"./chunk-JJDEQ6N2.js";import"./chunk-MGYYSX7Y.js";import"./chunk-RA2BUYI3.js";import"./chunk-U23S37TT.js";import"./chunk-T73GHMFB.js";import"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-VK5J556O.js";import"./chunk-5M4PFLRW.js";import"./chunk-KRXTI4JO.js";import{K as $}from"./chunk-W34AK4SK.js";import"./chunk-TX46YMGI.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import"./chunk-3CPIMAYX.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";function A(m){m.tool("cost_query","Report daily/monthly spending, budgets and remaining amounts, API/plan split, source breakdown, and token usage.",{projectId:$.string().optional().describe("Scope the report to one project. Omit for the global view.")},{readOnlyHint:!0},async({projectId:h})=>{try{let n=h??null,t=await y(n),{dailyBudget:i,monthlyBudget:d,budgetScope:g}=t,a=new Date,r=l=>String(l).padStart(2,"0"),b=`${a.getFullYear()}-${r(a.getMonth()+1)}-${r(a.getDate())}`,x=`${a.getFullYear()}-${r(a.getMonth()+1)}`,c=t.byMode.today.total,u=t.byMode.month.total,F=t.byMode.today.api,S=t.byMode.today.plan,P=t.byMode.month.api,f=t.byMode.month.plan,j=(c/i*100).toFixed(1),M=(u/d*100).toFixed(1),o=[n?`Project: ${n} (${g==="project"?"per-project budget":"global budget"})`:"Scope: all projects (global budget)",`Today (${b}): $${c.toFixed(2)} / $${i} (${j}%, ${t.entryCount} sessions in window)`,` API: $${F.toFixed(2)} | Plan: $${S.toFixed(2)}`,`Month (${x}): $${u.toFixed(2)} / $${d} (${M}%)`,` API: $${P.toFixed(2)} | Plan: $${f.toFixed(2)}`,`Remaining today: $${(i-c).toFixed(2)}`,`Remaining month: $${(d-u).toFixed(2)}`];if(t.bySource&&Object.keys(t.bySource).length>0){o.push(""),o.push("By source:");for(let[l,p]of Object.entries(t.bySource))o.push(` ${l}: today $${p.today.toFixed(2)} | month $${p.month.toFixed(2)}`)}let e=t.tokens;return e&&(e.total.input>0||e.total.output>0)&&(o.push(""),o.push(`Tokens today: ${s(e.today.input)} in / ${s(e.today.output)} out`),o.push(`Tokens month: ${s(e.month.input)} in / ${s(e.month.output)} out`)),{content:[{type:"text",text:o.join(`
|
|
5
|
-
`)}]}}catch(n){return{content:[{type:"text",text:`Failed to query cost: ${n.message}`}],isError:!0}}})}export{A as registerCostTools};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{$ as Fa,$a as Lb,A as X,Aa as hb,B as Y,Ba as ib,C as Z,Ca as jb,D as _,Da as kb,E as da,Ea as lb,F as ea,Fa as ob,G as fa,Ga as pb,H as ga,Ha as qb,I as ha,Ia as rb,J as ia,Ja as sb,K as ja,Ka as tb,L as ka,La as ub,M as la,Ma as vb,N as ma,Na as wb,O as na,Oa as xb,P as oa,Pa as zb,Q as pa,Qa as Ab,R as qa,Ra as Bb,S as ra,Sa as Cb,T as sa,Ta as Db,U as ta,Ua as Eb,V as za,Va as Fb,W as Aa,Wa as Gb,X as Ba,Xa as Hb,Y as Ca,Ya as Ib,Z as Da,Za as Jb,_ as Ea,_a as Kb,aa as Ga,ab as Mb,ba as Ha,bb as Nb,ca as Ia,cb as Ob,d as q,da as Ja,db as Pb,e as r,ea as Ka,eb as Qb,f as s,fa as La,fb as Rb,g as D,ga as Ma,gb as Sb,h as E,ha as Na,hb as Tb,i as F,ia as Oa,ib as Ub,j as G,ja as Pa,jb as Vb,k as H,ka as Qa,kb as Wb,l as I,la as Ra,m as J,ma as Sa,n as K,na as Ta,o as L,oa as Ua,p as M,pa as Va,q as N,qa as Wa,r as O,ra as Xa,s as P,sa as Ya,t as Q,ta as Za,u as R,ua as _a,v as S,va as cb,w as T,wa as db,x as U,xa as eb,y as V,ya as fb,z as W,za as gb}from"./chunk-NNTQUHLO.js";import{b as mb,c as nb}from"./chunk-HGPBHTVD.js";import{k as $a}from"./chunk-Y3GFB5XM.js";import{d as yb}from"./chunk-3CZPBLB3.js";import{L as ab,N as bb,j as h,l as i}from"./chunk-LAWOWPZX.js";import"./chunk-EQIMHXC4.js";import"./chunk-VQUPKMDR.js";import"./chunk-WEZWKMYU.js";import"./chunk-YKKEI5GI.js";import"./chunk-ZNZFWSPH.js";import{a as t,b as u}from"./chunk-4EX2JJWB.js";import{a as $,g as aa,l as ba,p as ca}from"./chunk-BJGYGEZO.js";import"./chunk-RA6HKFBV.js";import"./chunk-AFTBQRPN.js";import"./chunk-XEBEWR6Y.js";import{e as x,f as y,g as z,h as A,i as B,j as C,r as xa,v as ya}from"./chunk-5DF5WJNM.js";import{a as v,b as w}from"./chunk-FX6MOGLR.js";import{Aa as m,Ba as n,Ca as o,Ea as p,Ga as ua,Ia as va,Ja as wa,ia as j,sa as k,za as l}from"./chunk-CK3P345X.js";import"./chunk-ZQ7LGTSN.js";import"./chunk-LACGULCN.js";import"./chunk-3TGQSGG4.js";import{G as e,H as f,M as g,s as a,v as b,w as c,x as d}from"./chunk-QUUEQRIT.js";import"./chunk-KDYEGGMW.js";import"./chunk-SKHLZ6XY.js";import"./chunk-6R73ICDB.js";import"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import"./chunk-CXT5IR5T.js";import"./chunk-AWFUHWQK.js";import"./chunk-G2V65UBA.js";import"./chunk-NHD2ESHA.js";import"./chunk-B3XBQEFM.js";import"./chunk-WHC7AYZD.js";export{_a as AgentSession,jb as AgentSessionRuntime,yb as ArminComponent,zb as AssistantMessageComponent,Ab as BashExecutionComponent,wb as BorderedLoader,Bb as BranchSummaryMessageComponent,e as CONFIG_DIR_NAME,E as CURRENT_SESSION_VERSION,Cb as CompactionSummaryMessageComponent,cb as CredentialSynchronizationError,Db as CustomEditor,Eb as CustomMessageComponent,O as DEFAULT_COMPACTION_SETTINGS,y as DEFAULT_MAX_BYTES,x as DEFAULT_MAX_LINES,eb as DefaultPackageManager,gb as DefaultResourceLoader,qb as DynamicBorder,xb as ExtensionEditorComponent,tb as ExtensionInputComponent,ga as ExtensionRunner,ub as ExtensionSelectorComponent,Fb as FooterComponent,Qb as InteractiveMode,Gb as LoginDialogComponent,ta as ModelRegistry,db as ModelRuntime,Hb as ModelSelectorComponent,Ib as OAuthSelectorComponent,nb as ProjectTrustStore,Sb as RpcClient,M as SessionManager,vb as SessionSelectorComponent,h as SettingsManager,Jb as SettingsSelectorComponent,Vb as ShowImagesSelectorComponent,Kb as SkillInvocationMessageComponent,j as Theme,Wb as ThemeSelectorComponent,Lb as ThinkingSelectorComponent,Mb as ToolExecutionComponent,Nb as TreeSelectorComponent,Ob as UserMessageComponent,Pb as UserMessageSelectorComponent,f as VERSION,Ya as VIRTUAL_MODEL_STATE_ENTRY,J as buildContextEntries,L as buildSessionContext,K as buildSessionProjection,P as calculateContextTokens,Y as collectEntriesForBranchSummary,X as compact,D as convertToLlm,s as convertToPng,pb as copyToClipboard,lb as createAgentSession,ib as createAgentSessionFromServices,kb as createAgentSessionRuntime,hb as createAgentSessionServices,Ba as createBashTool,Aa as createBashToolDefinition,ob as createCodemodeExtension,Wa as createCodingTools,Ha as createEditTool,Ga as createEditToolDefinition,$ as createEventBus,ba as createExtensionRuntime,Ja as createFindTool,Ia as createFindToolDefinition,La as createGrepTool,Ka as createGrepToolDefinition,za as createLocalBashOperations,Oa as createLocalPowerShellOperations,Na as createLsTool,Ma as createLsToolDefinition,rb as createMcpExtension,Qa as createPowerShellTool,Pa as createPowerShellToolDefinition,Xa as createReadOnlyTools,Ta as createReadTool,Sa as createReadToolDefinition,aa as createSyntheticSourceInfo,sb as createToolSearchExtension,Va as createWriteTool,Ua as createWriteToolDefinition,ha as defineTool,Ra as detectSupportedImageMimeTypeFromFile,ca as discoverAndLoadExtensions,S as estimateTokens,U as findCutPoint,T as findTurnStartIndex,u as formatDimensionNote,ya as formatReadLineRange,z as formatSize,ea as formatSkillsForPrompt,_ as generateBranchSummary,Da as generateDiffString,V as generateSummary,W as generateSummaryWithUsage,Ca as generateUnifiedPatch,g as getAgentDir,c as getDocsPath,d as getExamplesPath,m as getLanguageFromPath,Q as getLastAssistantUsage,H as getLatestCompactionEntry,n as getMarkdownTheme,a as getPackageDir,w as getPowerShellConfig,b as getReadmePath,o as getSelectListTheme,p as getSettingsListTheme,v as getShellConfig,mb as hasTrustRequiringProjectResources,l as highlightCode,k as initTheme,ia as isBashToolResult,la as isEditToolResult,oa as isFindToolResult,na as isGrepToolResult,pa as isLsToolResult,ja as isPowerShellToolResult,ka as isReadToolResult,qa as isToolCallEventType,ma as isWriteToolResult,va as keyHint,ua as keyText,fb as loadProjectContextFiles,fa as loadSkills,da as loadSkillsFromDir,Ub as main,F as migrateSessionEntries,i as parseArgs,q as parseFrontmatter,G as parseSessionEntries,Za as parseSkillBlock,Z as prepareBranchEntries,wa as rawKeyHint,$a as readStoredCredential,Fa as renderDiff,t as resizeImage,bb as resolveCliModel,ab as resolveModelScopeWithDiagnostics,Rb as runPrintMode,Tb as runRpcMode,N as serializeConversation,I as sessionEntryToContextMessages,R as shouldCompact,r as stripFrontmatter,A as truncateHead,C as truncateLine,B as truncateTail,xa as truncateToVisualLines,Ea as withFileMutationQueue,ra as wrapRegisteredTool,sa as wrapRegisteredTools};
|
|
@@ -1,4 +0,0 @@
|
|
|
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 a,g as b,h as c}from"./chunk-4YLAGSDM.js";import"./chunk-MGYYSX7Y.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";export{b as ExecutionRepo,a as TERMINAL_STATUSES,c as executionRepo};
|
|
@@ -1,4 +0,0 @@
|
|
|
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 g,c as F}from"./chunk-S3MR37DL.js";import{a as y}from"./chunk-2ROGTDM2.js";import{a as h}from"./chunk-NT32UURL.js";import"./chunk-LMDWRRX4.js";import"./chunk-UT6DGZDO.js";import"./chunk-ETIBCA2S.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-QUXPMNFQ.js";import"./chunk-KRXTI4JO.js";import{K as l}from"./chunk-W34AK4SK.js";import"./chunk-VBN2JSER.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";import*as b from"fs";import*as d from"path";function m(e){return{content:[{type:"text",text:typeof e=="string"?e:JSON.stringify(e,null,2)}]}}function w(e){return{content:[{type:"text",text:e}],isError:!0}}var S="Feishu is not configured (missing FEISHU_APP_ID / FEISHU_APP_SECRET). Set them in the Cortex config and restart, and grant the app docx/drive/wiki/bitable/sheets scopes.";function x(e){let t=e;if(t&&typeof t.code=="number"&&t.code!==0)throw new Error(`Feishu API error ${t.code}: ${t.msg??"unknown"}`);return t?.data??t}async function _(e,t){if(!e)return w(S);try{return await t(e)}catch(i){return w(`Feishu operation failed: ${i.message}`)}}function E(e){let t=d.extname(e).toLowerCase();return{".pdf":"pdf",".doc":"doc",".xls":"xls",".ppt":"ppt",".mp4":"mp4",".opus":"opus"}[t]||"stream"}async function N(e,t,i){let n=await e.im.v1.file.create({data:{file_type:E(i),file_name:i,file:b.readFileSync(t)}}),c=x(n).file_key;if(!c)throw new Error("Feishu file upload failed: no file_key returned");return c}async function k(e,{channel:t,filePath:i,fileName:n,title:c}){let{resolved:r,size:a}=h(i),p=n||d.basename(r),f=g(t,"feishu:"),s=await y(e,r,a),u=s?"image":"file",o=JSON.stringify(s?{image_key:s}:{file_key:await N(e,r,p)});return await e.im.v1.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:f,msg_type:u,content:o}}),{path:r,fileName:p,size:a}}function z(e,t){e.tool("feishu_send_file","Share a local or remote-device file in Feishu.",{file_path:l.string().describe("File path to upload. Local path, or an absolute path on `device`."),file_name:l.string().optional().describe("Optional filename override shown in Feishu"),title:l.string().optional().describe("Optional file title shown in Feishu"),channel:l.string().optional().describe("Optional chat/channel ID (uses route context if not provided)"),device:l.string().optional().describe("Connected device to read from; omit for this server.")},async({file_path:i,file_name:n,title:c,channel:r,device:a})=>_(t.client,async p=>{let f=r||t.fallbackChannel||"";if(!f)throw new Error("No Feishu channel available (no session channel or channel parameter)");let s=(o,v)=>k(p,{channel:f,filePath:o,fileName:v,title:c});if(!a){let o=await s(i,n);return m(`File uploaded: ${o.fileName} (${o.size} bytes)`)}let u=await F(t.ctx,a,i,o=>s(o.localPath,n||o.name));return m(`File uploaded from ${a}: ${u.fileName} (${u.size} bytes)`)}))}export{z as registerFileTools,k as uploadFileToFeishu};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{d as w}from"./chunk-VQUPKMDR.js";import{a as g}from"./chunk-JXFG66UN.js";import{a as y}from"./chunk-ILEML5IP.js";import"./chunk-WHC7AYZD.js";var U=e=>atob(e),x=U("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),f={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},S="2026-06-01";function _(e){let t=e.trim();if(!t)return null;try{return(t.includes("://")?new URL(t):new URL(`https://${t}`)).hostname}catch{return null}}function h(e){return{deviceCodeUrl:`https://${e}/login/device/code`,accessTokenUrl:`https://${e}/login/oauth/access_token`,copilotTokenUrl:`https://api.${e}/copilot_internal/v2/token`}}function A(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,"api.")}`:null}function b(e,t){if(e){let n=A(e);if(n)return n}return t?`https://copilot-api.${t}`:"https://api.individual.githubcopilot.com"}function p(e){return e&&typeof e=="object"?e:void 0}function M(e,t){let n=p(e)?.data;if(!Array.isArray(n))throw new Error("Invalid Copilot models response");let o=n.flatMap(i=>{let l=p(i),d=l?.id;if(!l||typeof d!="string")return[];let u=p(l.capabilities);return p(u?.supports)?.tool_calls===!1?[]:[{id:d,pickerEnabled:l.model_picker_enabled===!0,policyState:p(l.policy)?.state}]}),r=o.filter(i=>i.pickerEnabled&&i.policyState!=="disabled").map(i=>i.id),a=t&&r.length===0,s=r.length>0||!t?r:o.filter(i=>i.policyState==="enabled").map(i=>i.id),c=o.filter(i=>i.policyState==="unconfigured"&&Object.hasOwn(w,i.id)&&(i.pickerEnabled||a)).map(i=>i.id);return{availableModelIds:s,policyModelIds:c}}async function C(e,t,n,o){let r=o.maxRetries>0&&o.maxElapsedMs>0?AbortSignal.timeout(o.maxElapsedMs):void 0,a=r?AbortSignal.any([n,r]):n,s=r?Date.now()+o.maxElapsedMs:void 0;for(let c=0;;c++){let i=await fetch(e,{...t,signal:AbortSignal.any([a,AbortSignal.timeout(5e3)])});if(i.status!==429||c===o.maxRetries)return i;let l=i.headers.get("retry-after"),d=500*2**c;if(l){let u=Number.parseFloat(l);if(d=Number.isNaN(u)?Date.parse(l)-Date.now():u*1e3,!Number.isFinite(d))return i}if(d=Math.max(0,d),s!==void 0&&d>=s-Date.now())return i;await i.body?.cancel(),await g(d,a)}}async function E(e,t,n,o){let r=b(e,t),a=r==="https://api.individual.githubcopilot.com",s=await C(`${r}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`,...f,"X-GitHub-Api-Version":S}},n,o);if(!s.ok)throw new Error(`${s.status} ${s.statusText}: ${await s.text()}`);return M(await s.json(),a)}async function m(e,t){let n=await fetch(e,t);if(!n.ok){let o=await n.text();throw new Error(`${n.status} ${n.statusText}: ${o}`)}return n.json()}async function k(e,t){let n=h(e),o=await m(n.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:x,scope:"read:user"}),signal:t});if(!o||typeof o!="object")throw new Error("Invalid device code response");let r=o.device_code,a=o.user_code,s=o.verification_uri,c=o.interval,i=o.expires_in;if(typeof r!="string"||typeof a!="string"||typeof s!="string"||c!==void 0&&typeof c!="number"||typeof i!="number")throw new Error("Invalid device code response fields");let l;try{l=new URL(s)}catch{throw new Error("Untrusted verification_uri in device code response")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:r,user_code:a,verification_uri:l.href,interval:c,expires_in:i}}async function $(e,t,n){let o=h(e);return y({intervalSeconds:t.interval,expiresInSeconds:t.expires_in,waitBeforeFirstPoll:!0,signal:n,poll:async()=>{let r=await m(o.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:x,device_code:t.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:n});if(r&&typeof r=="object"&&typeof r.access_token=="string")return{status:"complete",value:r.access_token};if(r&&typeof r=="object"&&typeof r.error=="string"){let{error:a,error_description:s,interval:c}=r;if(a==="authorization_pending")return{status:"pending"};if(a==="slow_down")return{status:"slow_down",intervalSeconds:typeof c=="number"?c:void 0};let i=s?`: ${s}`:"";return{status:"failed",message:`Device flow failed: ${a}${i}`}}return{status:"failed",message:"Invalid device token response"}}})}async function I(e,t,n){let r=h(t||"github.com"),a=await m(r.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`,...f},signal:n});if(!a||typeof a!="object")throw new Error("Invalid Copilot token response");let s=a.token,c=a.expires_at;if(typeof s!="string"||typeof c!="number")throw new Error("Invalid Copilot token response fields");return{type:"oauth",refresh:e,access:s,expires:c*1e3-300*1e3,enterpriseUrl:t}}async function T(e,t,n){let o=await I(e,t,n),{availableModelIds:r}=await E(o.access,t,n,{maxRetries:0,maxElapsedMs:0});return{...o,availableModelIds:r}}async function H(e,t,n,o){let a=`${b(e,n)}/models/${t}/policy`,s;try{s=await C(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...f,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},o,{maxRetries:2,maxElapsedMs:5e3})}catch(c){if(o.aborted)throw c;return!1}if(s.status===429)throw new Error(`${s.status} ${s.statusText}: ${await s.text()}`);return s.ok}async function O(e,t,n,o){let r=[];for(let a of t)try{await H(e,a,n,o)&&r.push(a)}catch(s){if(o.aborted)throw s;break}return r}async function G(e){let t=await e.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(e.signal.aborted)throw new Error("Login cancelled");let n=t.trim(),o=_(t);if(n&&!o)throw new Error("Invalid GitHub Enterprise URL/domain");let r=o||"github.com",a=await k(r,e.signal);e.notify({type:"device_code",userCode:a.user_code,verificationUri:a.verification_uri,intervalSeconds:a.interval,expiresInSeconds:a.expires_in});let s=await $(r,a,e.signal),c=await I(s,o??void 0,e.signal),i=await E(c.access,o??void 0,e.signal,{maxRetries:2,maxElapsedMs:5e3}),l=[];return i.policyModelIds.length>0&&(e.notify({type:"progress",message:"Enabling models..."}),l=await O(c.access,i.policyModelIds,o??void 0,e.signal)),{...c,availableModelIds:[...new Set([...i.availableModelIds,...l])]}}function v(e){let t=e.enterpriseUrl;if(!(typeof t!="string"||!t))return _(t)??void 0}var F={name:"GitHub Copilot",isSubscription:!0,login:G,refresh:(e,t)=>T(e.refresh,v(e),t),async toAuth(e){return{apiKey:e.access,baseUrl:b(e.access,v(e))}}};export{F as githubCopilotOAuth};
|
|
@@ -1,4 +0,0 @@
|
|
|
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 A,c as $,d as N,e as B,f as K,g as U,h as W,i as x,j as q,k as z,l as D,m as j,n as H,o as F}from"./chunk-YB5LUJHS.js";import{a as L,b as O}from"./chunk-FF7UELTU.js";import"./chunk-23PRJECN.js";import{i as P}from"./chunk-QBKCAIJG.js";import{J as M,L as _,o as S,s as I,u as v,x as R}from"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import{a as E}from"./chunk-USBJFDJ6.js";import{b as G}from"./chunk-K4NTZEDJ.js";import{h as T}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as w}from"./chunk-CXT5IR5T.js";import"./chunk-QN44UXQR.js";import"./chunk-I6OPDRVF.js";import"./chunk-2YTYYG4K.js";import"./chunk-SAJD4EKE.js";import"./chunk-WHC7AYZD.js";var J=0,y=(n,a,t)=>{let o=new w,s=R(a);return(async()=>{let e={role:"assistant",content:[],api:"google-generative-ai",provider:n.provider,model:n.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()};try{if(t?.fetch&&t.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let l=t?.apiKey;if(!l)throw new Error(`No API key for provider: ${n.provider}`);let d=V(n,l,t?.headers,t?.identity),h=Q(n,s,t),k=await t?.onPayload?.(h,n);k!==void 0&&(h=k);let p=await F(()=>d.models.generateContentStream(h),t);o.push({type:"start",partial:e});let i=null,f=e.content,u=()=>f.length-1;for await(let g of p){await t?.onProviderStreamEvent?.(g,n),e.responseId||=g.responseId;let m=g.candidates?.[0];if(m?.content?.parts)for(let r of m.content.parts){if(r.text!==void 0){let c=W(r);(!i||c&&i.type!=="thinking"||!c&&i.type!=="text")&&(i&&(i.type==="text"?o.push({type:"text_end",contentIndex:f.length-1,content:i.text,partial:e}):o.push({type:"thinking_end",contentIndex:u(),content:i.thinking,partial:e})),c?(i={type:"thinking",thinking:"",thinkingSignature:void 0},e.content.push(i),o.push({type:"thinking_start",contentIndex:u(),partial:e})):(i={type:"text",text:""},e.content.push(i),o.push({type:"text_start",contentIndex:u(),partial:e}))),i.type==="thinking"?(i.thinking+=r.text,i.thinkingSignature=x(i.thinkingSignature,r.thoughtSignature),o.push({type:"thinking_delta",contentIndex:u(),delta:r.text,partial:e})):(i.text+=r.text,i.textSignature=x(i.textSignature,r.thoughtSignature),o.push({type:"text_delta",contentIndex:u(),delta:r.text,partial:e}))}if(r.functionCall){i&&(i.type==="text"?o.push({type:"text_end",contentIndex:u(),content:i.text,partial:e}):o.push({type:"thinking_end",contentIndex:u(),content:i.thinking,partial:e}),i=null);let c=r.functionCall.id,C={type:"toolCall",id:!c||e.content.some(b=>b.type==="toolCall"&&b.id===c)?`${r.functionCall.name}_${Date.now()}_${++J}`:c,name:r.functionCall.name||"",arguments:r.functionCall.args??{},...r.thoughtSignature&&{thoughtSignature:r.thoughtSignature}};e.content.push(C),o.push({type:"toolcall_start",contentIndex:u(),partial:e}),o.push({type:"toolcall_delta",contentIndex:u(),delta:JSON.stringify(C.arguments),partial:e}),o.push({type:"toolcall_end",contentIndex:u(),toolCall:C,partial:e})}}m?.finishReason&&(e.rawStopReason=m.finishReason,e.stopReason=H(m.finishReason),e.content.some(r=>r.type==="toolCall")&&e.stopReason==="stop"&&(e.stopReason="toolUse")),g.usageMetadata&&(e.usage={input:(g.usageMetadata.promptTokenCount||0)-(g.usageMetadata.cachedContentTokenCount||0),output:(g.usageMetadata.candidatesTokenCount||0)+(g.usageMetadata.thoughtsTokenCount||0),cacheRead:g.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:g.usageMetadata.thoughtsTokenCount||0,totalTokens:g.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},M(n,e.usage))}if(i&&(i.type==="text"?o.push({type:"text_end",contentIndex:u(),content:i.text,partial:e}):o.push({type:"thinking_end",contentIndex:u(),content:i.thinking,partial:e})),t?.signal?.aborted)throw new Error("Request was aborted");if(e.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(e.stopReason==="aborted"||e.stopReason==="error"){let g=e.rawStopReason?`Provider stopped with: ${e.rawStopReason}`:"An unknown error occurred";throw new Error(g)}o.push({type:"done",reason:e.stopReason,message:e}),o.end()}catch(l){for(let d of e.content)"index"in d&&delete d.index;e.stopReason=t?.signal?.aborted?"aborted":"error",e.errorMessage=O(L(l)),o.push({type:"error",reason:e.stopReason,error:e}),o.end()}})(),o},de=(n,a,t)=>{let o=t?.apiKey;if(!o)throw new Error(`No API key for provider: ${n.provider}`);let s={...P(n,a,t,o),toolChoice:t?.toolChoice};if(!t?.reasoning)return y(n,a,{...s,thinking:{enabled:!1}});let e=_(n,t.reasoning);if(e==="off")return y(n,a,{...s,thinking:{enabled:!1}});let l=$(n,e);return N(n)?y(n,a,{...s,thinking:{enabled:!0,level:B(l)}}):y(n,a,{...s,thinking:{enabled:!0,budgetTokens:X(n,l,t.thinkingBudgets)}})};function V(n,a,t,o){let s={};n.baseUrl&&(s.baseUrl=n.baseUrl,s.apiVersion="");let e=G(T(n,o),n.headers,t);return e&&(s.headers=e),new A({apiKey:a,httpOptions:Object.keys(s).length>0?s:void 0})}function Q(n,a,t={}){let o=q(n,a),s=I(a.messages),e=v(a.messages),l={};t.temperature!==void 0&&(l.temperature=t.temperature),t.maxTokens!==void 0&&(l.maxOutputTokens=t.maxTokens);let d=D(n.id),h=e.length>0?j(e,t.toolChoice,d):void 0,k=s?S(s):"",p={...Object.keys(l).length>0&&l,...k&&{systemInstruction:E(k)},...e.length>0&&{tools:z(e,!1,d)},...h!==void 0&&{toolConfig:{functionCallingConfig:{mode:h}}}};if(t.thinking?.enabled&&n.reasoning){let f={includeThoughts:!0};t.thinking.level!==void 0?f.thinkingLevel=K(t.thinking.level):t.thinking.budgetTokens!==void 0&&(f.thinkingBudget=t.thinking.budgetTokens),p.thinkingConfig=f}else n.reasoning&&t.thinking&&!t.thinking.enabled&&(p.thinkingConfig=U(n));if(t.signal){if(t.signal.aborted)throw new Error("Request aborted");p.abortSignal=t.signal}return{model:n.id,contents:o,config:p}}function X(n,a,t){return t?.[a]!==void 0?t[a]:n.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[a]:n.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[a]:n.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[a]:-1}export{y as stream,de as streamSimple};
|
|
@@ -1,4 +0,0 @@
|
|
|
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 D,b as T,c as V,d as N,e as j,f as K,g as $,h as q,i as b,j as B,k as J,l as W,m as z,n as H,o as F}from"./chunk-YB5LUJHS.js";import{a as P,b as U}from"./chunk-FF7UELTU.js";import{a as C}from"./chunk-6R73ICDB.js";import"./chunk-23PRJECN.js";import{i as A}from"./chunk-QBKCAIJG.js";import{J as E,L as G,o as R,s as S,u as w,x as _}from"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import{a as M}from"./chunk-USBJFDJ6.js";import{b as L}from"./chunk-K4NTZEDJ.js";import{h as O}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as I}from"./chunk-CXT5IR5T.js";import"./chunk-QN44UXQR.js";import"./chunk-I6OPDRVF.js";import"./chunk-2YTYYG4K.js";import"./chunk-SAJD4EKE.js";import"./chunk-WHC7AYZD.js";var X="v1",Y="gcp-vertex-credentials",Z=0,y=(e,o,n)=>{let i=new I,s=_(o);return(async()=>{let t={role:"assistant",content:[],api:"google-vertex",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()};try{if(n?.fetch&&n.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let l=re(n),g=l?te(e,l,n?.headers,n?.identity):ee(e,se(n),ue(n),n?.headers,n?.env,n?.identity),h=le(e,s,n),m=await n?.onPayload?.(h,e);m!==void 0&&(h=m);let p=await F(()=>g.models.generateContentStream(h),n);i.push({type:"start",partial:t});let r=null,f=t.content,c=()=>f.length-1;for await(let u of p){await n?.onProviderStreamEvent?.(u,e),t.responseId||=u.responseId;let k=u.candidates?.[0];if(k?.content?.parts)for(let a of k.content.parts){if(a.text!==void 0){let d=q(a);(!r||d&&r.type!=="thinking"||!d&&r.type!=="text")&&(r&&(r.type==="text"?i.push({type:"text_end",contentIndex:f.length-1,content:r.text,partial:t}):i.push({type:"thinking_end",contentIndex:c(),content:r.thinking,partial:t})),d?(r={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(r),i.push({type:"thinking_start",contentIndex:c(),partial:t})):(r={type:"text",text:""},t.content.push(r),i.push({type:"text_start",contentIndex:c(),partial:t}))),r.type==="thinking"?(r.thinking+=a.text,r.thinkingSignature=b(r.thinkingSignature,a.thoughtSignature),i.push({type:"thinking_delta",contentIndex:c(),delta:a.text,partial:t})):(r.text+=a.text,r.textSignature=b(r.textSignature,a.thoughtSignature),i.push({type:"text_delta",contentIndex:c(),delta:a.text,partial:t}))}if(a.functionCall){r&&(r.type==="text"?i.push({type:"text_end",contentIndex:c(),content:r.text,partial:t}):i.push({type:"thinking_end",contentIndex:c(),content:r.thinking,partial:t}),r=null);let d=a.functionCall.id,x={type:"toolCall",id:!d||t.content.some(v=>v.type==="toolCall"&&v.id===d)?`${a.functionCall.name}_${Date.now()}_${++Z}`:d,name:a.functionCall.name||"",arguments:a.functionCall.args??{},...a.thoughtSignature&&{thoughtSignature:a.thoughtSignature}};t.content.push(x),i.push({type:"toolcall_start",contentIndex:c(),partial:t}),i.push({type:"toolcall_delta",contentIndex:c(),delta:JSON.stringify(x.arguments),partial:t}),i.push({type:"toolcall_end",contentIndex:c(),toolCall:x,partial:t})}}k?.finishReason&&(t.rawStopReason=k.finishReason,t.stopReason=H(k.finishReason),t.content.some(a=>a.type==="toolCall")&&t.stopReason==="stop"&&(t.stopReason="toolUse")),u.usageMetadata&&(t.usage={input:(u.usageMetadata.promptTokenCount||0)-(u.usageMetadata.cachedContentTokenCount||0),output:(u.usageMetadata.candidatesTokenCount||0)+(u.usageMetadata.thoughtsTokenCount||0),cacheRead:u.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:u.usageMetadata.thoughtsTokenCount||0,totalTokens:u.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},E(e,t.usage))}if(r&&(r.type==="text"?i.push({type:"text_end",contentIndex:c(),content:r.text,partial:t}):i.push({type:"thinking_end",contentIndex:c(),content:r.thinking,partial:t})),n?.signal?.aborted)throw new Error("Request was aborted");if(t.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(t.stopReason==="aborted"||t.stopReason==="error"){let u=t.rawStopReason?`Provider stopped with: ${t.rawStopReason}`:"An unknown error occurred";throw new Error(u)}i.push({type:"done",reason:t.stopReason,message:t}),i.end()}catch(l){for(let g of t.content)"index"in g&&delete g.index;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=U(P(l)),i.push({type:"error",reason:t.stopReason,error:t}),i.end()}})(),i},Oe=(e,o,n)=>{let i={...A(e,o,n,void 0),toolChoice:n?.toolChoice};if(!n?.reasoning)return y(e,o,{...i,thinking:{enabled:!1}});let s=G(e,n.reasoning);if(s==="off")return y(e,o,{...i,thinking:{enabled:!1}});let t=V(e,s);return N(e)?y(e,o,{...i,thinking:{enabled:!0,level:j(t)}}):y(e,o,{...i,thinking:{enabled:!0,budgetTokens:ce(e,t,n.thinkingBudgets)}})};function ee(e,o,n,i,s,t){let l=ie(s);return new T({vertexai:!0,project:o,location:n,apiVersion:X,...l?{googleAuthOptions:l}:{},httpOptions:Q(e,i,t)})}function te(e,o,n,i){return new T({vertexai:!0,apiKey:o,apiVersion:X,httpOptions:Q(e,n,i)})}function Q(e,o,n){let i={},s=ne(e.baseUrl);s&&(i.baseUrl=s,i.baseUrlResourceScope=D.COLLECTION,oe(s)&&(i.apiVersion=""));let t=L(O(e,n),e.headers,o);return t&&(i.headers=t),Object.keys(i).length>0?i:void 0}function ne(e){let o=e.trim();if(!(!o||o.includes("{location}")))return o}function oe(e){try{return new URL(e).pathname.split("/").some(n=>/^v\d+(?:beta\d*)?$/.test(n))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(e)}}function ie(e){let o=C("GOOGLE_APPLICATION_CREDENTIALS",e);return o?{keyFilename:o}:void 0}function re(e){let o=e?.apiKey?.trim();if(!(!o||o===Y||ae(o)))return o}function ae(e){return/^<[^>]+>$/.test(e)}function se(e){let o=e?.project||C("GOOGLE_CLOUD_PROJECT",e?.env)||C("GCLOUD_PROJECT",e?.env);if(!o)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return o}function ue(e){let o=e?.location||C("GOOGLE_CLOUD_LOCATION",e?.env);if(!o)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return o}function le(e,o,n={}){let i=B(e,o),s=S(o.messages),t=w(o.messages),l={};n.temperature!==void 0&&(l.temperature=n.temperature),n.maxTokens!==void 0&&(l.maxOutputTokens=n.maxTokens);let g=W(e.id),h=t.length>0?z(t,n.toolChoice,g):void 0,m=s?R(s):"",p={...Object.keys(l).length>0&&l,...m&&{systemInstruction:M(m)},...t.length>0&&{tools:J(t,!1,g)},...h!==void 0&&{toolConfig:{functionCallingConfig:{mode:h}}}};if(n.thinking?.enabled&&e.reasoning){let f={includeThoughts:!0};n.thinking.level!==void 0?f.thinkingLevel=K(n.thinking.level):n.thinking.budgetTokens!==void 0&&(f.thinkingBudget=n.thinking.budgetTokens),p.thinkingConfig=f}else e.reasoning&&n.thinking&&!n.thinking.enabled&&(p.thinkingConfig=$(e));if(n.signal){if(n.signal.aborted)throw new Error("Request aborted");p.abortSignal=n.signal}return{model:e.id,contents:i,config:p}}function ce(e,o,n){return n?.[o]!==void 0?n[o]:e.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[o]:e.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[o]:-1}export{y as stream,Oe as streamSimple};
|
|
@@ -1,4 +0,0 @@
|
|
|
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,h as d,i as e,j as f,k as g,l as h,m as i,n as j,o as k,p as l,q as m,r as n,s as o,t as p,u as q,v as r,w as s,x as t}from"./chunk-KDPY2YA3.js";import"./chunk-P7TVR4GY.js";import"./chunk-3ORG56I5.js";import"./chunk-2VVRTJQN.js";import"./chunk-53TQNK7Z.js";import"./chunk-RF4JLYBX.js";import"./chunk-2ATTYCRJ.js";import"./chunk-7GEBDPTT.js";import"./chunk-V7K3KNDM.js";import"./chunk-5T7IX5KN.js";import"./chunk-V6X7Y62J.js";import"./chunk-KUDK7GPS.js";import"./chunk-BDLKI2NT.js";import"./chunk-JJDEQ6N2.js";import"./chunk-MGYYSX7Y.js";import"./chunk-RA2BUYI3.js";import"./chunk-U23S37TT.js";import"./chunk-T73GHMFB.js";import"./chunk-NNBSSISP.js";import"./chunk-V35MFAUQ.js";import"./chunk-OKRK6JPY.js";import"./chunk-OE4KH3NJ.js";import"./chunk-VK5J556O.js";import"./chunk-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import"./chunk-QUXPMNFQ.js";import"./chunk-PMG4YGDU.js";import"./chunk-LP7T32PW.js";import"./chunk-BUZQBTV2.js";import"./chunk-STCNHXPJ.js";import"./chunk-STUHNKQS.js";import"./chunk-NRD57ICT.js";import"./chunk-KRXTI4JO.js";import"./chunk-W34AK4SK.js";import"./chunk-TX46YMGI.js";import"./chunk-Q4UGYGU5.js";import"./chunk-AVXDF7AG.js";import"./chunk-3CPIMAYX.js";import"./chunk-VBN2JSER.js";import"./chunk-NXZS5PEW.js";import"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";export{i as SLACK_APP_MANIFEST,c as ensureGitInstalled,h as formatConfigOutput,q as generateConfigs,g as generateDefaultModeJson,f as generateDotEnvContent,m as generateLaunchdPlist,l as generateSystemdUnit,b as getGitInstallHint,k as getInstallCommand,d as getResolvedPaths,j as isBackendInstalled,a as isGitInstalled,e as parseInitAnswersJson,o as parseInitAnswersLines,n as runFeishuUserLogin,s as runInit,p as safeCopy,r as writeDotEnv,t as writeInitConfigs};
|
|
@@ -1,4 +0,0 @@
|
|
|
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 _}from"./chunk-JXFG66UN.js";import{a as w}from"./chunk-ILEML5IP.js";import{a as d}from"./chunk-6R73ICDB.js";import"./chunk-WHC7AYZD.js";var f="17e5f671-d194-4dfb-9706-5516cb48c098",C="https://auth.kimi.com",E=900,k=5,T=30*1e3,y=3;function S(){return(d("KIMI_CODE_OAUTH_HOST")||d("KIMI_OAUTH_HOST")||C).replace(/\/+$/,"")}function p(e){return AbortSignal.any([AbortSignal.timeout(T),e])}function l(e){return new URLSearchParams(e).toString()}async function h(e){try{let o=await e.json();return o&&typeof o=="object"?o:null}catch{return null}}function g(e){if(typeof e!="string"||!e)return null;try{let o=new URL(e);return o.protocol!=="https:"&&o.protocol!=="http:"?null:o.href}catch{return null}}async function $(e,o){let r=await fetch(`${e}/api/oauth/device_authorization`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l({client_id:f}),signal:p(o)});if(!r.ok){let m=await r.text().catch(()=>"");throw new Error(`Kimi Code device authorization failed with status ${r.status}${m?`: ${m}`:""}`)}let t=await h(r),n=t?.device_code,i=t?.user_code,a=t?.verification_uri,s=t?.verification_uri_complete;if(typeof n!="string"||typeof i!="string"||typeof a!="string"||typeof s!="string"||!g(s)||!g(a))throw new Error(`Invalid Kimi Code device authorization response: ${JSON.stringify(t)}`);let c=t?.interval,u=t?.expires_in;return{deviceCode:n,userCode:i,verificationUri:a,verificationUriComplete:s,intervalSeconds:typeof c=="number"&&Number.isFinite(c)&&c>0?c:k,expiresInSeconds:typeof u=="number"&&Number.isFinite(u)&&u>0?u:E}}function v(e,o){let r=e?.access_token,t=e?.refresh_token,n=e?.expires_in;if(typeof r!="string"||!r||typeof t!="string"||!t||typeof n!="number"||!Number.isFinite(n)||n<=0)throw new Error(`Kimi Code token ${o} response missing fields: ${JSON.stringify(e)}`);return{access:r,refresh:t,expires:Date.now()+n*1e3}}async function x(e,o,r){return w({intervalSeconds:o.intervalSeconds,expiresInSeconds:o.expiresInSeconds,waitBeforeFirstPoll:!0,signal:r,poll:async()=>{let t=await fetch(`${e}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l({client_id:f,device_code:o.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:p(r)});if(t.status>=500){let s=await t.text().catch(()=>"");return{status:"failed",message:`Kimi Code device token request failed with status ${t.status}${s?`: ${s}`:""}`}}let n=await h(t);if(t.ok&&typeof n?.access_token=="string")try{return{status:"complete",value:v(n,"poll")}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}let i=n?.error,a=typeof n?.error_description=="string"?`: ${n.error_description}`:"";if(i==="authorization_pending")return{status:"pending"};if(i==="slow_down"){let s=n?.interval;return{status:"slow_down",intervalSeconds:typeof s=="number"&&s>0?s:void 0}}return i==="expired_token"?{status:"failed",message:"Kimi Code device authorization expired. Please restart login."}:i==="access_denied"?{status:"failed",message:"Kimi Code login was denied."}:{status:"failed",message:`Kimi Code device token request failed (status ${t.status})${typeof i=="string"?`: ${i}${a}`:""}`}}})}function O(e){return e.status===429||e.status>=500}async function b(e,o,r){let t;for(let n=0;n<=y;n++){if(n>0&&await _(1e3*2**(n-1),r),r.aborted)throw new Error("Kimi Code token refresh aborted");let i;try{i=await fetch(`${e}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l({client_id:f,grant_type:"refresh_token",refresh_token:o}),signal:p(r)})}catch(c){t=c instanceof Error?c:new Error(String(c));continue}let a=await h(i);if(i.ok)return v(a,"refresh");if(i.status===401||i.status===403||a?.error==="invalid_grant"){let c=typeof a?.error_description=="string"?`: ${a.error_description}`:"";throw new Error(`Kimi Code token refresh unauthorized (status ${i.status})${c}`)}if(O(i)&&n<y){t=new Error(`Kimi Code token refresh failed with status ${i.status}`);continue}let s=JSON.stringify(a);throw new Error(`Kimi Code token refresh failed with status ${i.status}${s?`: ${s}`:""}`)}throw t??new Error("Kimi Code token refresh failed")}async function I(e){let o=S(),r=await $(o,e.signal);e.notify({type:"device_code",userCode:r.userCode,verificationUri:r.verificationUriComplete,intervalSeconds:r.intervalSeconds,expiresInSeconds:r.expiresInSeconds});let t=await x(o,r,e.signal);return{type:"oauth",access:t.access,refresh:t.refresh,expires:t.expires}}var D={name:"Kimi Code (subscription)",isSubscription:!0,loginLabel:"Sign in with Kimi Code",login:I,refresh:async(e,o)=>{let r=await b(S(),e.refresh,o);return{type:"oauth",access:r.access,refresh:r.refresh,expires:r.expires}},async toAuth(e){return{headers:{Authorization:`Bearer ${e.access}`}}}};export{D as kimiCodingOAuth};
|
|
@@ -1,4 +0,0 @@
|
|
|
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 m,b as f,e as p,f as d,g as L}from"./chunk-LQTFDC67.js";import{b as l,g as u}from"./chunk-53TQNK7Z.js";import{a as s}from"./chunk-LP7T32PW.js";import"./chunk-AVXDF7AG.js";import{d as a,i as c}from"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";import*as y from"fs";import*as C from"path";import{execFileSync as S}from"child_process";var g=5e3,I=2e3,v=100;function w(e){S("taskkill",["/PID",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0})}function P(){try{return JSON.parse(y.readFileSync(C.join(c,"machines.json"),"utf8"))}catch{return{}}}var _={platform:process.platform,registry:P,alive:s,commandLine:L,terminate:e=>process.platform==="win32"?w(e):void process.kill(e,"SIGTERM"),kill:e=>process.platform==="win32"?w(e):void process.kill(e,"SIGKILL"),sleep:e=>new Promise(t=>setTimeout(t,e))};function k(e,t,n){let r=i=>n==="win32"?i.replace(/\//g,"\\").toLowerCase():i;return r(e).includes(r(t))}async function h(e,t,n){for(let r=0;r<t;r+=v){if(!n.alive(e))return!0;await n.sleep(v)}return!n.alive(e)}async function E(e,t){if(!t.alive(e))return"not-running";let n=t.commandLine(e);if(n===null)return t.alive(e)?"unverified":"not-running";if(!k(n,m(),t.platform))return"reused";try{t.terminate(e)}catch{}if(await h(e,g,t))return"stopped";try{t.kill(e)}catch{}return await h(e,I,t)?"stopped":"survived"}async function T(e){let t={DATA_DIR:a,CONFIG_DIR:c},n;try{n=l(t)?.device}catch{return}let r=e.find(i=>i.device===n);!n||!r||!["stopped","not-running","reused"].includes(r.outcome)||await u(t,n).catch(()=>{})}async function R(e=_){let t=e.registry(),n=[];for(let[r,i]of Object.entries(f())){if(!d(t[r])||!Number.isInteger(i)||i<=0)continue;let o=await E(i,e);o!=="unverified"&&o!=="survived"&&p(r),n.push({device:r,pid:i,outcome:o})}return await T(n),n}export{k as runsLocalClientEntry,R as stopLaunchedLocalClients};
|
|
@@ -1,11 +0,0 @@
|
|
|
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 I,d as S,e as T,g as M}from"./chunk-ROVKOIHF.js";import{f as E}from"./chunk-W6AKCEYF.js";import"./chunk-V35MFAUQ.js";import{b as D}from"./chunk-PMG4YGDU.js";import"./chunk-AVXDF7AG.js";import"./chunk-3CPIMAYX.js";import"./chunk-VBN2JSER.js";import{s as v}from"./chunk-Z24SBRJK.js";import"./chunk-VPVSKJGX.js";import"./chunk-WHC7AYZD.js";import*as j from"fs";import*as y from"path";var R=["superseded","deprecated","invalidated"];function C(s){if(!s)return!1;let e=String(s).toLowerCase();return R.some(c=>e.startsWith(c))}function U(s){if(!s)return null;let e=new Date(String(s));return isNaN(e.getTime())?null:(Date.now()-e.getTime())/864e5}function b(s,e,c){let r=[],n=e.filter(p=>!C(p.meta.status)),t=new Map;for(let p of n)for(let d of w(p.meta.tags)){let l=d.toLowerCase().trim();l&&(t.has(l)||t.set(l,[]),t.get(l).push(p.id))}let i=c.map(p=>({id:p.id,tags:new Set(w(p.meta.tags).map(d=>d.toLowerCase()))})),o=[...t.keys()].filter(p=>(t.get(p)?.length??0)>=2),a=new Set;for(let p=0;p<o.length;p++)for(let d=p+1;d<o.length;d++){let l=o[p],u=o[d],g=new Set(t.get(l)),h=t.get(u).filter(m=>g.has(m));if(h.length<3)continue;let f=[...h].sort().join(",");if(a.has(f))continue;a.add(f);let x=i.filter(m=>m.tags.has(l)&&m.tags.has(u)).map(m=>m.id);r.push({type:"tag-cluster",project:s,tags:[l,u],experiments:h,existingPatterns:x,reason:`${h.length} experiments share tags [${l}, ${u}]`})}return r}function F(s,e){let c=[],r=e.filter(i=>!C(i.meta.status)),n=new Map;for(let i of r){let o=w(i.meta.links);if(o.length!==0){n.has(i.id)||n.set(i.id,new Set);for(let a of o)n.get(i.id).add(a.toUpperCase().trim())}}let t=new Set;for(let[i]of n){if(t.has(i))continue;let o=[],a=[i];for(;a.length>0;){let p=a.pop();if(t.has(p))continue;t.add(p),o.push(p);let d=n.get(p);if(d)for(let l of d)!t.has(l)&&n.has(l)&&a.push(l)}o.length>=3&&c.push({type:"link-cluster",project:s,experiments:o,existingPatterns:[],reason:`${o.length} experiments form a connected link cluster`})}return c}function W(s,e){let c=[],r=new Map;for(let i of e){let a=String(i.meta.status||"").match(/^(?:superseded|refined):(.+)/i);a&&r.set(i.id.toUpperCase(),a[1].toUpperCase().trim())}let n=new Set(r.values()),t=[...r.keys()].filter(i=>!n.has(i));for(let i of t){let o=[i],a=i;for(;r.has(a)&&(a=r.get(a),o.push(a),!(o.length>20)););o.length>=3&&c.push({type:"supersede-chain",project:s,experiments:o,existingPatterns:[],reason:`Supersession chain of length ${o.length}: ${o.join(" \u2192 ")}`})}return c}function K(s,e,c,r){let n=[],t=new Map;for(let o of e)t.set(o.id.toUpperCase(),String(o.meta.status||"active").toLowerCase());let i=[...c.map(o=>({...o,entryType:"knowledge",dir:"knowledge"})),...r.map(o=>({...o,entryType:"pattern",dir:"patterns"}))];for(let o of i){let a=[];for(let u of["evidence","source-experiments","source"]){let g=o.meta[u];if(Array.isArray(g))a.push(...w(g).map(h=>h.toUpperCase().trim()));else if(typeof g=="string"){let h=String(g).matchAll(/EXP-\d+/gi);for(let f of h)a.push(f[0].toUpperCase())}}if(a.length===0)continue;let p=[],d=[];for(let u of a){let g=t.get(u);g&&(C(g)?p.push({id:u,status:g}):d.push(u))}if(p.length===0)continue;let l=d.length===0?"all-compromised":"partial";n.push({entryId:o.id,entryFile:`${o.dir}/${o.filename}`,entryType:o.entryType,project:s,compromisedSources:p,remainingSources:d,severity:l,reason:l==="all-compromised"?`${o.id} has NO remaining valid evidence (all sources invalidated/superseded)`:`${o.id} has ${p.length}/${a.length} sources compromised`})}return n}function V(s,e,c,r,n,t=30){let i=[],o=[...e.map(a=>({...a,entryType:"experiment"})),...c.map(a=>({...a,entryType:"knowledge"})),...r.map(a=>({...a,entryType:"pattern"}))];for(let a of o){if(C(a.meta.status))continue;let p=String(a.meta.status||"").toLowerCase();if(p==="stale"||p.startsWith("challenged"))continue;let d=n.get(a.filename)?.refs??0;if(d>0)continue;let l=U(a.meta.date);l===null||l<=t||i.push({entryId:a.id,entryFile:a.filename,entryType:a.entryType,project:s,ageDays:Math.floor(l),refs:d,reason:`${a.id} has 0 refs and is ${Math.floor(l)} days old (threshold: ${t}d)`})}return i}function z(s,e){let c=[],r=e.filter(l=>!C(l.meta.status)),n=y.join(v,s),t=y.join(n,"experiments");if(!j.existsSync(t))return[];let i=[];for(let l of r){let u=y.join(t,l.filename),g;try{g=j.readFileSync(u,"utf8")}catch{continue}let h=g.match(/\*\*过程缺陷\*\*[::]\s*(.+?)(?=\n\*\*|\n####|\n##|$)/s);h&&h[1].trim()&&h[1].trim()!=="\u65E0"&&h[1].trim()!=="None"&&i.push({id:l.id,text:h[1].trim()})}if(i.length<2)return[];let o=new Map,a=new Set(["\u7684","\u4E86","\u5728","\u662F","\u548C","\u4E0E","\u6216","\u4F46","\u56E0\u4E3A","\u6240\u4EE5","the","a","an","is","are","was","were","and","or","but","for","to","in","on","\u6CA1\u6709","\u4E0D","\u65E0","\u9700\u8981","\u5E94\u8BE5","\u53EF\u4EE5","with","from","that","this","have","been"]),p=/^[\*\#\(\)\d\.\-\+\>\`]+$|^\*\*.*\*\*:?$|^\(\d+\)$/;for(let{id:l,text:u}of i){let h=u.replace(/\*\*[^*]+\*\*/g,"").replace(/\([^)]*\)/g,"").replace(/`[^`]+`/g,"").replace(/[,。;:、!?\n\r\-\*\#\>\+]/g," ").split(/\s+/).filter(f=>f.length>=3&&!a.has(f.toLowerCase())&&!p.test(f)).map(f=>f.toLowerCase());for(let f of h){o.has(f)||o.set(f,[]);let x=o.get(f);x.includes(l)||x.push(l)}}let d=new Set;for(let[l,u]of o){if(u.length<3)continue;let g=[...u].sort().join(",");if(d.has(g))continue;d.add(g);let h=i.filter(f=>u.includes(f.id)).map(f=>`${f.id}: ${f.text.slice(0,80)}`).join("; ");c.push({project:s,pattern:l,experiments:u,reason:`Keyword "${l}" appears in ${u.length} experiments' deficiency sections: ${h.slice(0,200)}`})}return c.sort((l,u)=>u.experiments.length-l.experiments.length),c.slice(0,10)}function L(s){let e=y.join(v,s),c=y.join(e,"experiments"),r=y.join(e,"knowledge"),n=y.join(e,"patterns"),t=S(c),i=S(r),o=S(n),a=b(s,t,o),p=F(s,t),d=W(s,t),l=[...a,...p,...d];l.sort((f,x)=>{let m={"tag-cluster":0,"link-cluster":1,"supersede-chain":2},A=(m[f.type]??9)-(m[x.type]??9);return A!==0?A:x.experiments.length-f.experiments.length});let u=K(s,t,i,o),g=V(s,t,i,o,I(e)),h=z(s,t);return{project:s,experimentCount:t.length,knowledgeCount:i.length,patternCount:o.length,consolidation:l,contradictions:u,stale:g,antiPatterns:h}}function O(s){let e=[],c=s.filter(n=>n.consolidation.length>0||n.contradictions.length>0||n.stale.length>0||n.antiPatterns.length>0);if(c.length===0)return"No findings across all projects.";for(let n of c){if(e.push(`
|
|
5
|
-
=== ${n.project} (${n.experimentCount} exp, ${n.knowledgeCount} K, ${n.patternCount} PAT) ===`),n.contradictions.length>0){e.push(`
|
|
6
|
-
\u26A0 CONTRADICTIONS (${n.contradictions.length}):`);for(let t of n.contradictions){let i=t.severity==="all-compromised"?"\u{1F534}":"\u{1F7E1}";e.push(` ${i} ${t.reason}`),e.push(` Compromised: ${t.compromisedSources.map(o=>`${o.id}(${o.status})`).join(", ")}`),t.remainingSources.length>0&&e.push(` Remaining: ${t.remainingSources.join(", ")}`)}}if(n.stale.length>0){e.push(`
|
|
7
|
-
\u23F3 STALE (${n.stale.length}):`);for(let t of n.stale.slice(0,10))e.push(` ${t.entryId} (${t.entryType}, ${t.ageDays}d old, ${t.refs} refs)`);n.stale.length>10&&e.push(` ... and ${n.stale.length-10} more`)}if(n.antiPatterns.length>0){e.push(`
|
|
8
|
-
\u{1F501} ANTI-PATTERNS (${n.antiPatterns.length}):`);for(let t of n.antiPatterns.slice(0,5))e.push(` "${t.pattern}" in ${t.experiments.join(", ")}`)}if(n.consolidation.length>0){let t=n.consolidation.filter(i=>i.existingPatterns.length===0);e.push(`
|
|
9
|
-
\u{1F4E6} CONSOLIDATION (${n.consolidation.length} total, ${t.length} uncovered):`);for(let i of t.slice(0,5))e.push(` [${i.type}] ${i.reason}`);t.length>5&&e.push(` ... and ${t.length-5} more`)}}let r={contradictions:s.reduce((n,t)=>n+t.contradictions.length,0),allCompromised:s.reduce((n,t)=>n+t.contradictions.filter(i=>i.severity==="all-compromised").length,0),stale:s.reduce((n,t)=>n+t.stale.length,0),antiPatterns:s.reduce((n,t)=>n+t.antiPatterns.length,0),consolidation:s.reduce((n,t)=>n+t.consolidation.length,0),uncovered:s.reduce((n,t)=>n+t.consolidation.filter(i=>i.existingPatterns.length===0).length,0)};return e.push(`
|
|
10
|
-
--- Summary ---`),e.push(`Contradictions: ${r.contradictions} (${r.allCompromised} fully compromised)`),e.push(`Stale entries: ${r.stale}`),e.push(`Anti-pattern signals: ${r.antiPatterns}`),e.push(`Consolidation candidates: ${r.consolidation} (${r.uncovered} uncovered)`),e.join(`
|
|
11
|
-
`)}var P=["regen","consolidate"],$=class extends Error{validValues;hint;constructor(e,c,r="cortex memory --help"){super(e),this.validValues=c,this.hint=r}};function J(s,e){let c={projects:[],text:!1};for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="--project"){let t=e[r+1];if(t===void 0||t.startsWith("-"))throw new $("Missing value for --project.");c.projects.push(t),r+=1}else if(n==="--text"&&s==="consolidate")c.text=!0;else{let t=s==="consolidate"?["--project","--text"]:["--project"];throw new $(`Unknown argument for '${s}': '${n}'.`,t)}}return c}function N(s){let e=T();if(s.length===0)return e;let c=s.filter(r=>!e.includes(r));if(c.length>0)throw new $(`Unknown project: '${c[0]}' (no experiments/, knowledge/ or patterns/ directory).`,e);return s}function _(s){let e=N(s.projects).map(c=>({project:c,indexes:M(c)}));return JSON.stringify({ok:!0,projects:e},null,2)}function B(s){let e=N(s.projects).map(c=>L(c));return s.text?O(e):JSON.stringify({ok:!0,reports:e},null,2)}function k(s,e,c){return{exitCode:1,stdout:"",stderr:D(s,{validValues:e,hint:c})}}function tt(s){if(s.includes("--help")||s.includes("-h"))return{exitCode:0,stdout:E(),stderr:""};let[e,...c]=s;if(!e)return k("Missing subcommand for 'memory'.",[...P]);if(!P.includes(e))return k(`Unknown subcommand: '${e}'.`,[...P]);try{let r=J(e,c);return{exitCode:0,stdout:e==="regen"?_(r):B(r),stderr:""}}catch(r){return r instanceof $?k(r.message,r.validValues,r.hint):k(r.message)}}export{tt as runMemoryCli};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as l}from"./chunk-ILEML5IP.js";import"./chunk-WHC7AYZD.js";var p="1031625952748946",f="https://auth.meta.com",w=`${f}/oidc/device/authorization/`,y=`${f}/oidc/device/token/`,g="https://api.meta.ai/muse-code/key",_=1440*60*1e3,m=30*1e3;function u(e){return AbortSignal.any([AbortSignal.timeout(m),e])}async function d(e){try{let t=await e.json();return t&&typeof t=="object"?t:null}catch{return null}}function s(e){for(let t of["error_description","detail","message","error"]){let n=e?.[t];if(typeof n=="string"&&n.trim())return`: ${n.trim()}`}return""}function a(e){if(typeof e!="string"||!e)return null;try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.href}catch{return null}}function c(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}async function S(e){let t=await fetch(w,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:p}).toString(),signal:u(e)}),n=await d(t);if(!t.ok)throw new Error(`Meta device authorization failed with status ${t.status}${s(n)}`);let o=n?.device_code,i=n?.user_code,r=a(n?.verification_uri_complete)??a(n?.verification_uri);if(typeof o!="string"||!o||typeof i!="string"||!i||!r)throw new Error(`Invalid Meta device authorization response: ${JSON.stringify(n)}`);return{deviceCode:o,userCode:i,verificationUri:r,intervalSeconds:c(n?.interval),expiresInSeconds:c(n?.expires_in)}}async function v(e,t){return l({intervalSeconds:e.intervalSeconds,expiresInSeconds:e.expiresInSeconds,waitBeforeFirstPoll:!0,signal:t,poll:async()=>{let n=await fetch(y,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e.deviceCode,client_id:p}).toString(),signal:u(t)}),o=await d(n);if(n.ok&&typeof o?.access_token=="string"&&o.access_token)return{status:"complete",value:o.access_token};switch(o?.error){case"authorization_pending":return{status:"pending"};case"slow_down":return{status:"slow_down",intervalSeconds:c(o?.interval)};case"access_denied":return{status:"failed",message:"Meta login was denied."};case"expired_token":return{status:"failed",message:"Meta device authorization expired. Please restart login."};default:return{status:"failed",message:`Meta device token request failed with status ${n.status}${s(o)}`}}}})}async function h(e,t){let n=await fetch(g,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","x-api-version":"1.0.0"},body:"{}",signal:u(t)}),o=await d(n);if(n.status===401||n.status===403)throw new Error(`Meta session expired (status ${n.status}). Run \`/login meta\` to sign in again.${s(o)}`);if(!n.ok)throw new Error(`Meta API key mint failed with status ${n.status}${s(o)}`);let i=o?.api_key;if(typeof i!="string"||!i){let r=a(o?.action_url);throw new Error(`Meta did not issue an API key.${r?` Complete setup at ${r}`:""}`)}return{type:"oauth",refresh:e,access:i,expires:Date.now()+_}}async function I(e){try{let t=await S(e.signal);e.notify({type:"device_code",userCode:t.userCode,verificationUri:t.verificationUri,intervalSeconds:t.intervalSeconds,expiresInSeconds:t.expiresInSeconds});let n=await v(t,e.signal);return e.notify({type:"progress",message:"Enabling Meta Model API access..."}),await h(n,e.signal)}catch(t){throw e.signal.aborted?new Error("Login cancelled"):t}}var A={name:"Meta (Muse subscription)",isSubscription:!0,loginLabel:"Sign in with Meta",login:I,refresh:(e,t)=>h(e.refresh,t),async toAuth(e){return{apiKey:e.access}}};export{A as metaOAuth};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as H}from"./chunk-DQJ6LLAS.js";import{a as z}from"./chunk-V3AQJSWR.js";import{c as j,d as L}from"./chunk-SKHLZ6XY.js";import{a as D,d as U,i as B,o as J}from"./chunk-QBKCAIJG.js";import{J as $,L as O,o as I,p as E,u as v,y as P}from"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import{a as y}from"./chunk-USBJFDJ6.js";import{a as N}from"./chunk-K4NTZEDJ.js";import{h as A}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as S}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var K=9,Q=4e3,V=(t,e,n)=>{let r=new S,o=P(e,t.compat?.supportsMidConvoSystemMessages);return(async()=>{let s=ee(t);try{let l=n?.apiKey;if(!l)throw new Error(`No API key for provider: ${t.provider}`);let f=te(),u=J(o.messages,t,d=>f(d)),a=de(t,o,u,n),i=await n?.onPayload?.(a,t);i!==void 0&&(a=i);let c=await se(t,a,l,n);if(r.push({type:"start",partial:s}),await pe(t,s,r,c,n?.onProviderStreamEvent),n?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(s.stopReason==="aborted"||s.stopReason==="error")throw new Error(s.errorMessage||"An unknown error occurred");r.push({type:"done",reason:s.stopReason,message:s}),r.end()}catch(l){for(let f of s.content)delete f.partialArgs;s.stopReason=n?.signal?.aborted?"aborted":"error",s.errorMessage=ne(l),r.push({type:"error",reason:s.stopReason,error:s}),r.end()}})(),r},Pe=(t,e,n)=>{let r=n?.apiKey;if(!r)throw new Error(`No API key for provider: ${t.provider}`);let o={...B(t,e,n,r),toolChoice:n?.toolChoice},s=n?.reasoning?O(t,n.reasoning):void 0,l=s==="off"?void 0:s,f=t.reasoning?t.thinkingLevelMap:void 0,u=f?l?f[l]??"high":f.off??void 0:void 0;return V(t,e,{...o,promptMode:t.reasoning&&!f&&l?"reasoning":void 0,reasoningEffort:u})};function ee(t){return{role:"assistant",content:[],api:t.api,provider:t.provider,model:t.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()}}function te(){let t=new Map,e=new Map;return n=>{let r=t.get(n);if(r)return r;let o=0;for(;;){let s=G(n,o),l=e.get(s);if(!l||l===n)return t.set(n,s),e.set(s,n),s;o++}}}function G(t,e){let n=t.replace(/[^a-zA-Z0-9]/g,"");if(e===0&&n.length===K)return n;let r=n||t,o=e===0?r:`${r}:${e}`;return z(o).replace(/[^a-zA-Z0-9]/g,"").slice(0,K)}function ne(t){if(t instanceof Error){let e=t,n=typeof e.statusCode=="number"?e.statusCode:void 0,r=typeof e.body=="string"?e.body.trim():void 0;return n!==void 0&&r?`Mistral API error (${n}): ${re(r,Q)}`:n!==void 0?`Mistral API error (${n}): ${t.message}`:t.message}return oe(t)}function re(t,e){return t.length<=e?t:`${t.slice(0,e)}... [truncated ${t.length-e} chars]`}function oe(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}async function se(t,e,n,r){let o=new URL(t.baseUrl);o.pathname=`${o.pathname.replace(/\/+$/u,"")}/`;let s=new URL("v1/chat/completions",o),l=ae(t,n,r),f=r?.timeoutMs??6e4,u=AbortSignal.timeout(f),a=H([r?.signal,u]),i;try{i=await(r?.fetch??globalThis.fetch)(s,{method:"POST",headers:l,body:JSON.stringify(ie(e)),signal:a.signal})}catch(c){throw u.aborted&&!r?.signal?.aborted?new Error(`Mistral response headers timed out after ${f}ms`):c}finally{a.cleanup()}if(await r?.onResponse?.({status:i.status,headers:N(i.headers)},t),!i.ok){let c=await i.text();throw new M(i.status,c,i.statusText)}if(!i.body)throw new Error("Mistral response has no body");return fe(i.body,r?.signal)}var M=class extends Error{statusCode;body;constructor(e,n,r){super(r||`Request failed with status ${e}`),this.name="MistralHttpError",this.statusCode=e,this.body=n}};function ae(t,e,n){let r=new Headers({...A(t,n?.identity),accept:"text/event-stream",authorization:`Bearer ${e}`,"content-type":"application/json"});W(r,t.headers),W(r,n?.headers);let o=q(t.headers,"x-affinity")||q(n?.headers,"x-affinity");return X(n)&&!o&&r.set("x-affinity",n.sessionId),r}function W(t,e){if(e)for(let[n,r]of Object.entries(e))r===null?t.delete(n):t.set(n,r)}function q(t,e){return!!t&&Object.keys(t).some(n=>n.toLowerCase()===e)}function ie(t){let e={...t};for(let[r,o]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])k(e,r,o);e.messages=t.messages.map(r=>ce(r));let n=e.response_format;if(w(n)){let r={...n};k(r,"jsonSchema","json_schema");let o=r.json_schema;if(w(o)){let s={...o};k(s,"schemaDefinition","schema"),r.json_schema=s}e.response_format=r}return e}function ce(t){let e={...t};return k(e,"toolCalls","tool_calls"),k(e,"toolCallId","tool_call_id"),Array.isArray(t.content)&&(e.content=t.content.map(n=>le(n))),e}function le(t){let e={...t};for(let[n,r]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])k(e,n,r);return e}function k(t,e,n){e in t&&(t[n]=t[e],delete t[e])}function w(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var b=Symbol("mistral-stream-done");async function*fe(t,e){let n=t.getReader(),r=new TextDecoder,o="",s=()=>{n.cancel().catch(()=>{})};e?.addEventListener("abort",s,{once:!0});try{for(;;){if(e?.aborted)throw e.reason;let{done:l,value:f}=await n.read();if(e?.aborted)throw e.reason;o+=l?r.decode():r.decode(f,{stream:!0});let u=F(o);for(;u;){let a=Z(o.slice(0,u.index));if(o=o.slice(u.index+u.length),a===b)return;a&&(yield a),u=F(o)}if(l)break}if(o.trim()){let l=Z(o);l!==b&&l&&(yield l)}}finally{e?.removeEventListener("abort",s);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}function F(t){let e=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(t);return e?.index===void 0?void 0:{index:e.index,length:e[0].length}}function Z(t){let e=t.split(/\r\n|\r|\n/u).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).trimStart()).join(`
|
|
5
|
-
`).trim();if(!e)return;if(e==="[DONE]")return b;let n=JSON.parse(e);if(!w(n)||!Array.isArray(n.choices))throw new Error("Invalid Mistral streaming event");return{data:n}}function de(t,e,n,r){let o={model:t.id,stream:!0,messages:he(n,t.input.includes("image"))},s=v(e.messages);return s.length>0&&(o.tools=me(s)),r?.temperature!==void 0&&(o.temperature=r.temperature),r?.maxTokens!==void 0&&(o.maxTokens=r.maxTokens),r?.toolChoice&&(o.toolChoice=ye(r.toolChoice)),r?.promptMode&&(o.promptMode=r.promptMode),r?.reasoningEffort&&(o.reasoningEffort=r.reasoningEffort),X(r)&&(o.promptCacheKey=r.sessionId),o}function X(t){return t?.cacheRetention!=="none"&&!!t?.sessionId}function ue(t,e){let n=t,r=n.promptTokensDetails?.cachedTokens??n.prompt_tokens_details?.cached_tokens??n.promptTokenDetails?.cachedTokens??n.prompt_token_details?.cached_tokens??n.numCachedTokens??n.num_cached_tokens??0,o=typeof r=="number"&&Number.isFinite(r)?r:0;return Math.min(e,Math.max(0,o))}async function pe(t,e,n,r,o){let s=null,l=e.content,f=()=>l.length-1,u=new Map,a=i=>{if(i){if(i.type==="text"){n.push({type:"text_end",contentIndex:f(),content:i.text,partial:e});return}i.type==="thinking"&&n.push({type:"thinking_end",contentIndex:f(),content:i.thinking,partial:e})}};for await(let i of r){let c=i.data;if(await o?.(c,t),e.responseId||=c.id,c.usage){let p=c.usage.prompt_tokens||0,h=ue(c.usage,p);e.usage.input=Math.max(0,p-h),e.usage.output=c.usage.completion_tokens||0,e.usage.cacheRead=h,e.usage.cacheWrite=0,e.usage.totalTokens=c.usage.total_tokens||e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,$(t,e.usage)}let d=c.choices[0];if(!d)continue;if(d.finish_reason){e.rawStopReason=d.finish_reason;let p=xe(d.finish_reason);e.stopReason=p.stopReason,p.errorMessage&&(e.errorMessage=p.errorMessage)}let x=d.delta;if(x.content!==null&&x.content!==void 0){let p=typeof x.content=="string"?[x.content]:x.content;for(let h of p){if(typeof h=="string"){let m=y(h);if(!m)continue;(!s||s.type!=="text")&&(a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e})),s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e});continue}if(h.type==="thinking"){let m=(h.thinking??[]).map(g=>g.text??"").filter(g=>g.length>0).join(""),_=y(m);if(!_)continue;(!s||s.type!=="thinking")&&(a(s),s={type:"thinking",thinking:""},e.content.push(s),n.push({type:"thinking_start",contentIndex:f(),partial:e})),s.thinking+=_,n.push({type:"thinking_delta",contentIndex:f(),delta:_,partial:e});continue}if(h.type==="text"){let m=y(h.text??"");if(!m)continue;(!s||s.type!=="text")&&(a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e})),s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e})}}}let Y=x.tool_calls||[];for(let p of Y){s&&(a(s),s=null);let h=p.id&&p.id!=="null"?p.id:G(`toolcall:${p.index??0}`,0),m=p.index??h,_=u.get(m),g;if(_!==void 0){let R=e.content[_];R?.type==="toolCall"&&(g=R)}g||(g={type:"toolCall",id:h,name:p.function.name,arguments:{},partialArgs:""},e.content.push(g),u.set(m,e.content.length-1),n.push({type:"toolcall_start",contentIndex:e.content.length-1,partial:e}));let C=typeof p.function.arguments=="string"?p.function.arguments:JSON.stringify(p.function.arguments||{});g.partialArgs=(g.partialArgs||"")+C,g.arguments=L(g.partialArgs),n.push({type:"toolcall_delta",contentIndex:u.get(m),delta:C,partial:e})}}a(s);for(let i of u.values()){let c=e.content[i];if(c.type!=="toolCall")continue;let d=c;Object.assign(d,j(d.partialArgs)),delete d.partialArgs,n.push({type:"toolcall_end",contentIndex:i,toolCall:d,partial:e})}}function me(t){return t.map(e=>{let n=U(e,!0);return{type:"function",function:{name:e.name,description:e.description,parameters:T(D(e,n)),strict:n??!1}}})}function T(t){if(Array.isArray(t))return t.map(e=>T(e));if(t&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=T(r);return e}return t}function he(t,e){let n=[];for(let[r,o]of t.entries()){if(o.role==="system"){let a=r===0?I(o):E(o);a.length>0&&n.push({role:"system",content:y(a)});continue}if(o.role==="user"){if(typeof o.content=="string"){n.push({role:"user",content:y(o.content)});continue}let a=o.content.some(c=>c.type==="image"),i=o.content.filter(c=>c.type==="text"||e).map(c=>c.type==="text"?{type:"text",text:y(c.text)}:{type:"image_url",imageUrl:`data:${c.mimeType};base64,${c.data}`});if(i.length>0){n.push({role:"user",content:i});continue}a&&!e&&n.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(o.role==="assistant"){let a=[],i=[];for(let d of o.content){if(d.type==="text"){d.text.trim().length>0&&a.push({type:"text",text:y(d.text)});continue}if(d.type==="thinking"){d.thinking.trim().length>0&&a.push({type:"thinking",thinking:[{type:"text",text:y(d.thinking)}]});continue}i.push({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.arguments||{})},index:0})}let c={role:"assistant",prefix:!1};a.length>0&&(c.content=a),i.length>0&&(c.toolCalls=i),(a.length>0||i.length>0)&&n.push(c);continue}let s=[],l=o.content.filter(a=>a.type==="text").map(a=>a.type==="text"?y(a.text):"").join(`
|
|
6
|
-
`),f=o.content.some(a=>a.type==="image"),u=ge(l,f,e,o.isError);s.push({type:"text",text:u});for(let a of o.content)e&&a.type==="image"&&s.push({type:"image_url",imageUrl:`data:${a.mimeType};base64,${a.data}`});n.push({role:"tool",toolCallId:o.toolCallId,name:o.toolName,content:s})}return n}function ge(t,e,n,r){let o=t.trim(),s=r?"[tool error] ":"";return o.length>0?`${s}${o}${e&&!n?`
|
|
7
|
-
[tool image omitted: model does not support images]`:""}`:e?n?r?"[tool error] (see attached image)":"(see attached image)":r?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":r?"[tool error] (no tool output)":"(no tool output)"}function ye(t){if(t)return t==="auto"||t==="none"||t==="any"||t==="required"?t:{type:"function",function:{name:t.function.name}}}function xe(t){if(t===null)return{stopReason:"stop"};switch(t){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error (server error)"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${t}`}}}export{V as stream,Pe as streamSimple};
|
|
@@ -1,4 +0,0 @@
|
|
|
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{H as a,I as b,J as c,K as d,L as e,M as f,N as g,O as h,P as i}from"./chunk-LAWOWPZX.js";import"./chunk-EQIMHXC4.js";import"./chunk-YKKEI5GI.js";import"./chunk-LACGULCN.js";import"./chunk-3TGQSGG4.js";import"./chunk-QUUEQRIT.js";import"./chunk-SKHLZ6XY.js";import"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import"./chunk-CXT5IR5T.js";import"./chunk-AWFUHWQK.js";import"./chunk-B3XBQEFM.js";import"./chunk-WHC7AYZD.js";export{a as defaultModelPerProvider,c as findExactModelReferenceMatch,h as findInitialModel,g as resolveCliModel,b as resolveModelReference,f as resolveModelScope,d as resolveModelScopeFromModels,e as resolveModelScopeWithDiagnostics,i as restoreModelFromSession};
|
|
@@ -1,12 +0,0 @@
|
|
|
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 ue,c as fe}from"./chunk-YKKEI5GI.js";import{a as we}from"./chunk-DQJ6LLAS.js";import{a as ye,b as G,c as be,d as j}from"./chunk-7GAYFN52.js";import{a as me}from"./chunk-XIECJESP.js";import"./chunk-V3AQJSWR.js";import{a as he}from"./chunk-ZSV6TO7Q.js";import{a as de,b as pe}from"./chunk-FF7UELTU.js";import"./chunk-SKHLZ6XY.js";import"./chunk-6R73ICDB.js";import{f as K,i as le}from"./chunk-QBKCAIJG.js";import{C as J,F as ae,L as ce,o as ne,r as se,s as oe,y as ie}from"./chunk-PZMGBKUR.js";import{a as q,c as ee,d as te}from"./chunk-D6VMBA4C.js";import"./chunk-USBJFDJ6.js";import{a as H}from"./chunk-K4NTZEDJ.js";import{h as re}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as Q}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var Be="https://chatgpt.com/backend-api",Pe="https://api.openai.com/auth",Ie=0,ge=1e3,Fe=6e4,$e=15e3,Ue=3,Re=new Set(["openai","openai-codex","opencode"]),ze=1009,Je="websocket_connection_limit_reached",He="previous_response_not_found",Ke=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function Se(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 Ge(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function je(e,r){return e===429&&Ge(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 Ve(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 Xe(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=setTimeout(t,e);r?.addEventListener("abort",()=>{clearTimeout(i),n(new Error("Request was aborted"))})})}function _e(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function Ye(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function Ze(e){let r=Ye();if(!r||typeof r.zstdCompressSync!="function")return null;try{let t=r.zstdCompressSync(e,{params:{[r.constants.ZSTD_c_compressionLevel]:Ue}});return new Uint8Array(t)}catch{return null}}var Qe=(e,r,t)=>{let n=new Q,i=ie(r,e.compat?.supportsMidConvoSystemMessages);return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",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()};try{let o=t?.apiKey;if(!o)throw new Error(`No API key for provider: ${e.provider}`);let c=xt(o),a=K(J(i.messages),e.compat?.supportsOpenAIGrammarTools??!1),d=t?.cacheRetention==="none"?void 0:t?.sessionId,p=me(d),u=et(e,i,t,p,a),l=await t?.onPayload?.(u,e);l!==void 0&&(u=l);let f=p||fe(),m={originator:"pi",...re(e,t?.identity)},h=Ot(m,e.headers,t?.headers,c,o,p),S=At(m,e.headers,t?.headers,c,o,f),k=JSON.stringify(u),y=_e(t?.timeoutMs),C=_e(t?.websocketConnectTimeoutMs),T=t?.transport||"auto",b=!1,x=T!=="sse"&&Me(d);if(x&&ke(d),T!=="sse"&&!x){let g=!1,_=!1,A=!1;for(;;){g=!1;try{if(await Rt(rt(e.baseUrl),u,S,s,n,e,()=>{g=!0,b||(b=!0,n.push({type:"start",partial:s}))},y,C,d,c,a,t),t?.signal?.aborted)throw new Error("Request was aborted");Se(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(v){let D=t?.signal?.aborted,N=!g&&ot(v),W=it(v);if(!D&&W&&!A){A=!0;continue}if(!D&&N&&!_){_=!0;continue}if(D||st(v)&&!N||(te(s,ee("provider_transport_failure",v,{configuredTransport:T,...g?{}:{fallbackTransport:"sse"},eventsEmitted:g,phase:g?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(k).byteLength})),mt(d,v),g))throw v;ke(d);break}}}let O=Ze(k);O&&h.set("content-encoding","zstd");let Ne=O??k,E,L,z=t?.maxRetries??Ie;for(let g=0;g<=z;g++){if(t?.signal?.aborted)throw new Error("Request was aborted");try{let _=y!==void 0&&y>0?AbortSignal.timeout(y):void 0,A=we([t?.signal,_]);try{E=await(t?.fetch??globalThis.fetch)(Oe(e.baseUrl),{method:"POST",headers:h,body:Ne,signal:A.signal})}catch(W){throw _?.aborted&&!t?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${y}ms`):W}finally{A.cleanup()}if(await t?.onResponse?.({status:E.status,headers:H(E.headers)},e),E.ok)break;let v=await E.text();if(g<z&&je(E.status,v)){let W=Ve(E.headers),qe=W===void 0?ge*2**g:Xe(W,t);await Ee(qe,t?.signal);continue}let D=new Response(v,{status:E.status,statusText:E.statusText}),N=await Ct(D);throw new Error(N.friendlyMessage||N.message)}catch(_){if(_ instanceof Error&&(_.name==="AbortError"||_.message==="Request was aborted"))throw new Error("Request was aborted");if(L=_ instanceof Error?_:new Error(String(_)),g<z&&!(L instanceof F)&&!L.message.includes("usage limit")){let A=ge*2**g;await Ee(A,t?.signal);continue}throw L}}if(!E?.ok)throw L??new Error("Failed after retries");if(!E.body)throw new Error("No response body");if(b||(b=!0,n.push({type:"start",partial:s})),await nt(E,s,n,e,a,t),t?.signal?.aborted)throw new Error("Request was aborted");Se(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let c of s.content)delete c.partialJson,delete c.customInput;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=pe(de(o)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},Gt=(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?ce(e,t.reasoning):void 0;return Qe(e,r,{...i,reasoningEffort:s==="off"?void 0:s})};function et(e,r,t,n,i=K(J(r.messages),e.compat?.supportsOpenAIGrammarTools??!1)){let s=e.compat?.supportsStrictMode??!0,o=e.compat?.supportsOpenAIGrammarTools??!1,c=e.compat?.supportsAdditionalTools??!1,a=e.compat?.supportsToolSearch??!1,d=ae(r.messages,ye({supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:c,supportsToolSearch:a})),p=G(e,r,Re,{includeSystemPrompt:!1,grammarToolInputProperties:i,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:c,supportsToolSearch:a,toolOptions:{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:o}}),u=oe(r.messages),l=u?ne(u):"",f={model:e.id,store:!1,stream:!0,instructions:l||"You are a helpful assistant.",input:p,text:{verbosity:t?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:t?.toolChoice??"auto",parallel_tool_calls:!0};if(t?.temperature!==void 0&&(f.temperature=t.temperature),t?.serviceTier!==void 0&&(f.service_tier=t.serviceTier),d.requestTools.length>0&&(f.tools=be(d.requestTools,{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:o})),t?.reasoningEffort!==void 0){let m=t.reasoningEffort==="none"?e.thinkingLevelMap?.off===void 0?"none":e.thinkingLevelMap.off:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;m!==null&&(f.reasoning={effort:m,summary:t.reasoningSummary??"auto"})}else e.reasoning&&e.thinkingLevelMap?.off!==null&&(f.reasoning={effort:e.thinkingLevelMap?.off??"none"});return f}function tt(e,r){switch(r){case"flex":return .5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function Ce(e,r,t){let n=tt(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 xe(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 rt(e){let r=new URL(Oe(e));return r.protocol==="https:"&&(r.protocol="wss:"),r.protocol==="http:"&&(r.protocol="ws:"),r.toString()}async function nt(e,r,t,n,i,s){await j(Ae(ut(e,s?.signal),r,n,s?.onProviderStreamEvent),r,t,n,{serviceTier:s?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:xe,applyServiceTierPricing:(o,c)=>Ce(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}},$=class extends Error{constructor(r){super(q(r)),this.name="ProviderStreamEventCallbackError",this.cause=r}};function st(e){return e instanceof M||e instanceof B||e instanceof $}function ot(e){return e instanceof M&&e.code===Je}function it(e){return e instanceof M&&e.code===He}function at(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 $(o)}let s=typeof i.type=="string"?i.type:void 0;if(s){if(s==="error"){let{code:o,message:c}=at(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:ct(o.status)};yield{...i,type:"response.completed",response:c};return}yield i}}}function ct(e){if(typeof e=="string")return Ke.has(e)?e:void 0}async function*ut(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 d=i.slice(0,a);i=i.slice(a+2);let p=d.split(`
|
|
9
|
-
`).filter(u=>u.startsWith("data:")).map(u=>u.slice(5).trim());if(p.length>0){let u=p.join(`
|
|
10
|
-
`).trim();if(u&&u!=="[DONE]")try{yield JSON.parse(u)}catch(l){throw new B(`Invalid Codex SSE JSON: ${q(l)}`,{cause:l,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 ft="responses_websockets=2026-02-06",lt=300*1e3,dt=3300*1e3,w=new Map,P=new Map,U=new Set;function Z(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 jt(e){let r=P.get(e);return r?{...r}:void 0}function Vt(e){if(e){P.delete(e),U.delete(e);return}P.clear(),U.clear()}function pt(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()}ue(pt);function Me(e){return e?U.has(e):!1}function ke(e){if(!e)return;let r=Z(e);r.sseFallbacks++,r.websocketFallbackActive=Me(e)}function mt(e,r){if(!e)return;U.add(e);let t=Z(e);t.websocketFailures++,t.lastWebSocketError=q(r),t.websocketFallbackActive=!0}var V=null;async function yt(e){if(!e&&V)return V;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=he(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...s,...o?{proxy:o.toString()}:{}})}};return e||(V=t),t}let r=globalThis.WebSocket;return typeof r!="function"?null:r}var Y=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 bt(e){let r=e.readyState;return typeof r=="number"?r:void 0}function I(e){let r=bt(e);return r===void 0||r===1}function ht(e){return Date.now()-e.createdAt>=dt}function R(e,r=1e3,t="done"){try{e.close(r,t)}catch{}}function Te(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)},lt)}async function X(e,r,t,n=$e,i){let s=await yt(i);if(!s)throw new Error("WebSocket transport is not available in this runtime");let o=H(r);return delete o["OpenAI-Beta"],new Promise((c,a)=>{let d=!1,p,u;try{u=new s(e,{headers:o})}catch(y){a(y instanceof Error?y:new Error(String(y)));return}let l=()=>{p&&(clearTimeout(p),p=void 0),u.removeEventListener("open",m),u.removeEventListener("error",h),u.removeEventListener("close",S),t?.removeEventListener("abort",k)},f=(y,C)=>{d||(d=!0,l(),C&&R(u,1e3,C),a(y))},m=()=>{d||(d=!0,l(),c(u))},h=y=>{f(We(y))},S=y=>{f(Le(y))},k=()=>{f(new Error("Request was aborted"),"aborted")};u.addEventListener("open",m),u.addEventListener("error",h),u.addEventListener("close",S),t?.addEventListener("abort",k),n>0&&(p=setTimeout(()=>{f(new Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n)),t?.aborted&&k()})}async function wt(e,r,t,n,i,s,o){if(!t){let u=await X(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&&ht(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 l=w.get(t);l?.get(n)===a&&l.delete(n),l?.size===0&&w.delete(t);return}a.busy=!1,Te(t,n,a)}};if(a.busy){let u=await X(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 d=await X(e,r,i,s,o),p={socket:d,busy:!0,createdAt:Date.now()};return c=w.get(t),c||(c=new Map,w.set(t,c)),c.set(n,p),{socket:d,entry:p,reused:!1,release:({keep:u}={})=>{if(!u||!I(p.socket)){R(p.socket),p.idleTimer&&clearTimeout(p.idleTimer);let l=w.get(t);l?.get(n)===p&&l.delete(n),l?.size===0&&w.delete(t);return}p.busy=!1,Te(t,n,p)}}}function We(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 Le(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 Y(`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 gt(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*St(e,r,t){let n=[],i=null,s=!1,o=null,c=!1,a=()=>{if(!i)return;let f=i;i=null,f()},d=f=>{(async()=>{let m=null;try{if(!f||typeof f!="object"||!("data"in f)||(m=await gt(f.data),!m))return;let h=JSON.parse(m),S=typeof h.type=="string"?h.type:"";(S==="response.completed"||S==="response.done"||S==="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()}})()},p=f=>{o=We(f),s=!0,a()},u=f=>{if(c){s=!0,a();return}o||(o=Le(f)),s=!0,a()},l=()=>{o=new Error("Request was aborted"),s=!0,a()};e.addEventListener("message",d),e.addEventListener("error",p),e.addEventListener("close",u),r?.addEventListener("abort",l);try{for(;;){if(r?.aborted)throw new Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(s)break;let f;await new Promise((m,h)=>{i=m,t!==void 0&&t>0&&(f=setTimeout(()=>{let S=new Error(`WebSocket idle timeout after ${t}ms`);o=S,s=!0,i=null,R(e,1e3,"idle_timeout"),h(S)},t))}).finally(()=>{f&&clearTimeout(f)})}if(o)throw o;if(!c)throw new Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",d),e.removeEventListener("error",p),e.removeEventListener("close",u),r?.removeEventListener("abort",l)}}function ve(e){let{input:r,previous_response_id:t,...n}=e;return n}function Et(e,r){return JSON.stringify(e??[])===JSON.stringify(r??[])}function _t(e,r){return JSON.stringify(ve(e))===JSON.stringify(ve(r))}function kt(e,r){if(!_t(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(Et(i,n))return t.slice(n.length)}function Tt(e,r){let t=e.continuation;if(!t)return r;let n=kt(r,t);return!n||!t.lastResponseId?(e.continuation=void 0,r):{...r,previous_response_id:t.lastResponseId,input:n}}async function*vt(e,r){let t=!1;for await(let n of e)t||(t=!0,r()),yield n}async function Rt(e,r,t,n,i,s,o,c,a,d,p,u,l){let{socket:f,entry:m,reused:h,release:S}=await wt(e,t,d,p,l?.signal,a,l?.env),k=!0,y=l?.transport==="websocket-cached"||l?.transport==="auto",C=r,T=y&&m?Tt(m,C):C,b=d?Z(d):void 0;b&&(b.requests++,h?b.connectionsReused++:b.connectionsCreated++,y&&b.cachedContextRequests++,T.store===!0&&b.storeTrueRequests++,b.lastInputItems=T.input?.length??0,T.previous_response_id?(b.deltaRequests++,b.lastDeltaInputItems=T.input?.length??0,b.lastPreviousResponseId=T.previous_response_id):(b.fullContextRequests++,b.lastDeltaInputItems=void 0,b.lastPreviousResponseId=void 0));try{if(f.send(JSON.stringify({type:"response.create",...T})),await j(vt(Ae(St(f,l?.signal,c),n,s,l?.onProviderStreamEvent),o),n,i,s,{serviceTier:l?.serviceTier,grammarToolInputProperties:u,resolveServiceTier:xe,applyServiceTierPricing:(x,O)=>Ce(x,O,s)}),l?.signal?.aborted)k=!1;else if(y&&m&&n.responseId){let x=G(s,se({messages:[n]}),Re,{includeSystemPrompt:!1,grammarToolInputProperties:u}).filter(O=>O.type!=="function_call_output"&&O.type!=="custom_tool_call_output");m.continuation={lastRequestBody:C,lastResponseId:n.responseId,lastResponseItems:x}}}catch(x){throw m&&(m.continuation=void 0),k=!1,x}finally{S({keep:k})}}async function Ct(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,d=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${c}.${d}`.trim()}t=s.message||n||t}}catch{}return{message:t,friendlyMessage:n}}function xt(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 De(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 Ot(e,r,t,n,i,s){let o=De(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 At(e,r,t,n,i,s){let o=De(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",ft),o.set("x-client-request-id",s),o.set("session-id",s),o}export{pt as closeOpenAICodexWebSocketSessions,jt as getOpenAICodexWebSocketDebugStats,Vt as resetOpenAICodexWebSocketDebugStats,Qe as stream,Gt as streamSimple};
|
|
@@ -1,9 +0,0 @@
|
|
|
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 ke}from"./chunk-XIECJESP.js";import{a as Te}from"./chunk-V3AQJSWR.js";import{a as he}from"./chunk-CVC66CFV.js";import{a as me,b as ye}from"./chunk-FF7UELTU.js";import{a as ue,b as fe}from"./chunk-BGYR4ID3.js";import{c as X,d as Y}from"./chunk-SKHLZ6XY.js";import{a as ee}from"./chunk-6R73ICDB.js";import{a as ne}from"./chunk-23PRJECN.js";import{a as se,b as re,c as oe,d as ie,e as ae,f as N,h as le,i as ce,k as pe,l as ge,o as de}from"./chunk-QBKCAIJG.js";import{C as j,F as G,J as Z,L as Q,o as U,p as V,y as z}from"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import{a as b}from"./chunk-USBJFDJ6.js";import{a as te}from"./chunk-K4NTZEDJ.js";import{h as J}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as W}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";function Re(e,n){if(!e)return!1;let t=n.toLowerCase();for(let[s,u]of Object.entries(e))if(s.toLowerCase()===t&&u!==null&&u.trim().length>0)return!0;return!1}function Ce(e,n,t){if(n)return n;if(Re(t,"authorization")||Re(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 xe(e){return e.type==="text"}function Be(e){return e.type==="thinking"}function Pe(e){return e.type==="toolCall"}function Le(e){return e.type==="image"}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(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 $(e){if(!qe(e)||!De(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 ze(e){if(e)try{let n=JSON.parse(e);return Array.isArray(n)&&n.length>0&&n.every($)?n:void 0}catch{return}}function je(e){if(e)try{let n=JSON.parse(e);return $(n)&&n.type==="reasoning.encrypted"&&typeof n.id=="string"&&n.id.length>0&&n.data.length>0?n:void 0}catch{return}}function _e(e,n){e.id??=n.id,e.format||=n.format,e.index??=n.index}function Ge(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,_e(t,n);return}if(n.type==="reasoning.summary"&&t?.type==="reasoning.summary"){t.summary+=n.summary,_e(t,n);return}e.push({...n})}var Ne=["reasoning","reasoning_content","reasoning_text"];function $e(e){return Ne.includes(e)}function Me(e,n){return e||(ee("PI_CACHE_RETENTION",n)==="long"?"long":"short")}var He=(e,n,t)=>{let s=new W,u=z(n,q(e).supportsMidConvoSystemMessages);return(async()=>{let r={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()},h,k=T=>{h!==void 0&&(T.thinkingSignature=JSON.stringify(h))};try{let T=Ce(e.provider,t?.apiKey,t?.headers),a=q(e),m=N(j(u.messages),a.supportsOpenAIGrammarTools),M=Me(t?.cacheRetention,t?.env),g=M==="none"?void 0:t?.sessionId,i=Ke(e,u,T,t?.headers,t?.identity,t?.fetch,g,a),f=We(e,u,t,a,M,m),p=await t?.onPayload?.(f,e);p!==void 0&&(f=p);let R={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:A,response:I}=await ne(()=>i.chat.completions.create(f,R).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:I.status,headers:te(I.headers)},e),s.push({type:"start",partial:r});let O=null,E=null,S=!1,v=new Map,w=new Map,B=r.content,l=o=>B.indexOf(o),F=o=>{let c=o.customInput?.property;if(c===void 0)return"";let x=o.arguments[c];return typeof x=="string"?x:""},H=(o,c,x)=>{let d=o.customInput;if(!d)return;let C=oe(d.jsonBuffer,d.property,c,x);return o.arguments={[d.property]:c},C},Se=o=>{let c=l(o);if(c!==-1){if(o.type==="text")s.push({type:"text_end",contentIndex:c,content:o.text,partial:r});else if(o.type==="thinking")k(o),s.push({type:"thinking_end",contentIndex:c,content:o.thinking,partial:r});else if(o.type==="toolCall"){if(o.customInput){let x=H(o,F(o),!0);x!==void 0&&s.push({type:"toolcall_delta",contentIndex:c,delta:x,partial:r})}else Object.assign(o,X(o.partialArgs));delete o.partialArgs,delete o.customInput,delete o.streamIndex,s.push({type:"toolcall_end",contentIndex:c,toolCall:o,partial:r})}}},we=()=>(O||(O={type:"text",text:""},B.push(O),s.push({type:"text_start",contentIndex:l(O),partial:r})),O),K=o=>(E||(E={type:"thinking",thinking:"",thinkingSignature:o},B.push(E),s.push({type:"thinking_start",contentIndex:l(E),partial:r})),E),Fe=o=>{let c=typeof o.index=="number"?o.index:void 0,x=o.function?.name??o.custom?.name??"",d=c!==void 0?v.get(c):void 0;if(!d&&o.id&&(d=w.get(o.id)),!d){let C=o.custom&&!o.function?m.get(x)??"input":void 0,P=C!==void 0;d={type:"toolCall",id:o.id||"",name:x,arguments:P?{[C]:""}:{},partialArgs:P?void 0:"",customInput:P?{property:C,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex:c},c!==void 0&&v.set(c,d),o.id&&w.set(o.id,d),B.push(d),s.push({type:"toolcall_start",contentIndex:l(d),partial:r})}if(c!==void 0&&d.streamIndex===void 0&&(d.streamIndex=c,v.set(c,d)),o.id&&w.set(o.id,d),!d.name&&x&&(d.name=x),o.custom&&!o.function&&!d.customInput){let C=m.get(d.name)??"input";d.arguments={[C]:""},d.customInput={property:C,jsonBuffer:{input:"",started:!1,closed:!1}},delete d.partialArgs}return d};for await(let o of A){if(await t?.onProviderStreamEvent?.(o,e),!o||typeof o!="object")continue;r.responseId||=o.id,typeof o.model=="string"&&o.model.length>0&&o.model!==e.id&&(r.responseModel||=o.model),o.usage&&(r.usage=Ae(o.usage,e));let c=Array.isArray(o.choices)?o.choices[0]:void 0;if(c){if(!o.usage&&c.usage&&(r.usage=Ae(c.usage,e)),c.finish_reason){r.rawStopReason=c.finish_reason;let x=rt(c.finish_reason);r.stopReason=x.stopReason,x.errorMessage&&(r.errorMessage=x.errorMessage),S=!0}if(c.delta){let x=["reasoning_content","reasoning","reasoning_text"],d=c.delta,C=null;for(let y of x){let _=d[y];if(typeof _=="string"&&_.length>0){C=y;break}}if(C){let y=d[C];if(typeof y=="string"&&y.length>0){let _=e.provider==="opencode-go"&&C==="reasoning"?"reasoning_content":C,L=K(_);L.thinking+=y,s.push({type:"thinking_delta",contentIndex:l(L),delta:y,partial:r})}}let P=c.delta.reasoning_details;if(Array.isArray(P))for(let y of P)$(y)&&(K(""),h??=[],Ge(h,y));if(c.delta.content!==null&&c.delta.content!==void 0&&c.delta.content.length>0){let y=we();y.text+=c.delta.content,s.push({type:"text_delta",contentIndex:l(y),delta:c.delta.content,partial:r})}if(c?.delta?.tool_calls)for(let y of c.delta.tool_calls){let _=Fe(y);!_.id&&y.id&&(_.id=y.id,w.set(y.id,_));let L=y.function?.name??y.custom?.name;!_.name&&L&&(_.name=L);let D="";if(y.function?.arguments)D=y.function.arguments,_.partialArgs=(_.partialArgs??"")+y.function.arguments,_.arguments=Y(_.partialArgs);else if(y.custom?.input){let Oe=F(_)+y.custom.input;D=H(_,Oe,!1)??""}s.push({type:"toolcall_delta",contentIndex:l(_),delta:D,partial:r})}}}}for(let o of B)Se(o);if(t?.signal?.aborted)throw new Error("Request was aborted");if(r.stopReason==="aborted")throw new Error("Request was aborted");if(!S&&!a.supportsFinishReason&&(r.stopReason=r.content.some(o=>o.type==="toolCall")?"toolUse":"stop"),r.stopReason==="error")throw new Error(r.errorMessage||"Provider returned an error stop reason");if(a.supportsFinishReason&&!S||r.stopReason==="pending")throw new Error("Stream ended without finish_reason");s.push({type:"done",reason:r.stopReason,message:r}),s.end()}catch(T){for(let m of r.content)m.type==="thinking"&&k(m),delete m.index,delete m.partialArgs,delete m.customInput,delete m.streamIndex;r.stopReason=t?.signal?.aborted?"aborted":"error",r.errorMessage=ye(me(T));let a=T?.error?.metadata?.raw;a&&!r.errorMessage.includes(String(a))&&(r.errorMessage+=`
|
|
5
|
-
${a}`),s.push({type:"error",reason:r.stopReason,error:r}),s.end()}})(),s},At=(e,n,t)=>{Ce(e.provider,t?.apiKey,t?.headers);let s={...ce(e,n,t,t?.apiKey),toolChoice:t?.toolChoice},u=t?.reasoning?Q(e,t.reasoning):void 0;return He(e,n,{...s,reasoningEffort:u==="off"?void 0:u,thinkingBudgets:t?.thinkingBudgets})};function Ke(e,n,t,s,u,r,h,k=q(e)){let T={...J(e,u),...e.headers};if(e.provider==="github-copilot"){let a=ue(n.messages),m=fe({messages:n.messages,hasImages:a});Object.assign(T,m)}return h&&k.sendSessionAffinityHeaders&&(k.sessionAffinityFormat==="openrouter"?T["x-session-id"]=h:(k.sessionAffinityFormat==="openai"&&(T.session_id=h),T["x-client-request-id"]=h,T["x-session-affinity"]=h)),s&&Object.assign(T,s),new he({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:T})}function We(e,n,t,s=q(e),u=Me(t?.cacheRetention,t?.env),r=N(j(n.messages),s.supportsOpenAIGrammarTools)){let h=G(n.messages,s.supportsMidConvoSystemMessages===!0&&s.supportsMidConvoToolAdditions===!0?"additions":"none"),k=st(e,n,s,{grammarToolInputProperties:r}),T=Ze(s,u),a={model:e.id,messages:k,stream:!0,prompt_cache_key:e.baseUrl.includes("api.openai.com")&&u!=="none"||u==="long"&&s.supportsLongCacheRetention?ke(t?.sessionId):void 0,prompt_cache_retention:u==="long"&&s.supportsLongCacheRetention?"24h":void 0};s.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),s.supportsStore&&(a.store=!1),t?.maxTokens&&(s.maxTokensField==="max_tokens"?a.max_tokens=t.maxTokens:a.max_completion_tokens=t.maxTokens),t?.temperature!==void 0&&(a.temperature=t.temperature),h.requestTools.length>0?(a.tools=Ee(h.requestTools,s),s.zaiToolStream&&(a.tool_stream=!0)):be(n.messages)&&(a.tools=[]),T&&Qe(k,a.tools,T),t?.toolChoice&&(a.tool_choice=t.toolChoice),s.vllmPriority!==void 0&&(a.priority=s.vllmPriority);let m=Je(s),M=Ue(e,t,a);if(s.thinkingFormat==="zai"&&e.reasoning){let i=a;if(i.thinking=t?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},t?.reasoningEffort&&s.supportsReasoningEffort){let f=e.thinkingLevelMap?.[t.reasoningEffort],p=f===void 0?t.reasoningEffort:f;typeof p=="string"&&(i.reasoning_effort=p)}}else if(s.thinkingFormat==="qwen"&&e.reasoning){if(a.enable_thinking=!!t?.reasoningEffort,t?.reasoningEffort&&s.supportsReasoningEffort){let i=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;typeof i=="string"&&(a.reasoning_effort=i)}}else if(s.thinkingFormat==="qwen-chat-template"&&e.reasoning)a.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:!0};else if(s.thinkingFormat==="chat-template"&&e.reasoning){let i=ve(e,t,s.chatTemplateKwargs,M);i&&(a.chat_template_kwargs=i)}else if(s.thinkingFormat==="baseten"&&e.reasoning){let i=a,f=ve(e,t,s.chatTemplateArgs,M);if(f&&(i.chat_template_args=f),s.supportsReasoningEffort){let p=t?.reasoningEffort,R=p?e.thinkingLevelMap?.[p]:e.thinkingLevelMap?.off,A=R===void 0?p:R;typeof A=="string"&&(i.reasoning_effort=A)}}else if(s.thinkingFormat==="deepseek"&&e.reasoning)t?.reasoningEffort?a.thinking={type:"enabled"}:e.thinkingLevelMap?.off!==null&&(a.thinking={type:"disabled"}),t?.reasoningEffort&&s.supportsReasoningEffort&&(a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort);else if(s.thinkingFormat==="openrouter"&&e.reasoning){let i=a;t?.reasoningEffort?i.reasoning={effort:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(i.reasoning={effort:e.thinkingLevelMap?.off??"none"})}else if(s.thinkingFormat==="ant-ling"&&e.reasoning&&t?.reasoningEffort){let i=e.thinkingLevelMap?.[t.reasoningEffort];typeof i=="string"&&(a.reasoning={effort:i})}else if(s.thinkingFormat==="together"&&e.reasoning){let i=a;i.reasoning={enabled:!!t?.reasoningEffort},t?.reasoningEffort&&s.supportsReasoningEffort&&(i.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort)}else if(s.thinkingFormat==="string-thinking"&&e.reasoning){let i=a;t?.reasoningEffort?i.thinking=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort:e.thinkingLevelMap?.off!==null&&(i.thinking=e.thinkingLevelMap?.off??"none")}else if(t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort)a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(!t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort){let i=e.thinkingLevelMap?.off;typeof i=="string"&&(a.reasoning_effort=i)}if(m&&M!==void 0&&Object.assign(a,{[m]:M}),e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){let i=e.compat.vercelGatewayRouting;if(i.only||i.order){let f={};i.only&&(f.only=i.only),i.order&&(f.order=i.order),a.providerOptions={gateway:f}}}let g=le(e,t?.reasoningEffort??"off",t?.samplingParams);return g&&Object.assign(a,g),a}function Je(e){if(e.thinkingTokenBudgetField)return e.thinkingTokenBudgetField;if(e.supportsThinkingTokenBudget)return"thinking_token_budget"}function Ue(e,n,t){if(!n?.reasoningEffort||!e.reasoning)return;let s=t.max_tokens??t.max_completion_tokens??e.maxTokens,u=ge(pe(n.reasoningEffort,n.thinkingBudgets),s);return u>0?u:void 0}function ve(e,n,t,s){let u={};for(let[r,h]of Object.entries(t)){let k=Ve(e,n,h,s);k!==void 0&&(u[r]=k)}return Object.keys(u).length>0?u:void 0}function Ve(e,n,t,s){if(typeof t!="object"||t===null)return t;let u=n?.reasoningEffort;if(!u&&t.omitWhenOff)return;if(t.$var==="thinking.enabled")return!!u;if(t.$var==="thinking.budget")return s;let r=u?e.thinkingLevelMap?.[u]:e.thinkingLevelMap?.off;return r===void 0?u:typeof r=="string"?r:void 0}function Ze(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 Qe(e,n,t){Xe(e,t),et(n,t),Ye(e,t)}function Xe(e,n){for(let t of e)if(t.role==="system"||t.role==="developer"){tt(t,n);return}}function Ye(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")&&nt(s,n))return}}function et(e,n){if(!e||e.length===0)return;let t=e[e.length-1];t.cache_control=n}function tt(e,n){return Ie(e,n)}function nt(e,n){return e.role==="user"||e.role==="assistant"||e.role==="tool"?Ie(e,n):!1}function Ie(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 u=t[s];if(u?.type==="text"){let r=u;return r.cache_control=n,!0}}return!1}function st(e,n,t,s){let u=z(n,t.supportsMidConvoSystemMessages),r=[],h=g=>{if(g.includes("|")){let i=g.indexOf("|"),f=g.slice(0,i).replace(/[^a-zA-Z0-9_-]/g,"_"),p=g.slice(i+1).replace(/[^a-zA-Z0-9_-]/g,"_"),R=p.length>0?`${f}_${p}`:f;if(R.length<=40)return R;let A=Te(g).slice(0,8);return`${f.slice(0,Math.max(1,40-A.length-1))}_${A}`}return e.provider==="openai"&&g.length>40?g.slice(0,40):g},k=de(u.messages,e,g=>h(g)),T=G(u.messages,t.supportsMidConvoSystemMessages===!0&&t.supportsMidConvoToolAdditions===!0?"additions":"none"),a=e.reasoning&&t.supportsDeveloperRole?"developer":"system",m=null,M=0;for(let g=0;g<k.length;g++){let i=k[g];if(t.requiresAssistantAfterToolResult&&m==="toolResult"&&i.role==="user"&&r.push({role:"assistant",content:"I have processed the tool results."}),i.role==="system"){let f=M++>=T.foldedSystemMessages?i.toolsAdded??[]:[];if(f.length>0){let R={role:"system",tools:Ee(f,t)};r.push(R)}let p=g===0?U(i):V(i);p.length>0&&r.push({role:a,content:b(p)})}else if(i.role==="user")if(typeof i.content=="string")r.push({role:"user",content:b(i.content)});else{let f=i.content.filter(p=>p.type!=="text"||p.text.length>0).map(p=>p.type==="text"?{type:"text",text:b(p.text)}:{type:"image_url",image_url:{url:`data:${p.mimeType};base64,${p.data}`}});if(f.length===0)continue;r.push({role:"user",content:f})}else if(i.role==="assistant"){let f={role:"assistant",content:t.requiresAssistantAfterToolResult?"":null},p=i.content.filter(xe).filter(l=>l.text.trim().length>0).map(l=>({type:"text",text:b(l.text)})),R=p.map(l=>l.text).join(""),A=i.content.filter(Be),I=i.content.filter(Pe),O=A.map(l=>ze(l.thinkingSignature)).find(l=>l!==void 0),E=I.map(l=>je(l.thoughtSignature)).filter(l=>l!==void 0),S=O??(E.length>0?E:void 0),v=A.filter(l=>l.thinking.trim().length>0);if(v.length>0){if(t.requiresThinkingAsText){let l=v.map(F=>b(F.thinking)).join(`
|
|
6
|
-
|
|
7
|
-
`);f.content=[{type:"text",text:l},...p]}else if(R.length>0&&(f.content=R),!S){let l=v[0].thinkingSignature;e.provider==="opencode-go"&&l==="reasoning"&&(l="reasoning_content"),l&&$e(l)&&(f[l]=v.map(F=>F.thinking).join(`
|
|
8
|
-
`))}}else R.length>0&&(f.content=R);I.length>0&&(f.tool_calls=I.map(l=>{let F=s?.grammarToolInputProperties?.get(l.name);return F!==void 0?{id:l.id,type:"custom",custom:{name:l.name,input:b(re(l.name,l.arguments,F))}}:{id:l.id,type:"function",function:{name:l.name,arguments:JSON.stringify(l.arguments)}}})),S&&(f.reasoning_details=S),t.requiresReasoningContentOnAssistantMessages&&e.reasoning&&f.reasoning_content===void 0&&(f.reasoning_content="");let w=f.content;if(!(w!=null&&w.length>0)&&!f.tool_calls)continue;r.push(f)}else if(i.role==="toolResult"){let f=[],p=g;for(;p<k.length&&k[p].role==="toolResult";p++){let R=k[p],A=R.content.filter(xe).map(v=>v.text).join(`
|
|
9
|
-
`),I=R.content.some(v=>v.type==="image"),E=A.trim().length>0?A:I?"(see attached image)":"(no tool output)",S={role:"tool",content:b(E),tool_call_id:R.toolCallId};if(t.requiresToolResultName&&R.toolName&&(S.name=R.toolName),r.push(S),I&&e.input.includes("image"))for(let v of R.content)Le(v)&&f.push({type:"image_url",image_url:{url:`data:${v.mimeType};base64,${v.data}`}})}g=p-1,f.length>0?(t.requiresAssistantAfterToolResult&&r.push({role:"assistant",content:"I have processed the tool results."}),r.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...f]}),m="user"):m="toolResult";continue}m=i.role}return r}function Ee(e,n){return e.map(t=>{let s=ae(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 u=ie(t,n.supportsStrictMode!==!1);return{type:"function",function:{name:t.name,description:t.description,parameters:se(t,u),...n.supportsStrictMode!==!1&&{strict:u??!1}}}})}function Ae(e,n){let t=e.prompt_tokens||0,s=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??e.cached_tokens??0,u=e.prompt_tokens_details?.cache_write_tokens||0,r=Math.max(0,t-s-u),h=e.completion_tokens||0,k={input:r,output:h,cacheRead:s,cacheWrite:u,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:r+h+s+u,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return Z(n,k),k}function rt(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 ot(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"),u=n==="together"||t.includes("api.together.ai")||t.includes("api.together.xyz"),r=n==="moonshotai"||n==="moonshotai-cn"||t.includes("api.moonshot."),h=n==="openrouter"||t.includes("openrouter.ai"),k=n==="cloudflare-workers-ai"||t.includes("api.cloudflare.com"),T=n==="cloudflare-ai-gateway"||t.includes("gateway.ai.cloudflare.com"),a=n==="nvidia"||t.includes("integrate.api.nvidia.com"),m=n==="ant-ling"||t.includes("api.ant-ling.com"),M=n==="cerebras"||t.includes("cerebras.ai"),g=n==="deepseek"||t.toLowerCase().includes("deepseek.com"),i=a||M||n==="xai"||t.includes("api.x.ai")||u||t.includes("chutes.ai")||g||s||r||n==="opencode"||t.includes("opencode.ai")||k||T||m,f=t.includes("chutes.ai")||g||r||T||u||a||m||s,p=n==="xai"||t.includes("api.x.ai"),R=h&&(e.id.startsWith("anthropic/")||e.id.startsWith("openai/")),A=n==="openrouter"&&e.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!i,supportsDeveloperRole:R||!i&&!h,supportsReasoningEffort:!p&&!s&&!r&&!u&&!T&&!a&&!m,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:f?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:g,thinkingFormat:g?"deepseek":s?"zai":u?"together":m?"ant-ling":h?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!1,supportsOpenAIGrammarTools:!1,supportsMidConvoSystemMessages:!1,supportsMidConvoToolAdditions:!1,cacheControlFormat:A,sendSessionAffinityHeaders:h,sessionAffinityFormat:h?"openrouter":"openai",supportsLongCacheRetention:!(u||k||T||a||m)}}function q(e){let n=ot(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,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,vllmPriority:e.compat.vllmPriority}:n}export{st as convertMessages,He as stream,At as streamSimple};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{a as G,b as U,c as N,d as D}from"./chunk-7GAYFN52.js";import{a as L}from"./chunk-XIECJESP.js";import"./chunk-V3AQJSWR.js";import{a as x}from"./chunk-CVC66CFV.js";import{a as k,b}from"./chunk-FF7UELTU.js";import{a as A,b as O}from"./chunk-BGYR4ID3.js";import"./chunk-SKHLZ6XY.js";import{a as E}from"./chunk-6R73ICDB.js";import{a as _}from"./chunk-23PRJECN.js";import{f as P,h as I,i as w}from"./chunk-QBKCAIJG.js";import{C as y,F as C,L as M,y as R}from"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import"./chunk-USBJFDJ6.js";import{a as S}from"./chunk-K4NTZEDJ.js";import{h as v}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as T}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var V=new Set(["openai","openai-codex","opencode"]),B=16,J="https://chatgpt.com/settings/usage",Q="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.",Y="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,a]of Object.entries(e))if(s.toLowerCase()===r&&a!==null&&a.trim().length>0)return!0;return!1}function K(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 q(e,t){return e||(E("PI_CACHE_RETENTION",t)==="long"?"long":"short")}function g(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:e.compat?.sessionAffinityFormat??X(e),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 T,a=R(t,g(e).supportsMidConvoSystemMessages);return(async()=>{let u=g(e),c=Z(e,r,u),o={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,...c===void 0?{}:{providerThinkingLevel:c},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 i=K(e.provider,r?.apiKey,r?.headers),n=q(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,f=P(y(a.messages),u.supportsOpenAIGrammarTools),l=se(e,a,i,r?.headers,r?.identity,r?.fetch,n),d=oe(e,a,r,u,f,c),m=await r?.onPayload?.(d,e);m!==void 0&&(d=m);let W={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},{data:$,response:h}=await _(()=>l.responses.create(d,W).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});if(await r?.onResponse?.({status:h.status,headers:S(h.headers)},e),s.push({type:"start",partial:o}),await D($,o,s,e,{onProviderStreamEvent:r?.onProviderStreamEvent,serviceTier:r?.serviceTier,grammarToolInputProperties:f,applyServiceTierPricing:(j,z)=>ie(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(i){for(let n of o.content)delete n.index,delete n.partialJson,delete n.customInput;o.stopReason=r?.signal?.aborted?"aborted":"error";let p=b(k(i),`${e.provider==="openai"?"OpenAI":e.provider} API error`);p.includes("subscription_sharing_usage_limit_exceeded")?o.errorMessage=`${p}
|
|
5
|
-
Check your ChatGPT usage: ${J}`:p.includes("subscription_sharing_workplace_individual_usage_limit_exceeded")?o.errorMessage=`${p}
|
|
6
|
-
${Q}`:o.errorMessage=p,s.push({type:"error",reason:o.stopReason,error:o}),s.end()}})(),s},Ce=(e,t,r)=>{K(e.provider,r?.apiKey,r?.headers);let s={...w(e,t,r,r?.apiKey),toolChoice:r?.toolChoice},a=r?.reasoning?M(e,r.reasoning):void 0;return te(e,t,{...s,reasoningEffort:a==="off"?void 0:a})};function se(e,t,r,s,a,u,c){let o=g(e),i={...v(e,a),...e.headers};if(e.provider==="github-copilot"){let p=A(t.messages),n=O({messages:t.messages,hasImages:p});Object.assign(i,n)}return c&&(o.sessionAffinityFormat==="openrouter"?i["x-session-id"]=c:(o.sessionAffinityFormat==="openai"&&(i.session_id=c),i["x-client-request-id"]=c)),s&&Object.assign(i,s),new x({apiKey:r,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:u,defaultHeaders:i})}function oe(e,t,r,s,a,u){let c=C(t.messages,G(s)),o=U(e,t,V,{grammarToolInputProperties:a,supportsMidConvoSystemMessages:s.supportsMidConvoSystemMessages,supportsAdditionalTools:s.supportsAdditionalTools,supportsToolSearch:s.supportsToolSearch,toolOptions:{supportsStrictMode:s.supportsStrictMode,supportsOpenAIGrammarTools:s.supportsOpenAIGrammarTools},configurationUpdateEffort:u}),i=q(r?.cacheRetention,r?.env),p=H(e,r?.apiKey),n={model:e.id,input:o,stream:!0,prompt_cache_key:i==="none"?void 0:L(r?.sessionId),prompt_cache_retention:p?void 0:ee(s,i),prompt_cache_options:p?void 0:re(s,i),store:!1};r?.maxTokens&&s.supportsMaxOutputTokens&&!p&&(n.max_output_tokens=Math.max(r.maxTokens,B)),r?.temperature!==void 0&&!p&&(n.temperature=r?.temperature),r?.serviceTier!==void 0&&(n.service_tier=r.serviceTier),c.requestTools.length>0&&(n.tools=N(c.requestTools,{supportsStrictMode:s.supportsStrictMode,supportsOpenAIGrammarTools:s.supportsOpenAIGrammarTools})),r?.toolChoice!==void 0&&(n.tool_choice=r.toolChoice);let f=r?.reasoningEffort??(r?.reasoningSummary?"medium":void 0);if(e.reasoning){if(f){let d=r?.reasoningEffort?e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort:f,m=u===void 0?d:Y;n.reasoning={effort:m,summary:r?.reasoningSummary||"auto"},n.include=["reasoning.encrypted_content"]}else e.provider!=="github-copilot"&&e.thinkingLevelMap?.off!==null&&(n.reasoning={effort:e.thinkingLevelMap?.off??"none"});e.provider==="xai"&&(n.include=["reasoning.encrypted_content"])}let l=I(e,f??"off",r?.samplingParams);return l&&Object.assign(n,l),n}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 ie(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,Ce as streamSimple};
|
|
@@ -1,4 +0,0 @@
|
|
|
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 k}from"./chunk-CVC66CFV.js";import{a as w,b as T}from"./chunk-FF7UELTU.js";import{a as x}from"./chunk-23PRJECN.js";import{a as _}from"./chunk-USBJFDJ6.js";import{a as y,b as R}from"./chunk-K4NTZEDJ.js";import{h as l}from"./chunk-6AKUD3CF.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=b(e,a,t?.headers,t?.fetch,t?.identity),n=M(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:v,response:g}=await x(()=>i.chat.completions.create(n,o).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:g.status,headers:y(g.headers)},e);let u=v;r.responseId=u.id,u.usage&&(r.usage=P(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=T(w(a)),r}};function b(e,s,t,r,a){return new k({apiKey:s,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:R(l(e,a),e.headers,t)})}function M(e,s){let t=s.input.map(r=>r.type==="text"?{type:"text",text:_(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 P(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}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}export{H as generateImages};
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{d as x}from"./chunk-SKHLZ6XY.js";import{a as y}from"./chunk-6R73ICDB.js";import{c as h,d as p}from"./chunk-D6VMBA4C.js";import{a as k,b as w}from"./chunk-K4NTZEDJ.js";import{h as m}from"./chunk-6AKUD3CF.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 R(r){return r.length>8192?`${r.slice(0,8192)}\u2026`:r}function S(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,a=e??t,o=s?` (${s})`:"";return`${r.status} ${r.statusText}: ${a}${o}`}function _(r,t,n,e){let s=T(e),a=typeof s?.error?.code=="string"?s.error.code:void 0;return new g(S(n,e,s),a,{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:R(e)},timestampMs:Date.now()})}function E(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function b(r,t){t&&p(r,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...t}})}function M(r){let t={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:E(),stopReason:"pending",timestamp:Date.now()},n=new Map;return e=>{switch(e.type){case"done":return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),b(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.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),b(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,"");break;case"toolcall_delta":{let s=`${n.get(e.contentIndex)??""}${e.delta}`;n.set(e.contentIndex,s),t.content[e.contentIndex].arguments=x(s);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:a}=await n.read();e+=s?t.decode():t.decode(a,{stream:!0}),e=e.replace(/\r\n/g,`
|
|
5
|
-
`);let o=e.indexOf(`
|
|
6
|
-
|
|
7
|
-
`);for(;o!==-1;){let c=I(e.slice(0,o));c&&(yield c),e=e.slice(o+2),o=e.indexOf(`
|
|
8
|
-
|
|
9
|
-
`)}if(s)break}if(e.trim()){let s=I(e);s&&(yield s)}}finally{n.releaseLock()}}function I(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:E(),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 O(r,t){return r||(y("PI_CACHE_RETENTION",t)==="long"?"long":void 0)}var P=(r,t,n)=>{let e=new f,s=M(r);return(async()=>{try{let a=n?.apiKey;if(!a)throw new Error(`No API key provided for provider "${r.provider}"`);let o=new URL(`${r.baseUrl.replace(/\/+$/u,"")}/messages`);n?.debug&&o.searchParams.set("debug","1");let c={model:r.id,context:t,options:{temperature:n?.temperature,maxTokens:n?.maxTokens,reasoning:n?.reasoning,cacheRetention:O(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)(o,{method:"POST",headers:w(m(r,n?.identity),{authorization:`Bearer ${a}`,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:k(i.headers)},r),!i.ok){let d=await i.text();throw _(r,o,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(a){e.push(D(r,a,n?.signal?.aborted??!1))}})(),e},v=(r,t,n)=>{let e=n;return P(r,t,{...n,reasoning:n?.reasoning,toolChoice:n?.toolChoice,debug:e?.debug})};export{g as PiMessagesResponseError,P as stream,v as streamSimple};
|