diff --git a/package-lock.json b/package-lock.json
index 8fdc808..f0858ad 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -32,7 +32,10 @@
"pino-pretty": "^13.0.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
+ "react-markdown": "^10.1.0",
"recharts": "^3.7.0",
+ "rehype-highlight": "^7.0.2",
+ "remark-gfm": "^4.0.1",
"sonner": "^2.0.3",
"tailwind-merge": "^3.3.0",
"zod": "^3.25.20"
@@ -2890,13 +2893,39 @@
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
"license": "MIT"
},
+ "node_modules/@types/debug": {
+ "version": "4.1.12",
+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",
+ "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/ms": "*"
+ }
+ },
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
- "dev": true,
"license": "MIT"
},
+ "node_modules/@types/estree-jsx": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz",
+ "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "*"
+ }
+ },
+ "node_modules/@types/hast": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",
+ "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
@@ -2911,6 +2940,21 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/mdast": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",
+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
+ "node_modules/@types/ms": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "22.19.11",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.11.tgz",
@@ -2925,7 +2969,6 @@
"version": "19.2.14",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
- "devOptional": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@@ -2941,6 +2984,12 @@
"@types/react": "^19.2.0"
}
},
+ "node_modules/@types/unist": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
+ "license": "MIT"
+ },
"node_modules/@types/use-sync-external-store": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
@@ -3244,6 +3293,12 @@
"url": "https://opencollective.com/eslint"
}
},
+ "node_modules/@ungap/structured-clone": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
+ "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==",
+ "license": "ISC"
+ },
"node_modules/@unrs/resolver-binding-android-arm-eabi": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz",
@@ -3820,6 +3875,16 @@
"node": ">= 0.4"
}
},
+ "node_modules/bail": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",
+ "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -3946,6 +4011,16 @@
],
"license": "CC-BY-4.0"
},
+ "node_modules/ccount": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",
+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@@ -3963,6 +4038,46 @@
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
+ "node_modules/character-entities": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-html4": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz",
+ "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-legacy": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-reference-invalid": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",
+ "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/class-variance-authority": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz",
@@ -4025,6 +4140,16 @@
"integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
"license": "MIT"
},
+ "node_modules/comma-separated-tokens": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -4060,7 +4185,6 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
- "devOptional": true,
"license": "MIT"
},
"node_modules/d3-array": {
@@ -4287,6 +4411,19 @@
"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
"license": "MIT"
},
+ "node_modules/decode-named-character-reference": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",
+ "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==",
+ "license": "MIT",
+ "dependencies": {
+ "character-entities": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@@ -4339,6 +4476,15 @@
"node": ">=0.10"
}
},
+ "node_modules/dequal": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -4355,6 +4501,19 @@
"integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==",
"license": "MIT"
},
+ "node_modules/devlop": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",
+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",
+ "license": "MIT",
+ "dependencies": {
+ "dequal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/doctrine": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz",
@@ -5088,6 +5247,16 @@
"node": ">=4.0"
}
},
+ "node_modules/estree-util-is-identifier-name": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",
+ "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/esutils": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
@@ -5104,6 +5273,12 @@
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
"license": "MIT"
},
+ "node_modules/extend": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
+ "license": "MIT"
+ },
"node_modules/fast-copy": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-4.0.2.tgz",
@@ -5559,12 +5734,100 @@
"node": ">= 0.4"
}
},
+ "node_modules/hast-util-is-element": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-3.0.0.tgz",
+ "integrity": "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-to-jsx-runtime": {
+ "version": "2.3.6",
+ "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",
+ "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "comma-separated-tokens": "^2.0.0",
+ "devlop": "^1.0.0",
+ "estree-util-is-identifier-name": "^3.0.0",
+ "hast-util-whitespace": "^3.0.0",
+ "mdast-util-mdx-expression": "^2.0.0",
+ "mdast-util-mdx-jsx": "^3.0.0",
+ "mdast-util-mdxjs-esm": "^2.0.0",
+ "property-information": "^7.0.0",
+ "space-separated-tokens": "^2.0.0",
+ "style-to-js": "^1.0.0",
+ "unist-util-position": "^5.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-to-text": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.2.tgz",
+ "integrity": "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "hast-util-is-element": "^3.0.0",
+ "unist-util-find-after": "^5.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-whitespace": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",
+ "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/help-me": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz",
"integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==",
"license": "MIT"
},
+ "node_modules/highlight.js": {
+ "version": "11.11.1",
+ "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.11.1.tgz",
+ "integrity": "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/html-url-attributes": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
+ "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -5612,6 +5875,12 @@
"node": ">=0.8.19"
}
},
+ "node_modules/inline-style-parser": {
+ "version": "0.2.7",
+ "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",
+ "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==",
+ "license": "MIT"
+ },
"node_modules/internal-slot": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",
@@ -5660,6 +5929,30 @@
"url": "https://opencollective.com/ioredis"
}
},
+ "node_modules/is-alphabetical": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",
+ "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-alphanumerical": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",
+ "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",
+ "license": "MIT",
+ "dependencies": {
+ "is-alphabetical": "^2.0.0",
+ "is-decimal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-array-buffer": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
@@ -5805,6 +6098,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-decimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",
+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@@ -5864,6 +6167,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/is-hexadecimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-map": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz",
@@ -5917,6 +6230,18 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-plain-obj": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
+ "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/is-regex": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",
@@ -6532,6 +6857,16 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/longest-streak": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",
+ "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
@@ -6545,6 +6880,21 @@
"loose-envify": "cli.js"
}
},
+ "node_modules/lowlight": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/lowlight/-/lowlight-3.3.0.tgz",
+ "integrity": "sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "devlop": "^1.0.0",
+ "highlight.js": "~11.11.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
@@ -6576,6 +6926,16 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
+ "node_modules/markdown-table": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",
+ "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -6586,6 +6946,288 @@
"node": ">= 0.4"
}
},
+ "node_modules/mdast-util-find-and-replace": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz",
+ "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "escape-string-regexp": "^5.0.0",
+ "unist-util-is": "^6.0.0",
+ "unist-util-visit-parents": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",
+ "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/mdast-util-from-markdown": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz",
+ "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-to-string": "^4.0.0",
+ "micromark": "^4.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-decode-string": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0",
+ "unist-util-stringify-position": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",
+ "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-gfm-autolink-literal": "^2.0.0",
+ "mdast-util-gfm-footnote": "^2.0.0",
+ "mdast-util-gfm-strikethrough": "^2.0.0",
+ "mdast-util-gfm-table": "^2.0.0",
+ "mdast-util-gfm-task-list-item": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-autolink-literal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz",
+ "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "ccount": "^2.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-find-and-replace": "^3.0.0",
+ "micromark-util-character": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-footnote": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",
+ "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.1.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-strikethrough": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz",
+ "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-table": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz",
+ "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "markdown-table": "^3.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-task-list-item": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz",
+ "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdx-expression": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",
+ "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdx-jsx": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz",
+ "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "ccount": "^2.0.0",
+ "devlop": "^1.1.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "parse-entities": "^4.0.0",
+ "stringify-entities": "^4.0.0",
+ "unist-util-stringify-position": "^4.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdxjs-esm": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz",
+ "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-phrasing": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",
+ "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-hast": {
+ "version": "13.2.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",
+ "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "@ungap/structured-clone": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "trim-lines": "^3.0.0",
+ "unist-util-position": "^5.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-markdown": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz",
+ "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "longest-streak": "^3.0.0",
+ "mdast-util-phrasing": "^4.0.0",
+ "mdast-util-to-string": "^4.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-decode-string": "^2.0.0",
+ "unist-util-visit": "^5.0.0",
+ "zwitch": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-string": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",
+ "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/memory-pager": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz",
@@ -6602,6 +7244,569 @@
"node": ">= 8"
}
},
+ "node_modules/micromark": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",
+ "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@types/debug": "^4.0.0",
+ "debug": "^4.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-core-commonmark": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-combine-extensions": "^2.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-encode": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-subtokenize": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-core-commonmark": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz",
+ "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-factory-destination": "^2.0.0",
+ "micromark-factory-label": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-factory-title": "^2.0.0",
+ "micromark-factory-whitespace": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-html-tag-name": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-subtokenize": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-extension-gfm": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",
+ "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-extension-gfm-autolink-literal": "^2.0.0",
+ "micromark-extension-gfm-footnote": "^2.0.0",
+ "micromark-extension-gfm-strikethrough": "^2.0.0",
+ "micromark-extension-gfm-table": "^2.0.0",
+ "micromark-extension-gfm-tagfilter": "^2.0.0",
+ "micromark-extension-gfm-task-list-item": "^2.0.0",
+ "micromark-util-combine-extensions": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-autolink-literal": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",
+ "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-footnote": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",
+ "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-core-commonmark": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-strikethrough": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",
+ "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-table": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz",
+ "integrity": "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-tagfilter": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",
+ "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-task-list-item": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",
+ "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-factory-destination": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",
+ "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-label": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",
+ "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-space": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz",
+ "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-title": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",
+ "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-whitespace": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",
+ "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-character": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",
+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-chunked": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",
+ "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-classify-character": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",
+ "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-combine-extensions": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",
+ "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-decode-numeric-character-reference": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",
+ "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-decode-string": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",
+ "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decode-named-character-reference": "^1.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-encode": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",
+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-html-tag-name": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",
+ "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-normalize-identifier": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",
+ "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-resolve-all": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",
+ "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-sanitize-uri": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",
+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-encode": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-subtokenize": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",
+ "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-symbol": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",
+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-types": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",
+ "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
@@ -7164,6 +8369,31 @@
"node": ">=6"
}
},
+ "node_modules/parse-entities": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",
+ "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^2.0.0",
+ "character-entities-legacy": "^3.0.0",
+ "character-reference-invalid": "^2.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "is-alphanumerical": "^2.0.0",
+ "is-decimal": "^2.0.0",
+ "is-hexadecimal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/parse-entities/node_modules/@types/unist": {
+ "version": "2.0.11",
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",
+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
+ "license": "MIT"
+ },
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
@@ -7526,6 +8756,16 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/property-information": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",
+ "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/pump": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz",
@@ -7600,6 +8840,33 @@
"license": "MIT",
"peer": true
},
+ "node_modules/react-markdown": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
+ "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "hast-util-to-jsx-runtime": "^2.0.0",
+ "html-url-attributes": "^3.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "remark-parse": "^11.0.0",
+ "remark-rehype": "^11.0.0",
+ "unified": "^11.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ },
+ "peerDependencies": {
+ "@types/react": ">=18",
+ "react": ">=18"
+ }
+ },
"node_modules/react-redux": {
"version": "9.2.0",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
@@ -7811,6 +9078,89 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/rehype-highlight": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/rehype-highlight/-/rehype-highlight-7.0.2.tgz",
+ "integrity": "sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "hast-util-to-text": "^4.0.0",
+ "lowlight": "^3.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-gfm": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",
+ "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-gfm": "^3.0.0",
+ "micromark-extension-gfm": "^3.0.0",
+ "remark-parse": "^11.0.0",
+ "remark-stringify": "^11.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-parse": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",
+ "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "micromark-util-types": "^2.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-rehype": {
+ "version": "11.1.2",
+ "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz",
+ "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "unified": "^11.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-stringify": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz",
+ "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/reselect": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",
@@ -8213,6 +9563,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/space-separated-tokens": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/sparse-bitfield": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz",
@@ -8371,6 +9731,20 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/stringify-entities": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
+ "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",
+ "license": "MIT",
+ "dependencies": {
+ "character-entities-html4": "^2.0.0",
+ "character-entities-legacy": "^3.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/strip-bom": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
@@ -8394,6 +9768,24 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/style-to-js": {
+ "version": "1.1.21",
+ "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",
+ "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==",
+ "license": "MIT",
+ "dependencies": {
+ "style-to-object": "1.0.14"
+ }
+ },
+ "node_modules/style-to-object": {
+ "version": "1.0.14",
+ "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz",
+ "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==",
+ "license": "MIT",
+ "dependencies": {
+ "inline-style-parser": "0.2.7"
+ }
+ },
"node_modules/styled-jsx": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz",
@@ -8562,6 +9954,26 @@
"node": ">=18"
}
},
+ "node_modules/trim-lines": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
+ "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/trough": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz",
+ "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/ts-api-utils": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz",
@@ -8745,6 +10157,107 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/unified": {
+ "version": "11.0.5",
+ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",
+ "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "bail": "^2.0.0",
+ "devlop": "^1.0.0",
+ "extend": "^3.0.0",
+ "is-plain-obj": "^4.0.0",
+ "trough": "^2.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-find-after": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-find-after/-/unist-util-find-after-5.0.0.tgz",
+ "integrity": "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-is": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz",
+ "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-position": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz",
+ "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-stringify-position": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",
+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-visit": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz",
+ "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0",
+ "unist-util-visit-parents": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-visit-parents": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",
+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/unrs-resolver": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.11.1.tgz",
@@ -8851,6 +10364,34 @@
"uuid": "dist/bin/uuid"
}
},
+ "node_modules/vfile": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",
+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/vfile-message": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",
+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-stringify-position": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/victory-vendor": {
"version": "37.3.6",
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",
@@ -9043,6 +10584,16 @@
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
+ },
+ "node_modules/zwitch": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
}
}
}
diff --git a/package.json b/package.json
index ff39102..79c056d 100644
--- a/package.json
+++ b/package.json
@@ -39,7 +39,10 @@
"pino-pretty": "^13.0.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
+ "react-markdown": "^10.1.0",
"recharts": "^3.7.0",
+ "rehype-highlight": "^7.0.2",
+ "remark-gfm": "^4.0.1",
"sonner": "^2.0.3",
"tailwind-merge": "^3.3.0",
"zod": "^3.25.20"
diff --git a/scripts/seed.ts b/scripts/seed.ts
index 04c9972..05887bd 100644
--- a/scripts/seed.ts
+++ b/scripts/seed.ts
@@ -207,6 +207,51 @@ async function main() {
providerModelId: "sonar-reasoning-pro",
priority: 0,
},
+ // Image generation models
+ {
+ logicalModelId: "gpt-image-1",
+ providerId: "openai",
+ providerModelId: "gpt-image-1",
+ priority: 0,
+ modelType: "image",
+ },
+ {
+ logicalModelId: "dall-e-3",
+ providerId: "openai",
+ providerModelId: "dall-e-3",
+ priority: 0,
+ modelType: "image",
+ },
+ {
+ logicalModelId: "dall-e-2",
+ providerId: "openai",
+ providerModelId: "dall-e-2",
+ priority: 0,
+ modelType: "image",
+ },
+ // Audio TTS models
+ {
+ logicalModelId: "tts-1",
+ providerId: "openai",
+ providerModelId: "tts-1",
+ priority: 0,
+ modelType: "audio",
+ },
+ {
+ logicalModelId: "tts-1-hd",
+ providerId: "openai",
+ providerModelId: "tts-1-hd",
+ priority: 0,
+ modelType: "audio",
+ },
+ // Grok image model
+ {
+ logicalModelId: "grok-2-image",
+ providerId: "grok",
+ providerModelId: "grok-2-image",
+ priority: 0,
+ modelType: "image",
+ },
];
for (const mapping of mappings) {
@@ -218,7 +263,7 @@ async function main() {
},
{
$setOnInsert: { _id: crypto.randomUUID(), createdAt: now },
- $set: { ...mapping, enabled: true, updatedAt: now },
+ $set: { ...mapping, enabled: true, modelType: mapping.modelType ?? "chat", updatedAt: now },
},
{ upsert: true },
);
diff --git a/src/app/(auth)/layout.tsx b/src/app/(auth)/layout.tsx
index 41bc258..36c47a1 100644
--- a/src/app/(auth)/layout.tsx
+++ b/src/app/(auth)/layout.tsx
@@ -1,6 +1,6 @@
export default function AuthLayout({ children }: { children: React.ReactNode }) {
return (
-
+
);
diff --git a/src/app/(auth)/login/page.tsx b/src/app/(auth)/login/page.tsx
index e7204b1..605494d 100644
--- a/src/app/(auth)/login/page.tsx
+++ b/src/app/(auth)/login/page.tsx
@@ -46,9 +46,9 @@ function LoginForm() {
}
return (
-
+
-
Sign In
+
Sign In
Enter your credentials to continue
diff --git a/src/app/(auth)/register/page.tsx b/src/app/(auth)/register/page.tsx
index e693a2b..3930749 100644
--- a/src/app/(auth)/register/page.tsx
+++ b/src/app/(auth)/register/page.tsx
@@ -56,9 +56,9 @@ export default function RegisterPage() {
}
return (
-
+
-
Create Account
+
Create Account
Get started with LLM Proxy
diff --git a/src/app/admin/layout.tsx b/src/app/admin/layout.tsx
index 12006bb..567a126 100644
--- a/src/app/admin/layout.tsx
+++ b/src/app/admin/layout.tsx
@@ -9,11 +9,11 @@ export default async function AdminLayout({ children }: { children: React.ReactN
if (session.user.role !== "ADMIN") redirect("/dashboard");
return (
-
+
- {children}
+ {children}
);
diff --git a/src/app/admin/page.tsx b/src/app/admin/page.tsx
index 71598fd..a9ab952 100644
--- a/src/app/admin/page.tsx
+++ b/src/app/admin/page.tsx
@@ -16,10 +16,10 @@ export default async function AdminOverview() {
]);
const stats = [
- { title: "Total Users", value: userCount, icon: Users },
- { title: "Active Providers", value: providerCount, icon: Server },
- { title: "Active Provider Keys", value: providerKeyCount, icon: Key },
- { title: "Requests Today", value: todayLogs, icon: Activity },
+ { title: "Total Users", value: userCount, icon: Users, color: "text-blue-400" },
+ { title: "Active Providers", value: providerCount, icon: Server, color: "text-cyan-400" },
+ { title: "Active Provider Keys", value: providerKeyCount, icon: Key, color: "text-violet-400" },
+ { title: "Requests Today", value: todayLogs, icon: Activity, color: "text-emerald-400" },
];
return (
@@ -27,10 +27,10 @@ export default async function AdminOverview() {
Admin Overview
{stats.map((stat) => (
-
+
{stat.title}
-
+
{stat.value}
diff --git a/src/app/api/chat/conversations/[conversationId]/messages/route.ts b/src/app/api/chat/conversations/[conversationId]/messages/route.ts
new file mode 100644
index 0000000..ad0a1c6
--- /dev/null
+++ b/src/app/api/chat/conversations/[conversationId]/messages/route.ts
@@ -0,0 +1,295 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { getSession } from "@/lib/auth-helpers";
+import { db } from "@/lib/db";
+import { logger } from "@/lib/logger";
+import { checkRateLimit } from "@/server/services/rate-limiter";
+import { resolveModelRouteCandidates } from "@/server/services/model-router";
+import { logUsage } from "@/server/services/usage-logger";
+import { ApiError, internalError, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
+import { sseHeaders } from "@/server/services/streaming";
+import type { UnifiedChatRequest } from "@/types/unified-request";
+
+const imagePartSchema = z.object({
+ type: z.literal("image_url"),
+ image_url: z.object({
+ url: z.string().min(1),
+ detail: z.enum(["auto", "low", "high"]).optional(),
+ }),
+});
+
+const messageSchema = z.object({
+ content: z.string().trim().min(1),
+ images: z.array(imagePartSchema).max(10).optional(),
+ model: z.string().min(1).optional(),
+});
+
+function shouldRetry(error: ApiError) {
+ return error.statusCode === 429 || (error.statusCode >= 500 && error.statusCode < 600);
+}
+
+export async function GET(
+ _req: Request,
+ { params }: { params: Promise<{ conversationId: string }> },
+) {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ const { conversationId } = await params;
+ const conversation = await db.chatConversation.findUnique({ where: { id: conversationId } });
+ if (!conversation || (conversation as Record).userId !== session.user.id) {
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
+ }
+
+ const messages = await db.chatMessage.findMany({
+ where: { conversationId },
+ orderBy: { createdAt: "asc" },
+ take: 500,
+ });
+
+ return NextResponse.json({ data: messages });
+}
+
+export async function POST(
+ req: Request,
+ { params }: { params: Promise<{ conversationId: string }> },
+) {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ const { conversationId } = await params;
+ const conversation = await db.chatConversation.findUnique({ where: { id: conversationId } });
+ if (!conversation || (conversation as Record).userId !== session.user.id) {
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
+ }
+
+ let body: unknown;
+ try {
+ body = await req.json();
+ } catch {
+ return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
+ }
+
+ const parsed = messageSchema.safeParse(body);
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
+ }
+
+ const conv = conversation as Record;
+ const modelId = parsed.data.model || (conv.model as string) || "";
+ if (!modelId) {
+ return NextResponse.json({ error: "No model selected" }, { status: 400 });
+ }
+
+ if (modelId !== conv.model) {
+ await db.chatConversation.update({ where: { id: conversationId }, data: { model: modelId } });
+ }
+
+ // Save user message (store images as JSON array alongside text content)
+ const userMsgData: Record = {
+ conversationId,
+ role: "user",
+ content: parsed.data.content,
+ };
+ if (parsed.data.images?.length) {
+ userMsgData.images = parsed.data.images;
+ }
+ const userMsg = await db.chatMessage.create({ data: userMsgData });
+
+ // Get history for context
+ const history = await db.chatMessage.findMany({
+ where: { conversationId },
+ orderBy: { createdAt: "asc" },
+ take: 50,
+ });
+
+ // Resolve API key and rate limit
+ const [apiKeys, subscription] = await Promise.all([
+ db.userApiKey.findMany({
+ where: { userId: session.user.id },
+ orderBy: { createdAt: "asc" },
+ select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true },
+ }),
+ db.subscription.findUnique({
+ where: { userId: session.user.id },
+ include: { plan: true },
+ }),
+ ]);
+
+ type ApiKeyRow = {
+ id: string;
+ status?: string | null;
+ dailyRequestLimit?: number | null;
+ dailyTokenLimit?: number | null;
+ softCostLimitCents?: number | null;
+ };
+ const apiKey = (apiKeys as ApiKeyRow[]).find((k) => !k.status || k.status === "ACTIVE") ?? null;
+ if (!apiKey) {
+ return NextResponse.json({ error: "Create a user API key first in Dashboard > API Keys." }, { status: 400 });
+ }
+
+ const sub = subscription as { plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null;
+ if (!sub?.plan) {
+ return NextResponse.json({ error: "No active subscription plan found." }, { status: 403 });
+ }
+
+ const limits = {
+ dailyRequests: apiKey.dailyRequestLimit ?? sub.plan.dailyRequestLimit ?? null,
+ dailyTokens: apiKey.dailyTokenLimit ?? sub.plan.dailyTokenLimit ?? null,
+ dailyCostCents: apiKey.softCostLimitCents ?? null,
+ };
+ const rateLimit = await checkRateLimit(apiKey.id, limits);
+ if (!rateLimit.allowed) {
+ return rateLimitExceeded(rateLimit.reason!, rateLimit.retryAfter!);
+ }
+
+ const routes = await resolveModelRouteCandidates(modelId);
+ if (routes.length === 0) {
+ return modelNotFound(modelId).toResponse();
+ }
+
+ type HistoryRow = { role: string; content: string; images?: Array<{ type: "image_url"; image_url: { url: string; detail?: string } }> };
+ const chatMessages: UnifiedChatRequest["messages"] = (history as HistoryRow[]).map((m) => {
+ if (m.images?.length) {
+ return {
+ role: m.role as "user" | "assistant" | "system",
+ content: [
+ { type: "text" as const, text: m.content },
+ ...m.images.map((img) => ({
+ type: "image_url" as const,
+ image_url: { url: img.image_url.url, detail: img.image_url.detail as "auto" | "low" | "high" | undefined },
+ })),
+ ],
+ };
+ }
+ return {
+ role: m.role as "user" | "assistant" | "system",
+ content: m.content,
+ };
+ });
+
+ const unifiedReq: UnifiedChatRequest = {
+ model: modelId,
+ messages: chatMessages,
+ stream: true,
+ };
+
+ const startedAt = Date.now();
+ let lastApiError: ApiError | null = null;
+
+ for (const route of routes) {
+ try {
+ const providerStream = await route.adapter.chatCompletionStream(unifiedReq, route.ctx);
+
+ // Build a transform that:
+ // 1. Passes SSE chunks to the client
+ // 2. Accumulates the full text and usage for DB persistence after stream ends
+ const encoder = new TextEncoder();
+ const decoder = new TextDecoder();
+ let fullText = "";
+ let tokensIn = 0;
+ let tokensOut = 0;
+
+ const outputStream = new ReadableStream({
+ async start(controller) {
+ // Send the userMessage id as the first custom SSE event
+ controller.enqueue(
+ encoder.encode(`event: meta\ndata: ${JSON.stringify({ userMessageId: userMsg.id, providerId: route.providerId })}\n\n`),
+ );
+
+ const reader = providerStream.getReader();
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ // Forward raw SSE chunk to client
+ controller.enqueue(value);
+
+ // Parse to accumulate text and usage
+ const text = decoder.decode(value, { stream: true });
+ for (const line of text.split("\n")) {
+ if (!line.startsWith("data: ") || line === "data: [DONE]") continue;
+ try {
+ const json = JSON.parse(line.slice(6));
+ const delta = json.choices?.[0]?.delta;
+ if (delta?.content) fullText += delta.content;
+ if (json.usage) {
+ tokensIn = json.usage.prompt_tokens ?? tokensIn;
+ tokensOut = json.usage.completion_tokens ?? tokensOut;
+ }
+ } catch {
+ // skip
+ }
+ }
+ }
+ } catch (err) {
+ logger.error(err, "Stream read error");
+ }
+
+ // Stream done — persist assistant message and log usage
+ const latencyMs = Date.now() - startedAt;
+
+ const assistantMsg = await db.chatMessage.create({
+ data: {
+ conversationId,
+ role: "assistant",
+ content: fullText,
+ model: modelId,
+ providerId: route.providerId,
+ tokensIn,
+ tokensOut,
+ },
+ });
+
+ // Auto-title on first exchange
+ if ((history as unknown[]).length <= 1) {
+ const autoTitle = parsed.data.content.slice(0, 60) + (parsed.data.content.length > 60 ? "..." : "");
+ await db.chatConversation.update({ where: { id: conversationId }, data: { title: autoTitle } });
+ }
+ await db.chatConversation.update({ where: { id: conversationId }, data: {} });
+
+ // Send final meta event with saved message info
+ controller.enqueue(
+ encoder.encode(
+ `event: done\ndata: ${JSON.stringify({ assistantMessageId: assistantMsg.id, tokensIn, tokensOut })}\n\n`,
+ ),
+ );
+ controller.close();
+
+ logUsage({
+ userId: session.user.id,
+ userApiKeyId: apiKey.id,
+ providerId: route.providerId,
+ providerApiKeyId: route.providerApiKeyId,
+ logicalModelId: route.logicalModelId,
+ providerModelId: route.providerModelId,
+ statusCode: 200,
+ tokensIn,
+ tokensOut,
+ latencyMs,
+ streamed: true,
+ promptText: chatMessages.map((m) => {
+ const text = typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content.filter((p) => p.type === "text").map((p) => (p as { text: string }).text).join("") : "";
+ return `${m.role}: ${text}`;
+ }).join("\n"),
+ responseText: fullText,
+ loggingMode: "preview",
+ }).catch((err) => logger.error(err, "Failed to log chat streaming usage"));
+ },
+ });
+
+ return new Response(outputStream, { status: 200, headers: sseHeaders() });
+ } catch (error) {
+ if (error instanceof ApiError) {
+ lastApiError = error;
+ if (shouldRetry(error)) continue;
+ return error.toResponse();
+ }
+ logger.error(error, "Unhandled chat error");
+ }
+ }
+
+ if (lastApiError) return lastApiError.toResponse();
+ return internalError().toResponse();
+}
diff --git a/src/app/api/chat/conversations/[conversationId]/route.ts b/src/app/api/chat/conversations/[conversationId]/route.ts
new file mode 100644
index 0000000..fc4db78
--- /dev/null
+++ b/src/app/api/chat/conversations/[conversationId]/route.ts
@@ -0,0 +1,50 @@
+import { NextResponse } from "next/server";
+import { getSession } from "@/lib/auth-helpers";
+import { db } from "@/lib/db";
+
+export async function PATCH(
+ req: Request,
+ { params }: { params: Promise<{ conversationId: string }> },
+) {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ const { conversationId } = await params;
+ const conversation = await db.chatConversation.findUnique({ where: { id: conversationId } });
+ if (!conversation || (conversation as Record).userId !== session.user.id) {
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
+ }
+
+ let body: Record = {};
+ try {
+ body = (await req.json()) as Record;
+ } catch {
+ return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
+ }
+
+ const data: Record = {};
+ if (typeof body.title === "string") data.title = body.title.trim();
+ if (typeof body.model === "string") data.model = body.model.trim();
+
+ const updated = await db.chatConversation.update({ where: { id: conversationId }, data });
+ return NextResponse.json({ data: updated });
+}
+
+export async function DELETE(
+ _req: Request,
+ { params }: { params: Promise<{ conversationId: string }> },
+) {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ const { conversationId } = await params;
+ const conversation = await db.chatConversation.findUnique({ where: { id: conversationId } });
+ if (!conversation || (conversation as Record).userId !== session.user.id) {
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
+ }
+
+ await db.chatMessage.deleteMany({ where: { conversationId } });
+ await db.chatConversation.delete({ where: { id: conversationId } });
+
+ return NextResponse.json({ ok: true });
+}
diff --git a/src/app/api/chat/conversations/[conversationId]/save/route.ts b/src/app/api/chat/conversations/[conversationId]/save/route.ts
new file mode 100644
index 0000000..0d9e670
--- /dev/null
+++ b/src/app/api/chat/conversations/[conversationId]/save/route.ts
@@ -0,0 +1,84 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { getSession } from "@/lib/auth-helpers";
+import { db } from "@/lib/db";
+
+/**
+ * Save messages to a conversation without triggering LLM generation.
+ * Used by image/audio generation flows where the generation happens
+ * via dedicated endpoints but messages still need to be persisted.
+ */
+
+const messageEntrySchema = z.object({
+ role: z.enum(["user", "assistant"]),
+ content: z.string(),
+ model: z.string().optional(),
+ providerId: z.string().optional(),
+ images: z.array(z.unknown()).optional(),
+ generatedImages: z.array(z.unknown()).optional(),
+ audioB64: z.string().optional(),
+ audioContentType: z.string().optional(),
+});
+
+const schema = z.object({
+ messages: z.array(messageEntrySchema).min(1).max(10),
+});
+
+export async function POST(
+ req: Request,
+ { params }: { params: Promise<{ conversationId: string }> },
+) {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ const { conversationId } = await params;
+ const conversation = await db.chatConversation.findUnique({ where: { id: conversationId } });
+ if (!conversation || (conversation as Record).userId !== session.user.id) {
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
+ }
+
+ let body: unknown;
+ try {
+ body = await req.json();
+ } catch {
+ return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
+ }
+
+ const parsed = schema.safeParse(body);
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
+ }
+
+ const saved = [];
+ for (const msg of parsed.data.messages) {
+ const data: Record = {
+ conversationId,
+ role: msg.role,
+ content: msg.content,
+ };
+ if (msg.model) data.model = msg.model;
+ if (msg.providerId) data.providerId = msg.providerId;
+ if (msg.images) data.images = msg.images;
+ if (msg.generatedImages) data.generatedImages = msg.generatedImages;
+ if (msg.audioB64) data.audioB64 = msg.audioB64;
+ if (msg.audioContentType) data.audioContentType = msg.audioContentType;
+
+ const created = await db.chatMessage.create({ data });
+ saved.push(created);
+ }
+
+ // Auto-title on first messages
+ const existingCount = await db.chatMessage.count({ where: { conversationId } });
+ if (existingCount <= parsed.data.messages.length + 1) {
+ const userMsg = parsed.data.messages.find((m) => m.role === "user");
+ if (userMsg) {
+ const autoTitle = userMsg.content.slice(0, 60) + (userMsg.content.length > 60 ? "..." : "");
+ await db.chatConversation.update({ where: { id: conversationId }, data: { title: autoTitle } });
+ }
+ }
+
+ // Touch updatedAt
+ await db.chatConversation.update({ where: { id: conversationId }, data: {} });
+
+ return NextResponse.json({ data: saved });
+}
diff --git a/src/app/api/chat/conversations/route.ts b/src/app/api/chat/conversations/route.ts
new file mode 100644
index 0000000..ab6b4fe
--- /dev/null
+++ b/src/app/api/chat/conversations/route.ts
@@ -0,0 +1,41 @@
+import { NextResponse } from "next/server";
+import { getSession } from "@/lib/auth-helpers";
+import { db } from "@/lib/db";
+
+export async function GET() {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ const conversations = await db.chatConversation.findMany({
+ where: { userId: session.user.id },
+ orderBy: { updatedAt: "desc" },
+ take: 100,
+ });
+
+ return NextResponse.json({ data: conversations });
+}
+
+export async function POST(req: Request) {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ let body: Record = {};
+ try {
+ body = (await req.json()) as Record;
+ } catch {
+ // empty body is fine
+ }
+
+ const title = typeof body.title === "string" && body.title.trim() ? body.title.trim() : "New chat";
+ const model = typeof body.model === "string" && body.model.trim() ? body.model.trim() : "";
+
+ const conversation = await db.chatConversation.create({
+ data: {
+ userId: session.user.id,
+ title,
+ model,
+ },
+ });
+
+ return NextResponse.json({ data: conversation }, { status: 201 });
+}
diff --git a/src/app/api/chat/generate-audio/route.ts b/src/app/api/chat/generate-audio/route.ts
new file mode 100644
index 0000000..1bcee92
--- /dev/null
+++ b/src/app/api/chat/generate-audio/route.ts
@@ -0,0 +1,124 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { getSession } from "@/lib/auth-helpers";
+import { db } from "@/lib/db";
+import { logger } from "@/lib/logger";
+import { checkRateLimit } from "@/server/services/rate-limiter";
+import { resolveModelRouteCandidates } from "@/server/services/model-router";
+import { logUsage } from "@/server/services/usage-logger";
+import { ApiError, internalError, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
+
+const schema = z.object({
+ model: z.string().min(1),
+ input: z.string().trim().min(1).max(4096),
+ voice: z.enum(["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"]).optional().default("alloy"),
+ speed: z.number().min(0.25).max(4).optional(),
+});
+
+export async function POST(req: Request) {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ let body: unknown;
+ try {
+ body = await req.json();
+ } catch {
+ return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
+ }
+
+ const parsed = schema.safeParse(body);
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
+ }
+
+ const payload = parsed.data;
+
+ const [apiKeys, subscription] = await Promise.all([
+ db.userApiKey.findMany({
+ where: { userId: session.user.id },
+ orderBy: { createdAt: "asc" },
+ select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true },
+ }),
+ db.subscription.findUnique({
+ where: { userId: session.user.id },
+ include: { plan: true },
+ }),
+ ]);
+
+ type ApiKeyRow = { id: string; status?: string | null; dailyRequestLimit?: number | null; dailyTokenLimit?: number | null; softCostLimitCents?: number | null };
+ const apiKey = (apiKeys as ApiKeyRow[]).find((k) => !k.status || k.status === "ACTIVE") ?? null;
+ if (!apiKey) return NextResponse.json({ error: "Create a user API key first." }, { status: 400 });
+
+ const sub = subscription as { plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null;
+ if (!sub?.plan) return NextResponse.json({ error: "No active plan." }, { status: 403 });
+
+ const limits = {
+ dailyRequests: apiKey.dailyRequestLimit ?? sub.plan.dailyRequestLimit ?? null,
+ dailyTokens: apiKey.dailyTokenLimit ?? sub.plan.dailyTokenLimit ?? null,
+ dailyCostCents: apiKey.softCostLimitCents ?? null,
+ };
+ const rateLimit = await checkRateLimit(apiKey.id, limits);
+ if (!rateLimit.allowed) return rateLimitExceeded(rateLimit.reason!, rateLimit.retryAfter!);
+
+ const routes = await resolveModelRouteCandidates(payload.model);
+ if (routes.length === 0) return modelNotFound(payload.model).toResponse();
+
+ const startedAt = Date.now();
+ let lastApiError: ApiError | null = null;
+
+ for (const route of routes) {
+ if (!route.adapter.audioSpeech) continue;
+
+ try {
+ const audioBuffer = await route.adapter.audioSpeech(
+ {
+ model: payload.model,
+ input: payload.input,
+ voice: payload.voice,
+ response_format: "mp3",
+ speed: payload.speed,
+ },
+ route.ctx,
+ );
+
+ const latencyMs = Date.now() - startedAt;
+
+ logUsage({
+ userId: session.user.id,
+ userApiKeyId: apiKey.id,
+ providerId: route.providerId,
+ providerApiKeyId: route.providerApiKeyId,
+ logicalModelId: route.logicalModelId,
+ providerModelId: route.providerModelId,
+ statusCode: 200,
+ tokensIn: 0,
+ tokensOut: 0,
+ latencyMs,
+ streamed: false,
+ promptText: payload.input,
+ loggingMode: "preview",
+ }).catch((err) => logger.error(err, "Failed to log audio speech usage"));
+
+ // Return audio as base64
+ const b64 = Buffer.from(audioBuffer).toString("base64");
+ return NextResponse.json({
+ providerId: route.providerId,
+ model: payload.model,
+ audio: {
+ b64: b64,
+ contentType: "audio/mpeg",
+ },
+ });
+ } catch (error) {
+ if (error instanceof ApiError) {
+ lastApiError = error;
+ if (error.statusCode === 429 || error.statusCode >= 500) continue;
+ return error.toResponse();
+ }
+ logger.error(error, "Unhandled audio speech error");
+ }
+ }
+
+ if (lastApiError) return lastApiError.toResponse();
+ return internalError().toResponse();
+}
diff --git a/src/app/api/chat/generate-image/route.ts b/src/app/api/chat/generate-image/route.ts
new file mode 100644
index 0000000..13bfe8c
--- /dev/null
+++ b/src/app/api/chat/generate-image/route.ts
@@ -0,0 +1,126 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { getSession } from "@/lib/auth-helpers";
+import { db } from "@/lib/db";
+import { logger } from "@/lib/logger";
+import { checkRateLimit } from "@/server/services/rate-limiter";
+import { resolveModelRouteCandidates } from "@/server/services/model-router";
+import { logUsage } from "@/server/services/usage-logger";
+import { ApiError, internalError, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
+
+const schema = z.object({
+ model: z.string().min(1),
+ prompt: z.string().trim().min(1).max(4000),
+ size: z.enum(["1024x1024", "1024x1792", "1792x1024", "256x256", "512x512"]).optional(),
+ quality: z.enum(["auto", "high", "medium", "low", "standard", "hd"]).optional(),
+ style: z.enum(["vivid", "natural"]).optional(),
+ n: z.number().int().min(1).max(4).optional(),
+});
+
+export async function POST(req: Request) {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ let body: unknown;
+ try {
+ body = await req.json();
+ } catch {
+ return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
+ }
+
+ const parsed = schema.safeParse(body);
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
+ }
+
+ const payload = parsed.data;
+
+ const [apiKeys, subscription] = await Promise.all([
+ db.userApiKey.findMany({
+ where: { userId: session.user.id },
+ orderBy: { createdAt: "asc" },
+ select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true },
+ }),
+ db.subscription.findUnique({
+ where: { userId: session.user.id },
+ include: { plan: true },
+ }),
+ ]);
+
+ type ApiKeyRow = { id: string; status?: string | null; dailyRequestLimit?: number | null; dailyTokenLimit?: number | null; softCostLimitCents?: number | null };
+ const apiKey = (apiKeys as ApiKeyRow[]).find((k) => !k.status || k.status === "ACTIVE") ?? null;
+ if (!apiKey) return NextResponse.json({ error: "Create a user API key first." }, { status: 400 });
+
+ const sub = subscription as { plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null;
+ if (!sub?.plan) return NextResponse.json({ error: "No active plan." }, { status: 403 });
+
+ const limits = {
+ dailyRequests: apiKey.dailyRequestLimit ?? sub.plan.dailyRequestLimit ?? null,
+ dailyTokens: apiKey.dailyTokenLimit ?? sub.plan.dailyTokenLimit ?? null,
+ dailyCostCents: apiKey.softCostLimitCents ?? null,
+ };
+ const rateLimit = await checkRateLimit(apiKey.id, limits);
+ if (!rateLimit.allowed) return rateLimitExceeded(rateLimit.reason!, rateLimit.retryAfter!);
+
+ const routes = await resolveModelRouteCandidates(payload.model);
+ if (routes.length === 0) return modelNotFound(payload.model).toResponse();
+
+ const startedAt = Date.now();
+ let lastApiError: ApiError | null = null;
+
+ for (const route of routes) {
+ if (!route.adapter.imageGeneration) continue;
+
+ try {
+ const result = await route.adapter.imageGeneration(
+ {
+ prompt: payload.prompt,
+ model: payload.model,
+ n: payload.n,
+ size: payload.size,
+ quality: payload.quality,
+ style: payload.style,
+ },
+ route.ctx,
+ );
+
+ const latencyMs = Date.now() - startedAt;
+
+ logUsage({
+ userId: session.user.id,
+ userApiKeyId: apiKey.id,
+ providerId: route.providerId,
+ providerApiKeyId: route.providerApiKeyId,
+ logicalModelId: route.logicalModelId,
+ providerModelId: route.providerModelId,
+ statusCode: 200,
+ tokensIn: 0,
+ tokensOut: 0,
+ latencyMs,
+ streamed: false,
+ promptText: payload.prompt,
+ loggingMode: "preview",
+ }).catch((err) => logger.error(err, "Failed to log image generation usage"));
+
+ return NextResponse.json({
+ providerId: route.providerId,
+ model: payload.model,
+ images: result.data.map((d) => ({
+ b64_json: d.b64_json,
+ url: d.url,
+ revised_prompt: d.revised_prompt,
+ })),
+ });
+ } catch (error) {
+ if (error instanceof ApiError) {
+ lastApiError = error;
+ if (error.statusCode === 429 || error.statusCode >= 500) continue;
+ return error.toResponse();
+ }
+ logger.error(error, "Unhandled image generation error");
+ }
+ }
+
+ if (lastApiError) return lastApiError.toResponse();
+ return internalError().toResponse();
+}
diff --git a/src/app/api/chat/incognito/route.ts b/src/app/api/chat/incognito/route.ts
new file mode 100644
index 0000000..7b7fe4e
--- /dev/null
+++ b/src/app/api/chat/incognito/route.ts
@@ -0,0 +1,165 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { getSession } from "@/lib/auth-helpers";
+import { db } from "@/lib/db";
+import { logger } from "@/lib/logger";
+import { checkRateLimit } from "@/server/services/rate-limiter";
+import { resolveModelRouteCandidates } from "@/server/services/model-router";
+import { ApiError, internalError, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
+import { sseHeaders } from "@/server/services/streaming";
+import type { UnifiedChatRequest } from "@/types/unified-request";
+
+const imagePartSchema = z.object({
+ type: z.literal("image_url"),
+ image_url: z.object({
+ url: z.string().min(1),
+ detail: z.enum(["auto", "low", "high"]).optional(),
+ }),
+});
+
+const schema = z.object({
+ model: z.string().min(1),
+ message: z.string().trim().min(1),
+ images: z.array(imagePartSchema).max(10).optional(),
+ history: z
+ .array(z.object({
+ role: z.enum(["user", "assistant"]),
+ content: z.string(),
+ images: z.array(imagePartSchema).optional(),
+ }))
+ .max(50)
+ .optional(),
+});
+
+function shouldRetry(error: ApiError) {
+ return error.statusCode === 429 || (error.statusCode >= 500 && error.statusCode < 600);
+}
+
+export async function POST(req: Request) {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ let body: unknown;
+ try {
+ body = await req.json();
+ } catch {
+ return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
+ }
+
+ const parsed = schema.safeParse(body);
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
+ }
+
+ const payload = parsed.data;
+
+ const [apiKeys, subscription] = await Promise.all([
+ db.userApiKey.findMany({
+ where: { userId: session.user.id },
+ orderBy: { createdAt: "asc" },
+ select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true },
+ }),
+ db.subscription.findUnique({
+ where: { userId: session.user.id },
+ include: { plan: true },
+ }),
+ ]);
+
+ type ApiKeyRow = { id: string; status?: string | null; dailyRequestLimit?: number | null; dailyTokenLimit?: number | null; softCostLimitCents?: number | null };
+ const apiKey = (apiKeys as ApiKeyRow[]).find((k) => !k.status || k.status === "ACTIVE") ?? null;
+ if (!apiKey) return NextResponse.json({ error: "Create a user API key first." }, { status: 400 });
+
+ const sub = subscription as { plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null;
+ if (!sub?.plan) return NextResponse.json({ error: "No active plan." }, { status: 403 });
+
+ const limits = {
+ dailyRequests: apiKey.dailyRequestLimit ?? sub.plan.dailyRequestLimit ?? null,
+ dailyTokens: apiKey.dailyTokenLimit ?? sub.plan.dailyTokenLimit ?? null,
+ dailyCostCents: apiKey.softCostLimitCents ?? null,
+ };
+ const rateLimit = await checkRateLimit(apiKey.id, limits);
+ if (!rateLimit.allowed) return rateLimitExceeded(rateLimit.reason!, rateLimit.retryAfter!);
+
+ const routes = await resolveModelRouteCandidates(payload.model);
+ if (routes.length === 0) return modelNotFound(payload.model).toResponse();
+
+ const messages: UnifiedChatRequest["messages"] = [];
+ for (const m of payload.history ?? []) {
+ if (m.images?.length) {
+ messages.push({
+ role: m.role,
+ content: [
+ { type: "text", text: m.content },
+ ...m.images.map((img) => ({
+ type: "image_url" as const,
+ image_url: { url: img.image_url.url, detail: img.image_url.detail as "auto" | "low" | "high" | undefined },
+ })),
+ ],
+ });
+ } else {
+ messages.push({ role: m.role, content: m.content });
+ }
+ }
+ if (payload.images?.length) {
+ messages.push({
+ role: "user",
+ content: [
+ { type: "text", text: payload.message },
+ ...payload.images.map((img) => ({
+ type: "image_url" as const,
+ image_url: { url: img.image_url.url, detail: img.image_url.detail as "auto" | "low" | "high" | undefined },
+ })),
+ ],
+ });
+ } else {
+ messages.push({ role: "user", content: payload.message });
+ }
+
+ const unifiedReq: UnifiedChatRequest = { model: payload.model, messages, stream: true };
+ let lastApiError: ApiError | null = null;
+
+ for (const route of routes) {
+ try {
+ const providerStream = await route.adapter.chatCompletionStream(unifiedReq, route.ctx);
+
+ const encoder = new TextEncoder();
+ const decoder = new TextDecoder();
+
+ const outputStream = new ReadableStream({
+ async start(controller) {
+ // Send provider info as first event
+ controller.enqueue(
+ encoder.encode(`event: meta\ndata: ${JSON.stringify({ providerId: route.providerId })}\n\n`),
+ );
+
+ const reader = providerStream.getReader();
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ controller.enqueue(value);
+ }
+ } catch (err) {
+ logger.error(err, "Incognito stream read error");
+ }
+
+ // No DB writes or usage logging in incognito
+ controller.enqueue(encoder.encode(`event: done\ndata: {}\n\n`));
+ controller.close();
+ },
+ });
+
+ return new Response(outputStream, { status: 200, headers: sseHeaders() });
+ } catch (error) {
+ if (error instanceof ApiError) {
+ lastApiError = error;
+ if (shouldRetry(error)) continue;
+ return error.toResponse();
+ }
+ logger.error(error, "Unhandled incognito stream error");
+ }
+ }
+
+ if (lastApiError) return lastApiError.toResponse();
+ return internalError().toResponse();
+}
diff --git a/src/app/api/chat/preferences/route.ts b/src/app/api/chat/preferences/route.ts
new file mode 100644
index 0000000..779b897
--- /dev/null
+++ b/src/app/api/chat/preferences/route.ts
@@ -0,0 +1,58 @@
+import { NextResponse } from "next/server";
+import { getSession } from "@/lib/auth-helpers";
+import { db } from "@/lib/db";
+
+interface Preferences {
+ defaultModel?: string;
+ favouriteModels?: string[];
+}
+
+export async function GET() {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ const pref = await db.userPreference.findUnique({ where: { userId: session.user.id } });
+ const data: Preferences = pref
+ ? {
+ defaultModel: (pref as Record).defaultModel as string | undefined,
+ favouriteModels: (pref as Record).favouriteModels as string[] | undefined,
+ }
+ : { defaultModel: "", favouriteModels: [] };
+
+ return NextResponse.json({ data });
+}
+
+export async function PUT(req: Request) {
+ const session = await getSession();
+ if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+
+ let body: Record;
+ try {
+ body = (await req.json()) as Record;
+ } catch {
+ return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
+ }
+
+ const existing = await db.userPreference.findUnique({ where: { userId: session.user.id } });
+
+ const data: Record = {};
+ if (typeof body.defaultModel === "string") data.defaultModel = body.defaultModel;
+ if (Array.isArray(body.favouriteModels)) {
+ data.favouriteModels = (body.favouriteModels as unknown[]).filter(
+ (m): m is string => typeof m === "string",
+ );
+ }
+
+ if (existing) {
+ const updated = await db.userPreference.update({
+ where: { id: (existing as Record).id as string },
+ data,
+ });
+ return NextResponse.json({ data: updated });
+ }
+
+ const created = await db.userPreference.create({
+ data: { userId: session.user.id, ...data },
+ });
+ return NextResponse.json({ data: created }, { status: 201 });
+}
diff --git a/src/app/api/dashboard/playground/route.ts b/src/app/api/dashboard/playground/route.ts
index b63e6bc..ddc7f0a 100644
--- a/src/app/api/dashboard/playground/route.ts
+++ b/src/app/api/dashboard/playground/route.ts
@@ -34,21 +34,43 @@ export async function GET() {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ // Get providers that have at least one ACTIVE key
+ const providersWithKeys = await db.providerApiKey.findMany({
+ where: { status: "ACTIVE" },
+ select: { providerId: true },
+ });
+ const activeProviderIds = new Set(
+ (providersWithKeys as Array<{ providerId: string }>).map((k) => k.providerId),
+ );
+
+ // Also check provider is enabled
+ const enabledProviders = await db.provider.findMany({
+ where: { enabled: true },
+ select: { id: true },
+ });
+ const enabledProviderIds = new Set(
+ (enabledProviders as Array<{ id: string }>).map((p) => p.id),
+ );
+
const mappings = (await db.modelMapping.findMany({
where: { enabled: true },
- select: { logicalModelId: true, providerId: true, priority: true },
+ select: { logicalModelId: true, providerId: true, priority: true, modelType: true },
orderBy: [{ logicalModelId: "asc" }, { priority: "asc" }],
- })) as Array<{ logicalModelId: string; providerId: string }>;
+ })) as Array<{ logicalModelId: string; providerId: string; modelType?: string }>;
- const byModel = new Map();
+ const byModel = new Map();
for (const row of mappings) {
- if (!byModel.has(row.logicalModelId)) {
- byModel.set(row.logicalModelId, row.providerId);
+ if (
+ !byModel.has(row.logicalModelId) &&
+ activeProviderIds.has(row.providerId) &&
+ enabledProviderIds.has(row.providerId)
+ ) {
+ byModel.set(row.logicalModelId, { providerId: row.providerId, modelType: row.modelType ?? "chat" });
}
}
return NextResponse.json({
- data: [...byModel.entries()].map(([id, providerId]) => ({ id, providerId })),
+ data: [...byModel.entries()].map(([id, info]) => ({ id, providerId: info.providerId, modelType: info.modelType })),
});
}
@@ -140,7 +162,8 @@ export async function POST(req: Request) {
try {
const result = await route.adapter.chatCompletion(unifiedReq, route.ctx);
const latencyMs = Date.now() - startedAt;
- const assistantText = result.choices[0]?.message.content ?? "";
+ const rawContent = result.choices[0]?.message.content;
+ const assistantText = typeof rawContent === "string" ? rawContent : "";
logUsage({
userId: session.user.id,
@@ -154,7 +177,7 @@ export async function POST(req: Request) {
tokensOut: result.usage?.completion_tokens ?? 0,
latencyMs,
streamed: false,
- promptText: messages.map((m) => `${m.role}: ${m.content ?? ""}`).join("\n"),
+ promptText: messages.map((m) => `${m.role}: ${typeof m.content === "string" ? m.content : ""}`).join("\n"),
responseText: assistantText,
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log playground usage"));
@@ -183,7 +206,7 @@ export async function POST(req: Request) {
tokensOut: 0,
latencyMs,
streamed: false,
- promptText: messages.map((m) => `${m.role}: ${m.content ?? ""}`).join("\n"),
+ promptText: messages.map((m) => `${m.role}: ${typeof m.content === "string" ? m.content : ""}`).join("\n"),
loggingMode: "hash_only",
}).catch(() => {});
diff --git a/src/app/chat/layout.tsx b/src/app/chat/layout.tsx
new file mode 100644
index 0000000..a2daa0b
--- /dev/null
+++ b/src/app/chat/layout.tsx
@@ -0,0 +1,9 @@
+import { redirect } from "next/navigation";
+import { getSession } from "@/lib/auth-helpers";
+
+export default async function ChatLayout({ children }: { children: React.ReactNode }) {
+ const session = await getSession();
+ if (!session) redirect("/login");
+
+ return <>{children}>;
+}
diff --git a/src/app/chat/page.tsx b/src/app/chat/page.tsx
new file mode 100644
index 0000000..d102489
--- /dev/null
+++ b/src/app/chat/page.tsx
@@ -0,0 +1,1511 @@
+"use client";
+
+import { FormEvent, useCallback, useEffect, useRef, useState } from "react";
+import Link from "next/link";
+import { toast } from "sonner";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import {
+ ArrowUp,
+ Check,
+ ChevronDown,
+ Download,
+ EyeOff,
+ Image as ImageIcon,
+ LayoutDashboard,
+ Mic,
+ Palette,
+ Pause,
+ Play,
+ MessageSquare,
+ Plus,
+ Sparkles,
+ Square,
+ Star,
+ Trash2,
+ X,
+} from "lucide-react";
+import { cn } from "@/lib/utils";
+
+// ── Types ────────────────────────────────────────────────
+
+type ModelType = "chat" | "image" | "audio";
+
+interface ModelOption {
+ id: string;
+ providerId: string;
+ modelType: ModelType;
+}
+
+interface ImagePart {
+ type: "image_url";
+ image_url: { url: string; detail?: string };
+}
+
+interface ChatMessage {
+ id?: string;
+ role: "user" | "assistant";
+ content: string;
+ images?: ImagePart[];
+ generatedImages?: Array<{ b64_json?: string; url?: string; revised_prompt?: string }>;
+ audioB64?: string;
+ audioContentType?: string;
+ model?: string;
+ providerId?: string;
+ tokensIn?: number;
+ tokensOut?: number;
+ createdAt?: string;
+}
+
+interface Conversation {
+ id: string;
+ title: string;
+ model: string;
+ updatedAt: string;
+}
+
+// ── SSE parser helper ────────────────────────────────────
+
+function parseSSELines(buffer: string): { events: Array<{ event?: string; data: string }>; remaining: string } {
+ const events: Array<{ event?: string; data: string }> = [];
+ const lines = buffer.split("\n");
+ let currentEvent: string | undefined;
+ let currentData: string[] = [];
+ let lastProcessed = 0;
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+
+ if (line.startsWith("event: ")) {
+ currentEvent = line.slice(7).trim();
+ } else if (line.startsWith("data: ")) {
+ currentData.push(line.slice(6));
+ } else if (line === "" && currentData.length > 0) {
+ events.push({ event: currentEvent, data: currentData.join("\n") });
+ currentEvent = undefined;
+ currentData = [];
+ lastProcessed = i + 1;
+ } else if (line === "") {
+ lastProcessed = i + 1;
+ }
+ }
+
+ // Return unprocessed trailing text as remaining
+ const remaining = lines.slice(lastProcessed).join("\n");
+ return { events, remaining };
+}
+
+// ── Model menu item ──────────────────────────────────────
+
+function ModelMenuItem({
+ m,
+ model,
+ isDefault,
+ isFavourite,
+ onSelect,
+ onToggleFav,
+ onSetDefault,
+}: {
+ m: ModelOption;
+ model: string;
+ isDefault: boolean;
+ isFavourite: boolean;
+ onSelect: () => void;
+ onToggleFav: () => void;
+ onSetDefault: () => void;
+}) {
+ return (
+
+
+ {isDefault && }
+ {m.id}
+ {m.modelType === "image" && (
+ IMG
+ )}
+ {m.modelType === "audio" && (
+ TTS
+ )}
+
+ {m.providerId}
+ { e.stopPropagation(); onSetDefault(); }}
+ title={isDefault ? "Remove as default" : "Set as default"}
+ className={cn(
+ "shrink-0 rounded p-1 transition-colors",
+ isDefault
+ ? "text-emerald-400 hover:text-emerald-300"
+ : "text-muted-foreground/30 hover:text-emerald-400 md:opacity-0 md:group-hover:opacity-100",
+ )}
+ >
+
+
+ { e.stopPropagation(); onToggleFav(); }}
+ title={isFavourite ? "Remove from favourites" : "Add to favourites"}
+ className={cn(
+ "shrink-0 rounded p-1 transition-colors",
+ isFavourite
+ ? "text-amber-400 hover:text-amber-300"
+ : "text-muted-foreground/30 hover:text-amber-400 md:opacity-0 md:group-hover:opacity-100",
+ )}
+ >
+
+
+
+ );
+}
+
+// ── Custom audio player with waveform ────────────────────
+
+function AudioPlayer({ src }: { src: string }) {
+ const audioRef = useRef(null);
+ const canvasRef = useRef(null);
+ const animFrameRef = useRef(0);
+ const [playing, setPlaying] = useState(false);
+ const [progress, setProgress] = useState(0);
+ const [duration, setDuration] = useState(0);
+ const [bars, setBars] = useState([]);
+ const barsCount = 48;
+
+ // Generate deterministic waveform bars from audio data
+ useEffect(() => {
+ // Generate pseudo-random bars from src hash
+ const seed = src.length;
+ const generated: number[] = [];
+ for (let i = 0; i < barsCount; i++) {
+ const sin1 = Math.sin(i * 0.4 + seed * 0.01) * 0.3;
+ const sin2 = Math.sin(i * 0.15 + seed * 0.007) * 0.25;
+ const sin3 = Math.sin(i * 0.8 + seed * 0.003) * 0.15;
+ const base = 0.15 + Math.abs(sin1 + sin2 + sin3);
+ // Envelope: taper at edges
+ const envelope = Math.sin((i / (barsCount - 1)) * Math.PI);
+ generated.push(Math.max(0.08, Math.min(1, base * (0.4 + envelope * 0.6))));
+ }
+ setBars(generated);
+ }, [src]);
+
+ // Decode actual audio waveform for more accurate visualization
+ useEffect(() => {
+ async function decode() {
+ try {
+ const response = await fetch(src);
+ const arrayBuffer = await response.arrayBuffer();
+ const audioCtx = new AudioContext();
+ const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
+ const channelData = audioBuffer.getChannelData(0);
+ const samplesPerBar = Math.floor(channelData.length / barsCount);
+ const decoded: number[] = [];
+ for (let i = 0; i < barsCount; i++) {
+ let sum = 0;
+ const start = i * samplesPerBar;
+ for (let j = start; j < start + samplesPerBar && j < channelData.length; j++) {
+ sum += Math.abs(channelData[j]);
+ }
+ decoded.push(sum / samplesPerBar);
+ }
+ // Normalize
+ const max = Math.max(...decoded, 0.001);
+ setBars(decoded.map((v) => Math.max(0.08, v / max)));
+ audioCtx.close();
+ } catch {
+ // Keep the generated bars as fallback
+ }
+ }
+ decode();
+ }, [src]);
+
+ useEffect(() => {
+ const audio = audioRef.current;
+ if (!audio) return;
+
+ const onTime = () => {
+ if (audio.duration) {
+ setProgress(audio.currentTime / audio.duration);
+ }
+ };
+ const onMeta = () => setDuration(audio.duration || 0);
+ const onEnd = () => { setPlaying(false); setProgress(0); };
+
+ audio.addEventListener("timeupdate", onTime);
+ audio.addEventListener("loadedmetadata", onMeta);
+ audio.addEventListener("ended", onEnd);
+ return () => {
+ audio.removeEventListener("timeupdate", onTime);
+ audio.removeEventListener("loadedmetadata", onMeta);
+ audio.removeEventListener("ended", onEnd);
+ };
+ }, []);
+
+ // Draw waveform
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || !bars.length) return;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+
+ function draw() {
+ const dpr = window.devicePixelRatio || 1;
+ const rect = canvas!.getBoundingClientRect();
+ canvas!.width = rect.width * dpr;
+ canvas!.height = rect.height * dpr;
+ ctx!.scale(dpr, dpr);
+
+ const w = rect.width;
+ const h = rect.height;
+ ctx!.clearRect(0, 0, w, h);
+
+ const barWidth = Math.max(2, (w / bars.length) * 0.6);
+ const gap = (w - barWidth * bars.length) / (bars.length - 1 || 1);
+ const progressIndex = progress * bars.length;
+
+ for (let i = 0; i < bars.length; i++) {
+ const x = i * (barWidth + gap);
+ const barH = Math.max(3, bars[i] * (h - 4));
+ const y = (h - barH) / 2;
+ const radius = Math.min(barWidth / 2, 2);
+
+ if (i < progressIndex) {
+ // Played — emerald gradient
+ const grad = ctx!.createLinearGradient(x, y, x, y + barH);
+ grad.addColorStop(0, "rgba(52, 211, 153, 0.95)");
+ grad.addColorStop(1, "rgba(16, 185, 129, 0.7)");
+ ctx!.fillStyle = grad;
+ } else {
+ // Unplayed — dim
+ ctx!.fillStyle = "rgba(255, 255, 255, 0.12)";
+ }
+
+ // Rounded rect
+ ctx!.beginPath();
+ ctx!.moveTo(x + radius, y);
+ ctx!.lineTo(x + barWidth - radius, y);
+ ctx!.quadraticCurveTo(x + barWidth, y, x + barWidth, y + radius);
+ ctx!.lineTo(x + barWidth, y + barH - radius);
+ ctx!.quadraticCurveTo(x + barWidth, y + barH, x + barWidth - radius, y + barH);
+ ctx!.lineTo(x + radius, y + barH);
+ ctx!.quadraticCurveTo(x, y + barH, x, y + barH - radius);
+ ctx!.lineTo(x, y + radius);
+ ctx!.quadraticCurveTo(x, y, x + radius, y);
+ ctx!.closePath();
+ ctx!.fill();
+ }
+
+ animFrameRef.current = requestAnimationFrame(draw);
+ }
+
+ draw();
+ return () => cancelAnimationFrame(animFrameRef.current);
+ }, [bars, progress]);
+
+ function togglePlay() {
+ const audio = audioRef.current;
+ if (!audio) return;
+ if (playing) {
+ audio.pause();
+ setPlaying(false);
+ } else {
+ audio.play();
+ setPlaying(true);
+ }
+ }
+
+ function seekFromClick(e: React.MouseEvent) {
+ const audio = audioRef.current;
+ const canvas = canvasRef.current;
+ if (!audio || !canvas || !audio.duration) return;
+ const rect = canvas.getBoundingClientRect();
+ const pct = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
+ audio.currentTime = pct * audio.duration;
+ setProgress(pct);
+ }
+
+ function formatTime(s: number) {
+ if (!s || !isFinite(s)) return "0:00";
+ const m = Math.floor(s / 60);
+ const sec = Math.floor(s % 60);
+ return `${m}:${sec.toString().padStart(2, "0")}`;
+ }
+
+ return (
+
+
+
+
+ {playing ? : }
+
+
+
+
+ {formatTime((duration || 0) * progress)}
+ {formatTime(duration)}
+
+
+
{
+ const a = document.createElement("a");
+ a.href = src;
+ a.download = "speech.mp3";
+ a.click();
+ }}
+ title="Download MP3"
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground/40 transition-colors hover:bg-white/[0.06] hover:text-foreground"
+ >
+
+
+
+
+ );
+}
+
+// ── Markdown renderer ────────────────────────────────────
+
+function MarkdownContent({ content }: { content: string }) {
+ return (
+
+
{children}
,
+ h1: ({ children }) => {children} ,
+ h2: ({ children }) => {children} ,
+ h3: ({ children }) => {children} ,
+ ul: ({ children }) => ,
+ ol: ({ children }) => {children} ,
+ li: ({ children }) => {children} ,
+ blockquote: ({ children }) => (
+
+ {children}
+
+ ),
+ code: ({ className, children, ...props }) => {
+ const isBlock = className?.includes("language-");
+ if (isBlock) {
+ const lang = className?.replace("language-", "") ?? "";
+ return (
+
+ {lang && (
+
+ {lang}
+ navigator.clipboard.writeText(String(children).replace(/\n$/, ""))}
+ className="opacity-0 transition-opacity group-hover:opacity-100 hover:text-foreground"
+ >
+ Copy
+
+
+ )}
+
+ {children}
+
+
+ );
+ }
+ return (
+
+ {children}
+
+ );
+ },
+ pre: ({ children }) => <>{children}>,
+ img: ({ src, alt }) => (
+
+ ),
+ a: ({ href, children }) => (
+
+ {children}
+
+ ),
+ table: ({ children }) => (
+
+ ),
+ thead: ({ children }) => {children} ,
+ th: ({ children }) => {children} ,
+ td: ({ children }) => {children} ,
+ hr: () => ,
+ strong: ({ children }) => {children} ,
+ }}
+ >
+ {content}
+
+
+ );
+}
+
+// ── Component ────────────────────────────────────────────
+
+export default function ChatPage() {
+ // Models
+ const [models, setModels] = useState([]);
+ const [model, setModel] = useState("");
+ const [modelMenuOpen, setModelMenuOpen] = useState(false);
+
+ // Preferences
+ const [favourites, setFavourites] = useState([]);
+ const [defaultModel, setDefaultModel] = useState("");
+
+ // Conversations
+ const [conversations, setConversations] = useState([]);
+ const [activeConversationId, setActiveConversationId] = useState(null);
+ const [messages, setMessages] = useState([]);
+
+ // Input
+ const [input, setInput] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+ const [streamingText, setStreamingText] = useState("");
+ const [streamingProviderId, setStreamingProviderId] = useState();
+ const abortRef = useRef(null);
+ const fileInputRef = useRef(null);
+ const [pendingImages, setPendingImages] = useState([]);
+
+ // Incognito
+ const [incognito, setIncognito] = useState(false);
+ const [incognitoHistory, setIncognitoHistory] = useState([]);
+
+ // UI
+ const [sidebarOpen, setSidebarOpen] = useState(true);
+ const scrollRef = useRef(null);
+ const textareaRef = useRef(null);
+
+ const currentMessages = incognito ? incognitoHistory : messages;
+
+ // ── Load models + preferences ──────────────────────────
+ useEffect(() => {
+ Promise.all([
+ fetch("/api/dashboard/playground").then((r) => (r.ok ? r.json() : null)),
+ fetch("/api/chat/preferences").then((r) => (r.ok ? r.json() : null)),
+ ]).then(([modelsData, prefsData]) => {
+ const modelList: ModelOption[] = modelsData?.data ?? [];
+ setModels(modelList);
+
+ const prefs = prefsData?.data as { defaultModel?: string; favouriteModels?: string[] } | undefined;
+ const favs = prefs?.favouriteModels ?? [];
+ const defModel = prefs?.defaultModel ?? "";
+ setFavourites(favs);
+ setDefaultModel(defModel);
+
+ // Set initial model: default > first favourite > first model
+ if (!model) {
+ const initial =
+ (defModel && modelList.some((m) => m.id === defModel) ? defModel : "") ||
+ favs.find((f) => modelList.some((m) => m.id === f)) ||
+ modelList[0]?.id ||
+ "";
+ setModel(initial);
+ }
+ }).catch(() => {});
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // ── Save preferences helper ────────────────────────────
+ const savePreferences = useCallback(
+ async (newFavs: string[], newDefault: string) => {
+ setFavourites(newFavs);
+ setDefaultModel(newDefault);
+ await fetch("/api/chat/preferences", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ favouriteModels: newFavs, defaultModel: newDefault }),
+ }).catch(() => {});
+ },
+ [],
+ );
+
+ function toggleFavourite(modelId: string) {
+ const next = favourites.includes(modelId)
+ ? favourites.filter((f) => f !== modelId)
+ : [...favourites, modelId];
+ // If unfavouriting the default model, clear default
+ const nextDefault = !next.includes(defaultModel) && defaultModel === modelId ? "" : defaultModel;
+ savePreferences(next, nextDefault);
+ }
+
+ function setAsDefault(modelId: string) {
+ const nextDefault = defaultModel === modelId ? "" : modelId;
+ // Auto-favourite when setting as default
+ const nextFavs = nextDefault && !favourites.includes(modelId) ? [...favourites, modelId] : favourites;
+ savePreferences(nextFavs, nextDefault);
+ }
+
+ // Sorted models: default first, then favourites, then rest
+ const sortedModels = [...models].sort((a, b) => {
+ const aDefault = a.id === defaultModel ? 0 : 1;
+ const bDefault = b.id === defaultModel ? 0 : 1;
+ if (aDefault !== bDefault) return aDefault - bDefault;
+ const aFav = favourites.includes(a.id) ? 0 : 1;
+ const bFav = favourites.includes(b.id) ? 0 : 1;
+ if (aFav !== bFav) return aFav - bFav;
+ return a.id.localeCompare(b.id);
+ });
+
+ // ── Load conversations ─────────────────────────────────
+ const loadConversations = useCallback(async () => {
+ const res = await fetch("/api/chat/conversations");
+ if (!res.ok) return;
+ const data = await res.json();
+ setConversations(data.data ?? []);
+ }, []);
+
+ useEffect(() => {
+ loadConversations();
+ }, [loadConversations]);
+
+ // ── Load messages for active conversation ──────────────
+ useEffect(() => {
+ if (!activeConversationId || incognito) return;
+ fetch(`/api/chat/conversations/${activeConversationId}/messages`)
+ .then((r) => (r.ok ? r.json() : null))
+ .then((data) => {
+ if (data?.data) setMessages(data.data);
+ })
+ .catch(() => {});
+ }, [activeConversationId, incognito]);
+
+ // ── Auto scroll ────────────────────────────────────────
+ useEffect(() => {
+ requestAnimationFrame(() => {
+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
+ });
+ }, [currentMessages, submitting, streamingText]);
+
+ // ── Auto resize textarea ──────────────────────────────
+ useEffect(() => {
+ const el = textareaRef.current;
+ if (!el) return;
+ el.style.height = "auto";
+ el.style.height = Math.min(el.scrollHeight, 200) + "px";
+ }, [input]);
+
+ // ── Image helpers ────────────────────────────────────────
+ function fileToBase64(file: File): Promise {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.onerror = reject;
+ reader.readAsDataURL(file);
+ });
+ }
+
+ async function addImageFiles(files: FileList | File[]) {
+ const allowed = ["image/png", "image/jpeg", "image/gif", "image/webp"];
+ const maxSize = 20 * 1024 * 1024; // 20 MB
+ const newParts: ImagePart[] = [];
+ for (const file of Array.from(files)) {
+ if (!allowed.includes(file.type)) {
+ toast.error(`Unsupported file type: ${file.type}`);
+ continue;
+ }
+ if (file.size > maxSize) {
+ toast.error(`File too large: ${file.name} (max 20 MB)`);
+ continue;
+ }
+ const dataUrl = await fileToBase64(file);
+ newParts.push({ type: "image_url", image_url: { url: dataUrl } });
+ }
+ if (newParts.length) {
+ setPendingImages((prev) => [...prev, ...newParts].slice(0, 10));
+ }
+ }
+
+ function removePendingImage(index: number) {
+ setPendingImages((prev) => prev.filter((_, i) => i !== index));
+ }
+
+ // ── New chat ───────────────────────────────────────────
+ function newChat() {
+ if (incognito) {
+ setIncognitoHistory([]);
+ return;
+ }
+ setActiveConversationId(null);
+ setMessages([]);
+ }
+
+ // ── Select conversation ────────────────────────────────
+ function selectConversation(conv: Conversation) {
+ if (incognito) setIncognito(false);
+ setActiveConversationId(conv.id);
+ if (conv.model) setModel(conv.model);
+ }
+
+ // ── Delete conversation ────────────────────────────────
+ async function deleteConversation(id: string) {
+ await fetch(`/api/chat/conversations/${id}`, { method: "DELETE" });
+ if (activeConversationId === id) {
+ setActiveConversationId(null);
+ setMessages([]);
+ }
+ loadConversations();
+ }
+
+ // ── Toggle incognito ───────────────────────────────────
+ function toggleIncognito() {
+ if (!incognito) {
+ setIncognito(true);
+ setIncognitoHistory([]);
+ } else {
+ setIncognito(false);
+ }
+ }
+
+ // ── Stop generation ────────────────────────────────────
+ function stopGeneration() {
+ abortRef.current?.abort();
+ }
+
+ // ── Read SSE stream ────────────────────────────────────
+ async function readStream(response: Response, onToken: (token: string) => void): Promise<{
+ fullText: string;
+ providerId?: string;
+ tokensIn?: number;
+ tokensOut?: number;
+ }> {
+ const reader = response.body!.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ let fullText = "";
+ let providerId: string | undefined;
+ let tokensIn: number | undefined;
+ let tokensOut: number | undefined;
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, { stream: true });
+ const { events, remaining } = parseSSELines(buffer);
+ buffer = remaining;
+
+ for (const evt of events) {
+ if (evt.event === "meta") {
+ try {
+ const meta = JSON.parse(evt.data);
+ if (meta.providerId) providerId = meta.providerId;
+ } catch { /* skip */ }
+ continue;
+ }
+
+ if (evt.event === "done") {
+ try {
+ const meta = JSON.parse(evt.data);
+ if (meta.tokensIn != null) tokensIn = meta.tokensIn;
+ if (meta.tokensOut != null) tokensOut = meta.tokensOut;
+ } catch { /* skip */ }
+ continue;
+ }
+
+ if (evt.data === "[DONE]") continue;
+
+ try {
+ const json = JSON.parse(evt.data);
+ const delta = json.choices?.[0]?.delta;
+ if (delta?.content) {
+ fullText += delta.content;
+ onToken(delta.content);
+ }
+ } catch {
+ // skip non-JSON lines
+ }
+ }
+ }
+
+ return { fullText, providerId, tokensIn, tokensOut };
+ }
+
+ // ── Image/Audio generation helpers ───────────────────────
+ async function handleImageGeneration(userContent: string, abort: AbortController, msgSetter: typeof setMessages | typeof setIncognitoHistory, convId: string | null) {
+ try {
+ const res = await fetch("/api/chat/generate-image", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model, prompt: userContent }),
+ signal: abort.signal,
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => null);
+ toast.error(typeof err?.error === "string" ? err.error : err?.error?.message ?? "Image generation failed");
+ msgSetter((prev) => prev.slice(0, -1));
+ setInput(userContent);
+ return;
+ }
+ const data = await res.json();
+ const assistantMsg: ChatMessage = {
+ role: "assistant",
+ content: data.images?.[0]?.revised_prompt || "Generated image",
+ generatedImages: data.images,
+ providerId: data.providerId,
+ model,
+ };
+ msgSetter((prev) => [...prev, assistantMsg]);
+
+ // Save to DB if not incognito
+ if (convId) {
+ await fetch(`/api/chat/conversations/${convId}/save`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ messages: [
+ { role: "user", content: userContent },
+ { role: "assistant", content: assistantMsg.content, model, providerId: data.providerId, generatedImages: data.images },
+ ],
+ }),
+ }).catch(() => {});
+ loadConversations();
+ }
+ } catch (err) {
+ if ((err as Error).name !== "AbortError") {
+ toast.error("Image generation failed");
+ msgSetter((prev) => prev.slice(0, -1));
+ setInput(userContent);
+ }
+ }
+ }
+
+ async function handleAudioGeneration(userContent: string, abort: AbortController, msgSetter: typeof setMessages | typeof setIncognitoHistory, convId: string | null) {
+ try {
+ const res = await fetch("/api/chat/generate-audio", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model, input: userContent }),
+ signal: abort.signal,
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => null);
+ toast.error(typeof err?.error === "string" ? err.error : err?.error?.message ?? "Audio generation failed");
+ msgSetter((prev) => prev.slice(0, -1));
+ setInput(userContent);
+ return;
+ }
+ const data = await res.json();
+ const assistantMsg: ChatMessage = {
+ role: "assistant",
+ content: "Generated audio",
+ audioB64: data.audio?.b64,
+ audioContentType: data.audio?.contentType ?? "audio/mpeg",
+ providerId: data.providerId,
+ model,
+ };
+ msgSetter((prev) => [...prev, assistantMsg]);
+
+ // Save to DB if not incognito
+ if (convId) {
+ await fetch(`/api/chat/conversations/${convId}/save`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ messages: [
+ { role: "user", content: userContent },
+ { role: "assistant", content: "Generated audio", model, providerId: data.providerId, audioB64: data.audio?.b64, audioContentType: data.audio?.contentType ?? "audio/mpeg" },
+ ],
+ }),
+ }).catch(() => {});
+ loadConversations();
+ }
+ } catch (err) {
+ if ((err as Error).name !== "AbortError") {
+ toast.error("Audio generation failed");
+ msgSetter((prev) => prev.slice(0, -1));
+ setInput(userContent);
+ }
+ }
+ }
+
+ // ── Send message ───────────────────────────────────────
+ async function handleSubmit(e?: FormEvent) {
+ e?.preventDefault();
+ if ((!input.trim() && !pendingImages.length) || !model || submitting) return;
+
+ const userContent = input.trim() || (pendingImages.length ? "What's in this image?" : "");
+ const userImages = pendingImages.length ? [...pendingImages] : undefined;
+ setInput("");
+ setPendingImages([]);
+ setStreamingText("");
+ setStreamingProviderId(undefined);
+
+ const abort = new AbortController();
+ abortRef.current = abort;
+
+ // For image/audio models, use dedicated endpoints
+ if (currentModelType === "image" || currentModelType === "audio") {
+ const msgSetter = incognito ? setIncognitoHistory : setMessages;
+ const userMsg: ChatMessage = { role: "user", content: userContent, images: userImages };
+ msgSetter((prev) => [...prev, userMsg]);
+ setSubmitting(true);
+
+ // Create conversation if not incognito and no active conversation
+ let convId: string | null = incognito ? null : activeConversationId;
+ if (!incognito && !convId) {
+ try {
+ const convRes = await fetch("/api/chat/conversations", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model }),
+ });
+ if (convRes.ok) {
+ const convData = await convRes.json();
+ convId = convData.data.id;
+ setActiveConversationId(convId);
+ }
+ } catch { /* continue without saving */ }
+ }
+
+ if (currentModelType === "image") {
+ await handleImageGeneration(userContent, abort, msgSetter, convId);
+ } else {
+ await handleAudioGeneration(userContent, abort, msgSetter, convId);
+ }
+
+ setStreamingText("");
+ setSubmitting(false);
+ return;
+ }
+
+ if (incognito) {
+ const userMsg: ChatMessage = { role: "user", content: userContent, images: userImages };
+ setIncognitoHistory((prev) => [...prev, userMsg]);
+ setSubmitting(true);
+
+ try {
+ const res = await fetch("/api/chat/incognito", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ model,
+ message: userContent,
+ ...(userImages ? { images: userImages } : {}),
+ history: incognitoHistory.map((m) => ({
+ role: m.role,
+ content: m.content,
+ ...(m.images ? { images: m.images } : {}),
+ })),
+ }),
+ signal: abort.signal,
+ });
+
+ if (!res.ok || !res.body) {
+ const err = await res.json().catch(() => null);
+ toast.error(typeof err?.error === "string" ? err.error : err?.error?.message ?? "Request failed");
+ setIncognitoHistory((prev) => prev.slice(0, -1));
+ setInput(userContent);
+ setSubmitting(false);
+ return;
+ }
+
+ let accumulated = "";
+ const result = await readStream(res, (token) => {
+ accumulated += token;
+ setStreamingText(accumulated);
+ });
+
+ setStreamingProviderId(result.providerId);
+ setIncognitoHistory((prev) => [
+ ...prev,
+ {
+ role: "assistant",
+ content: result.fullText,
+ providerId: result.providerId,
+ model,
+ },
+ ]);
+ } catch (err) {
+ if ((err as Error).name !== "AbortError") {
+ toast.error("Stream failed");
+ setIncognitoHistory((prev) => prev.slice(0, -1));
+ setInput(userContent);
+ }
+ }
+
+ setStreamingText("");
+ setSubmitting(false);
+ return;
+ }
+
+ // Normal mode: create conversation if needed
+ let convId = activeConversationId;
+ if (!convId) {
+ const res = await fetch("/api/chat/conversations", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model }),
+ });
+ if (!res.ok) {
+ toast.error("Failed to create conversation");
+ return;
+ }
+ const data = await res.json();
+ convId = data.data.id;
+ setActiveConversationId(convId);
+ }
+
+ const userMsg: ChatMessage = { role: "user", content: userContent, images: userImages };
+ setMessages((prev) => [...prev, userMsg]);
+ setSubmitting(true);
+
+ try {
+ const res = await fetch(`/api/chat/conversations/${convId}/messages`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ content: userContent,
+ model,
+ ...(userImages ? { images: userImages } : {}),
+ }),
+ signal: abort.signal,
+ });
+
+ if (!res.ok || !res.body) {
+ const err = await res.json().catch(() => null);
+ toast.error(typeof err?.error === "string" ? err.error : err?.error?.message ?? "Request failed");
+ setMessages((prev) => prev.slice(0, -1));
+ setInput(userContent);
+ setSubmitting(false);
+ return;
+ }
+
+ let accumulated = "";
+ const result = await readStream(res, (token) => {
+ accumulated += token;
+ setStreamingText(accumulated);
+ });
+
+ setStreamingProviderId(result.providerId);
+
+ // Replace optimistic user message + add the full assistant message
+ setMessages((prev) => {
+ const updated = [...prev];
+ // The last message is the optimistic user message; keep it
+ updated.push({
+ role: "assistant",
+ content: result.fullText,
+ providerId: result.providerId,
+ model,
+ tokensIn: result.tokensIn,
+ tokensOut: result.tokensOut,
+ });
+ return updated;
+ });
+
+ loadConversations();
+ } catch (err) {
+ if ((err as Error).name !== "AbortError") {
+ toast.error("Stream failed");
+ setMessages((prev) => prev.slice(0, -1));
+ setInput(userContent);
+ }
+ }
+
+ setStreamingText("");
+ setSubmitting(false);
+ }
+
+ // ── Group conversations by date ────────────────────────
+ function groupConversations() {
+ const now = new Date();
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
+ const yesterday = new Date(today.getTime() - 86400000);
+ const sevenDaysAgo = new Date(today.getTime() - 7 * 86400000);
+ const thirtyDaysAgo = new Date(today.getTime() - 30 * 86400000);
+
+ const groups: { label: string; items: Conversation[] }[] = [
+ { label: "Today", items: [] },
+ { label: "Yesterday", items: [] },
+ { label: "Previous 7 days", items: [] },
+ { label: "Previous 30 days", items: [] },
+ { label: "Older", items: [] },
+ ];
+
+ for (const conv of conversations) {
+ const d = new Date(conv.updatedAt);
+ if (d >= today) groups[0].items.push(conv);
+ else if (d >= yesterday) groups[1].items.push(conv);
+ else if (d >= sevenDaysAgo) groups[2].items.push(conv);
+ else if (d >= thirtyDaysAgo) groups[3].items.push(conv);
+ else groups[4].items.push(conv);
+ }
+
+ return groups.filter((g) => g.items.length > 0);
+ }
+
+ const currentModel = models.find((m) => m.id === model);
+ const providerForModel = currentModel?.providerId;
+ const currentModelType: ModelType = currentModel?.modelType ?? "chat";
+
+ return (
+
+ {/* ── Sidebar overlay for mobile ──────────────────── */}
+ {sidebarOpen && (
+
setSidebarOpen(false)} />
+ )}
+
+ {/* ── Sidebar ─────────────────────────────────────── */}
+
+
+ {/* ── Main area ───────────────────────────────────── */}
+
+ {/* Top bar */}
+
+
+
setSidebarOpen(!sidebarOpen)}
+ className="rounded-lg p-1.5 text-muted-foreground transition-colors hover:bg-white/[0.04] hover:text-foreground"
+ >
+ {sidebarOpen ? : }
+
+
+ {/* Model selector */}
+
+
setModelMenuOpen(!modelMenuOpen)}
+ className="flex items-center gap-2 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors hover:bg-white/[0.04]"
+ >
+ {currentModelType === "image" ? (
+
+ ) : currentModelType === "audio" ? (
+
+ ) : (
+
+ )}
+ {model || "Select model"}
+
+
+ {modelMenuOpen && (
+ <>
+
setModelMenuOpen(false)} />
+
+ {/* Favourites section */}
+ {sortedModels.some((m) => favourites.includes(m.id)) && (
+ <>
+
+ Favourites
+
+ {sortedModels
+ .filter((m) => favourites.includes(m.id))
+ .map((m) => (
+
{ setModel(m.id); setModelMenuOpen(false); }}
+ onToggleFav={() => toggleFavourite(m.id)}
+ onSetDefault={() => setAsDefault(m.id)}
+ />
+ ))}
+
+
+ All Models
+
+ >
+ )}
+ {sortedModels
+ .filter((m) => !favourites.includes(m.id))
+ .map((m) => (
+ { setModel(m.id); setModelMenuOpen(false); }}
+ onToggleFav={() => toggleFavourite(m.id)}
+ onSetDefault={() => setAsDefault(m.id)}
+ />
+ ))}
+
+ >
+ )}
+
+
+ {providerForModel && (
+
via {providerForModel}
+ )}
+
+
+
+ {incognito && (
+
+
+ Incognito
+
+ )}
+
+
+
+ {/* Messages area */}
+
+ {currentMessages.length === 0 && !submitting ? (
+
+
+ {currentModelType === "image" ? (
+
+ ) : currentModelType === "audio" ? (
+
+ ) : (
+
+ )}
+
+
+ {incognito
+ ? "Incognito Chat"
+ : currentModelType === "image"
+ ? "Generate Images"
+ : currentModelType === "audio"
+ ? "Text to Speech"
+ : "Start a conversation"}
+
+
+ {incognito
+ ? "Messages in this session won't be saved. Close or switch to normal mode to clear."
+ : currentModelType === "image"
+ ? "Describe the image you want to create and the model will generate it for you."
+ : currentModelType === "audio"
+ ? "Enter text and the model will convert it to natural-sounding speech."
+ : "Send a message to begin. Your conversation will be saved automatically."}
+
+
+ ) : (
+
+ {currentMessages.map((msg, idx) => (
+
+ {msg.role === "user" ? (
+
+
+ {msg.images?.length ? (
+
+ {msg.images.map((img, i) => (
+
+ ))}
+
+ ) : null}
+
{msg.content}
+
+
+ ) : (
+
+
+
+
+
+ {/* Generated images */}
+ {msg.generatedImages?.length ? (
+
+ {msg.content && msg.content !== "Generated image" && (
+
{msg.content}
+ )}
+
+ {msg.generatedImages.map((img, i) => (
+
+
+
+ ))}
+
+ {msg.generatedImages[0]?.revised_prompt && (
+
{msg.generatedImages[0].revised_prompt}
+ )}
+
+ ) : msg.audioB64 ? (
+
+ ) : (
+
+ )}
+ {(msg.providerId || msg.tokensIn != null) && (
+
+ {msg.providerId && {msg.providerId} }
+ {msg.model && {msg.model} }
+ {msg.tokensIn != null && msg.tokensOut != null && (
+ {msg.tokensIn + msg.tokensOut} tokens
+ )}
+
+ )}
+
+
+ )}
+
+ ))}
+
+ {/* Streaming / generating indicator */}
+ {submitting && (
+
+
+ {currentModelType === "image" ? (
+
+ ) : currentModelType === "audio" ? (
+
+ ) : (
+
+ )}
+
+
+ {streamingText ? (
+
+
+
+
+ ) : currentModelType === "image" ? (
+
+
+ Generating image...
+
+ ) : currentModelType === "audio" ? (
+
+
+ Generating audio...
+
+ ) : (
+
+ )}
+ {streamingProviderId && (
+
{streamingProviderId}
+ )}
+
+
+ )}
+
+ )}
+
+
+ {/* Input area */}
+
{ e.preventDefault(); e.stopPropagation(); }}
+ onDrop={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (e.dataTransfer.files.length) addImageFiles(e.dataTransfer.files);
+ }}
+ >
+
+
+
+
+ );
+}
diff --git a/src/app/dashboard/api-keys/page.tsx b/src/app/dashboard/api-keys/page.tsx
index 26bc6ce..1c5f90f 100644
--- a/src/app/dashboard/api-keys/page.tsx
+++ b/src/app/dashboard/api-keys/page.tsx
@@ -120,10 +120,10 @@ export default function ApiKeysPage() {
return (
-
+
-
API Keys
-
Manage your API keys for accessing the LLM Proxy
+
API Keys
+
Manage your API keys for accessing the LLM Proxy
+
- {children}
+ {children}
);
diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsx
index bd8e8fe..69d3c90 100644
--- a/src/app/dashboard/page.tsx
+++ b/src/app/dashboard/page.tsx
@@ -72,21 +72,25 @@ export default async function DashboardOverview() {
title: "Active API Keys",
value: apiKeyCount,
icon: Key,
+ color: "text-blue-400",
},
{
title: "Requests Today",
value: todayLogs._count,
icon: Activity,
+ color: "text-cyan-400",
},
{
title: "Tokens Today",
value: ((todayLogs._sum.tokensIn ?? 0) + (todayLogs._sum.tokensOut ?? 0)).toLocaleString(),
icon: AlertCircle,
+ color: "text-violet-400",
},
{
title: "Cost Today",
value: `$${((todayLogs._sum.costCents ?? 0) / 100).toFixed(4)}`,
icon: Coins,
+ color: "text-emerald-400",
},
];
@@ -99,16 +103,16 @@ export default async function DashboardOverview() {
-
+
-
+
API Documentation
Open guides, endpoint reference, and live API testing.
-
+
Open Docs
@@ -116,10 +120,10 @@ export default async function DashboardOverview() {
{stats.map((stat) => (
-
+
{stat.title}
-
+
{stat.value}
diff --git a/src/app/dashboard/playground/page.tsx b/src/app/dashboard/playground/page.tsx
index 92d4c31..d5ff495 100644
--- a/src/app/dashboard/playground/page.tsx
+++ b/src/app/dashboard/playground/page.tsx
@@ -130,8 +130,8 @@ export default function PlaygroundPage() {
Test any mapped model directly from your dashboard.
-
-
+
+
@@ -200,7 +200,7 @@ export default function PlaygroundPage() {
-
+
Chat
diff --git a/src/app/dashboard/usage/page.tsx b/src/app/dashboard/usage/page.tsx
index f40f8ae..604a54f 100644
--- a/src/app/dashboard/usage/page.tsx
+++ b/src/app/dashboard/usage/page.tsx
@@ -8,31 +8,11 @@ export default async function UsagePage() {
const session = await getSession();
if (!session) return null;
- // Last 30 days aggregates
+ // Last 30 days
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
- const aggregates = await db.usageAggregateDaily.findMany({
- where: {
- userId: session.user.id,
- date: { gte: thirtyDaysAgo },
- userApiKeyId: null, // user-level aggregates
- },
- orderBy: { date: "desc" },
- take: 30,
- });
-
- const totals = aggregates.reduce(
- (acc, row) => ({
- requests: acc.requests + row.totalRequests,
- tokensIn: acc.tokensIn + row.totalTokensIn,
- tokensOut: acc.tokensOut + row.totalTokensOut,
- cost: acc.cost + row.totalCostCents,
- }),
- { requests: 0, tokensIn: 0, tokensOut: 0, cost: 0 },
- );
-
- const [providerStats, modelStats, apiKeyStats, apiKeys] = await Promise.all([
+ const [providerStats, modelStats, apiKeyStats, apiKeys, allLogs] = await Promise.all([
db.requestLog.groupBy({
by: ["providerId"],
where: {
@@ -73,19 +53,51 @@ export default async function UsagePage() {
where: { userId: session.user.id },
select: { id: true, keyPrefix: true },
}),
+ db.requestLog.findMany({
+ where: {
+ userId: session.user.id,
+ createdAt: { gte: thirtyDaysAgo },
+ softDeleted: false,
+ },
+ select: { tokensIn: true, tokensOut: true, costCents: true, createdAt: true },
+ orderBy: { createdAt: "asc" },
+ }),
]);
+ // Compute totals and daily breakdown from raw request logs
+ type LogRow = { tokensIn: number; tokensOut: number; costCents: number; createdAt: Date | string };
+ const logs = allLogs as LogRow[];
+
+ const totals = logs.reduce(
+ (acc, row) => ({
+ requests: acc.requests + 1,
+ tokensIn: acc.tokensIn + (row.tokensIn ?? 0),
+ tokensOut: acc.tokensOut + (row.tokensOut ?? 0),
+ cost: acc.cost + (row.costCents ?? 0),
+ }),
+ { requests: 0, tokensIn: 0, tokensOut: 0, cost: 0 },
+ );
+
+ // Group logs by day for daily chart
+ const dailyMap = new Map();
+ for (const row of logs) {
+ const d = new Date(row.createdAt).toLocaleDateString();
+ const existing = dailyMap.get(d) ?? { requests: 0, tokensIn: 0, tokensOut: 0, cost: 0 };
+ existing.requests += 1;
+ existing.tokensIn += row.tokensIn ?? 0;
+ existing.tokensOut += row.tokensOut ?? 0;
+ existing.cost += row.costCents ?? 0;
+ dailyMap.set(d, existing);
+ }
+
const keyPrefixMap = new Map(apiKeys.map((k) => [k.id, k.keyPrefix]));
- const chartDaily = aggregates
- .slice()
- .reverse()
- .map((row) => ({
- date: new Date(row.date).toLocaleDateString(),
- requests: row.totalRequests,
- tokensIn: row.totalTokensIn,
- tokensOut: row.totalTokensOut,
- cost: Number((row.totalCostCents / 100).toFixed(4)),
- }));
+ const chartDaily = [...dailyMap.entries()].map(([date, data]) => ({
+ date,
+ requests: data.requests,
+ tokensIn: data.tokensIn,
+ tokensOut: data.tokensOut,
+ cost: Number((data.cost / 100).toFixed(4)),
+ }));
const chartProviders = providerStats.map((row) => ({
name: row.providerId,
@@ -122,33 +134,33 @@ export default async function UsagePage() {
-
+
- Total Requests
+ Total Requests
{totals.requests.toLocaleString()}
-
+
- Input Tokens
+ Input Tokens
{totals.tokensIn.toLocaleString()}
-
+
- Output Tokens
+ Output Tokens
{totals.tokensOut.toLocaleString()}
-
+
- Total Cost
+ Total Cost
${(totals.cost / 100).toFixed(4)}
@@ -161,7 +173,7 @@ export default async function UsagePage() {
Daily Breakdown
- {aggregates.length === 0 ? (
+ {chartDaily.length === 0 ? (
No usage data yet.
) : (
@@ -172,18 +184,16 @@ export default async function UsagePage() {
Tokens In
Tokens Out
Cost
- Errors
- {aggregates.map((row) => (
-
- {new Date(row.date).toLocaleDateString()}
- {row.totalRequests.toLocaleString()}
- {row.totalTokensIn.toLocaleString()}
- {row.totalTokensOut.toLocaleString()}
- ${(row.totalCostCents / 100).toFixed(4)}
- {row.totalErrors}
+ {[...chartDaily].reverse().map((row) => (
+
+ {row.date}
+ {row.requests.toLocaleString()}
+ {row.tokensIn.toLocaleString()}
+ {row.tokensOut.toLocaleString()}
+ ${row.cost.toFixed(4)}
))}
diff --git a/src/app/docs/layout.tsx b/src/app/docs/layout.tsx
index c818561..88bdef2 100644
--- a/src/app/docs/layout.tsx
+++ b/src/app/docs/layout.tsx
@@ -6,7 +6,7 @@ import { KeySelector } from "@/components/docs/key-selector";
export default function DocsLayout({ children }: { children: React.ReactNode }) {
return (
-
+
LLM Proxy
diff --git a/src/app/globals.css b/src/app/globals.css
index aad631a..5b3c085 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -1,26 +1,33 @@
@import "tailwindcss";
@theme inline {
- --color-background: hsl(230 26% 8%);
- --color-foreground: hsl(210 40% 96%);
- --color-card: hsl(230 24% 11%);
- --color-card-foreground: hsl(210 40% 96%);
- --color-popover: hsl(230 24% 11%);
- --color-popover-foreground: hsl(210 40% 96%);
- --color-primary: hsl(188 100% 62%);
- --color-primary-foreground: hsl(220 40% 8%);
- --color-secondary: hsl(230 20% 17%);
- --color-secondary-foreground: hsl(210 40% 96%);
- --color-muted: hsl(230 18% 16%);
- --color-muted-foreground: hsl(220 18% 72%);
- --color-accent: hsl(230 20% 20%);
- --color-accent-foreground: hsl(210 40% 96%);
- --color-destructive: hsl(2 79% 60%);
+ --color-background: hsl(220 16% 4%);
+ --color-foreground: hsl(210 20% 95%);
+ --color-card: hsl(220 16% 7%);
+ --color-card-foreground: hsl(210 20% 95%);
+ --color-popover: hsl(220 16% 7%);
+ --color-popover-foreground: hsl(210 20% 95%);
+ --color-primary: hsl(213 94% 58%);
+ --color-primary-foreground: hsl(0 0% 100%);
+ --color-secondary: hsl(220 14% 12%);
+ --color-secondary-foreground: hsl(210 20% 95%);
+ --color-muted: hsl(220 14% 11%);
+ --color-muted-foreground: hsl(220 10% 55%);
+ --color-accent: hsl(220 14% 14%);
+ --color-accent-foreground: hsl(210 20% 95%);
+ --color-destructive: hsl(0 72% 55%);
--color-destructive-foreground: hsl(0 0% 98%);
- --color-border: hsl(230 20% 24%);
- --color-input: hsl(230 20% 24%);
- --color-ring: hsl(188 100% 62%);
+ --color-border: hsl(220 14% 14%);
+ --color-input: hsl(220 14% 14%);
+ --color-ring: hsl(213 94% 58%);
--radius: 0.5rem;
+
+ --color-chart-blue: hsl(213 94% 58%);
+ --color-chart-cyan: hsl(187 85% 53%);
+ --color-chart-violet: hsl(258 80% 65%);
+ --color-chart-emerald: hsl(160 72% 47%);
+ --color-chart-amber: hsl(38 92% 55%);
+ --color-chart-rose: hsl(347 77% 60%);
}
@layer base {
@@ -34,7 +41,5 @@
min-height: 100vh;
background-color: var(--color-background);
color: var(--color-foreground);
- background-image: radial-gradient(circle at 10% 10%, hsl(188 100% 62% / 0.08), transparent 25%),
- radial-gradient(circle at 90% 20%, hsl(260 90% 65% / 0.08), transparent 30%);
}
}
diff --git a/src/app/page.tsx b/src/app/page.tsx
index a279734..0dc62ca 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -67,23 +67,22 @@ export default async function Home() {
return (
-
-
-
-
+
-
-
+
+
-
+
LLM Proxy
Login
-
+
{session?.user ? "Open Dashboard" : "Get Started"}
@@ -92,10 +91,10 @@ export default async function Home() {
-
+
OpenAI-Compatible Multi-Provider Gateway
-
+
One key. Every model. One clean API.
@@ -103,16 +102,16 @@ export default async function Home() {
ship faster without juggling multiple integrations.
-
+
Start Building
-
+
Read API Docs
-
+
View Models API
@@ -120,7 +119,7 @@ export default async function Home() {
{stats.map((item) => (
-
+
{item.label}
{item.value}
@@ -129,13 +128,13 @@ export default async function Home() {
))}
-
+
Providers
{providers.map((provider) => (
{provider}
@@ -146,15 +145,15 @@ export default async function Home() {
Everything you need to ship faster
-
+
Modern API SaaS
{features.map((feature) => (
-
+
-
+
{feature.title}
{feature.description}
@@ -163,13 +162,13 @@ export default async function Home() {
-
+
Stop fighting limits. Start shipping continuously.
Connect once, route everywhere, and manage usage from a single dark-first control plane.
-
+
Launch Dashboard
diff --git a/src/components/admin/admin-analytics-charts.tsx b/src/components/admin/admin-analytics-charts.tsx
index 1c54f45..d399b59 100644
--- a/src/components/admin/admin-analytics-charts.tsx
+++ b/src/components/admin/admin-analytics-charts.tsx
@@ -1,6 +1,18 @@
"use client";
-import { Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
+import {
+ Area,
+ AreaChart,
+ Bar,
+ BarChart,
+ CartesianGrid,
+ Cell,
+ Legend,
+ ResponsiveContainer,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from "recharts";
interface ProviderRow {
name: string;
@@ -15,6 +27,28 @@ interface DailyRow {
cost: number;
}
+const PALETTE = [
+ "#3b82f6",
+ "#22d3ee",
+ "#8b5cf6",
+ "#34d399",
+ "#f59e0b",
+ "#f43f5e",
+ "#6366f1",
+ "#14b8a6",
+];
+
+const tooltipStyle = {
+ borderRadius: 12,
+ border: "1px solid rgba(255,255,255,0.06)",
+ backgroundColor: "hsl(220 16% 7%)",
+ boxShadow: "0 8px 32px rgba(0,0,0,0.5)",
+};
+const tooltipItemStyle = { color: "hsl(220 10% 80%)" };
+const tooltipLabelStyle = { color: "hsl(220 10% 55%)", marginBottom: 4 };
+
+const axisTick = { fill: "hsl(220 10% 45%)", fontSize: 12 };
+
export function AdminAnalyticsCharts({
providers,
daily,
@@ -38,87 +72,116 @@ export function AdminAnalyticsCharts({
return (
-
-
Requests by Provider
-
-
-
-
- numberFormatter.format(value)} />
-
- name === "cost"
- ? [currencyFormatter.format(toNumber(value)), "Cost"]
- : [numberFormatter.format(toNumber(value)), "Requests"]
- }
- />
-
-
-
+ {/* Provider bar chart with individual colors */}
+
+
Requests by Provider
+
Total requests per provider (30 days)
+
+
+
+
+
+ numberFormatter.format(value)} />
+
+ name === "cost"
+ ? [currencyFormatter.format(toNumber(value)), "Cost"]
+ : [numberFormatter.format(toNumber(value)), "Requests"]
+ }
+ />
+
+ {providers.map((_, index) => (
+ |
+ ))}
+
+
+
+
-
-
Daily Requests / Errors / Cost
-
-
-
-
- numberFormatter.format(value)}
- />
- currencyFormatter.format(value)}
- />
-
- name === "cost"
- ? [currencyFormatter.format(toNumber(value)), "Cost"]
- : [numberFormatter.format(toNumber(value)), name === "errors" ? "Errors" : "Requests"]
- }
- />
-
-
-
-
-
+ {/* Daily area chart with requests, errors, cost */}
+
+
Daily Overview
+
Requests, errors, and cost over time
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ numberFormatter.format(value)}
+ />
+ currencyFormatter.format(value)}
+ />
+
+ name === "Cost"
+ ? [currencyFormatter.format(toNumber(value)), "Cost"]
+ : [numberFormatter.format(toNumber(value)), name === "Errors" ? "Errors" : "Requests"]
+ }
+ />
+
+
+
+
+
+
+
);
diff --git a/src/components/admin/provider-management.tsx b/src/components/admin/provider-management.tsx
index e9ea4aa..b4ee9bb 100644
--- a/src/components/admin/provider-management.tsx
+++ b/src/components/admin/provider-management.tsx
@@ -191,12 +191,12 @@ export function ProviderManagement() {
return (
-
+
-
Provider Management
-
Manage ingested provider keys and routing readiness.
+
Provider Management
+
Manage ingested provider keys and routing readiness.
-
+
setTab("providers")}
className={cn(
@@ -219,7 +219,7 @@ export function ProviderManagement() {
{tab === "providers" ? (
-
+
Providers
@@ -309,13 +309,15 @@ export function ProviderManagement() {
{key.lastUsedAt ? formatDateTimeSafe(key.lastUsedAt, "Never") : "Never"}
{formatDateTimeSafe(key.createdAt)}
-
- toggleKeyStatus(key)}>
- {key.status === "ACTIVE" ? "Disable" : "Enable"}
-
- deleteKey(key)}>
- Delete
-
+
+
+ toggleKeyStatus(key)}>
+ {key.status === "ACTIVE" ? "Disable" : "Enable"}
+
+ deleteKey(key)}>
+ Delete
+
+
))}
@@ -326,7 +328,7 @@ export function ProviderManagement() {
) : (
-
+
Ingest Provider Keys
diff --git a/src/components/dashboard/dashboard-usage-graphs.tsx b/src/components/dashboard/dashboard-usage-graphs.tsx
index fa4fcdc..54cdcce 100644
--- a/src/components/dashboard/dashboard-usage-graphs.tsx
+++ b/src/components/dashboard/dashboard-usage-graphs.tsx
@@ -6,6 +6,7 @@ import {
Bar,
BarChart,
CartesianGrid,
+ Legend,
ResponsiveContainer,
Tooltip,
XAxis,
@@ -24,6 +25,24 @@ type ProviderPoint = {
requests: number;
};
+const COLORS = {
+ blue: "#3b82f6",
+ cyan: "#22d3ee",
+ violet: "#8b5cf6",
+ emerald: "#34d399",
+ amber: "#f59e0b",
+ rose: "#f43f5e",
+};
+
+const tooltipStyle = {
+ borderRadius: 12,
+ border: "1px solid rgba(255,255,255,0.06)",
+ backgroundColor: "hsl(220 16% 7%)",
+ boxShadow: "0 8px 32px rgba(0,0,0,0.5)",
+};
+const tooltipItemStyle = { color: "hsl(220 10% 80%)" };
+const tooltipLabelStyle = { color: "hsl(220 10% 55%)", marginBottom: 4 };
+
export function DashboardUsageGraphs({
trend,
providers,
@@ -41,7 +60,7 @@ export function DashboardUsageGraphs({
return (
-
+
Last 14 days
@@ -49,7 +68,7 @@ export function DashboardUsageGraphs({
Total Cost
-
+
{currencyFormatter.format(trend.reduce((acc, point) => acc + point.cost, 0))}
@@ -60,43 +79,50 @@ export function DashboardUsageGraphs({
-
-
+
+
-
-
+
+
-
-
- numberFormatter.format(value)} />
+
+
+ numberFormatter.format(value)} />
{
const numeric = typeof value === "number" ? value : Number(value);
if (key === "cost") return [currencyFormatter.format(numeric), "Cost"];
return [numberFormatter.format(numeric), key === "requests" ? "Requests" : "Tokens"];
}}
/>
+
+
-
-
+
Distribution
Requests by Provider
@@ -105,18 +131,17 @@ export function DashboardUsageGraphs({
-
- numberFormatter.format(value)} />
-
+
+ numberFormatter.format(value)} />
+
[numberFormatter.format(Number(value)), "Requests"]}
+ cursor={{ fill: "rgba(255,255,255,0.02)" }}
/>
-
+
diff --git a/src/components/dashboard/usage-breakdown-charts.tsx b/src/components/dashboard/usage-breakdown-charts.tsx
index 2245ad4..21c0349 100644
--- a/src/components/dashboard/usage-breakdown-charts.tsx
+++ b/src/components/dashboard/usage-breakdown-charts.tsx
@@ -1,6 +1,20 @@
"use client";
-import { Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
+import {
+ Area,
+ AreaChart,
+ Bar,
+ BarChart,
+ CartesianGrid,
+ Cell,
+ Legend,
+ Pie,
+ PieChart,
+ ResponsiveContainer,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from "recharts";
interface DailyPoint {
date: string;
@@ -17,6 +31,29 @@ interface BreakdownPoint {
cost: number;
}
+const PALETTE = [
+ "#3b82f6",
+ "#22d3ee",
+ "#8b5cf6",
+ "#34d399",
+ "#f59e0b",
+ "#f43f5e",
+ "#6366f1",
+ "#14b8a6",
+];
+
+const tooltipStyle = {
+ borderRadius: 12,
+ border: "1px solid rgba(255,255,255,0.06)",
+ backgroundColor: "hsl(220 16% 7%)",
+ boxShadow: "0 8px 32px rgba(0,0,0,0.5)",
+};
+
+const tooltipItemStyle = { color: "hsl(220 10% 80%)" };
+const tooltipLabelStyle = { color: "hsl(220 10% 55%)", marginBottom: 4 };
+
+const axisTick = { fill: "hsl(220 10% 45%)", fontSize: 12 };
+
export function UsageBreakdownCharts({
daily,
providers,
@@ -44,118 +81,166 @@ export function UsageBreakdownCharts({
return (
-
-
Daily Requests & Cost
-
-
-
-
- numberFormatter.format(value)}
- />
- currencyFormatter.format(value)}
- />
-
- name === "cost"
- ? [currencyFormatter.format(toNumber(value)), "Cost"]
- : [numberFormatter.format(toNumber(value)), "Requests"]
- }
- />
-
-
-
-
+ {/* Daily Requests & Cost - Area chart */}
+
+
Daily Requests & Cost
+
Last 30 days trend
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ numberFormatter.format(value)}
+ />
+ currencyFormatter.format(value)}
+ />
+
+ name === "cost"
+ ? [currencyFormatter.format(toNumber(value)), "Cost"]
+ : [numberFormatter.format(toNumber(value)), "Requests"]
+ }
+ />
+
+
+
+
+
+
-
-
Top Providers
-
-
-
-
- numberFormatter.format(value)} />
- [numberFormatter.format(toNumber(value)), name]}
- />
-
-
-
-
+ {/* Top Providers - Horizontal bar + Pie */}
+
+
Top Providers
+
Requests and tokens breakdown
+
+
+
+
+
+ numberFormatter.format(value)} />
+ [numberFormatter.format(toNumber(value)), name]}
+ />
+
+
+
+
+
+
-
-
Top Models
-
-
-
-
- numberFormatter.format(value)} />
- [numberFormatter.format(toNumber(value)), name]}
- />
-
-
-
-
+ {/* Top Models - Colorful bars */}
+
+
Top Models
+
Usage by model
+
+
+
+
+ numberFormatter.format(value)} />
+
+ [numberFormatter.format(toNumber(value)), "Requests"]}
+ />
+
+ {models.map((_, index) => (
+ |
+ ))}
+
+
+
+
-
-
Top API Keys
-
-
-
-
- numberFormatter.format(value)} />
- [numberFormatter.format(toNumber(value)), name]}
- />
-
-
-
-
+ {/* Top API Keys - Pie chart */}
+
+
Top API Keys
+
Request distribution by key
+
+
+ {keys.length > 0 ? (
+
+
+ {keys.map((_, index) => (
+ |
+ ))}
+
+ [numberFormatter.format(toNumber(value)), "Requests"]}
+ />
+
+
+ ) : (
+
+
+ No data
+
+
+ )}
+
+
);
diff --git a/src/components/layout/header.tsx b/src/components/layout/header.tsx
index 550525f..a252323 100644
--- a/src/components/layout/header.tsx
+++ b/src/components/layout/header.tsx
@@ -11,23 +11,23 @@ export function Header() {
const isAdminArea = pathname.startsWith("/admin");
return (
-
+
{isAdminArea && (
Dashboard
)}
-
-
{session?.user.email}
+
+
{session?.user.email}
signOut({ callbackUrl: "/login" })}
- className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
+ className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
>
Sign out
diff --git a/src/components/layout/sidebar.tsx b/src/components/layout/sidebar.tsx
index a710b9e..a841ecc 100644
--- a/src/components/layout/sidebar.tsx
+++ b/src/components/layout/sidebar.tsx
@@ -19,7 +19,11 @@ import {
TrendingUp,
Shield,
ArrowLeft,
+ Sparkles,
+ Menu,
+ X,
} from "lucide-react";
+import { useEffect, useState } from "react";
interface NavItem {
label: string;
@@ -29,7 +33,7 @@ interface NavItem {
const dashboardNav: NavItem[] = [
{ label: "Overview", href: "/dashboard", icon: LayoutDashboard },
- { label: "Playground", href: "/dashboard/playground", icon: MessageSquare },
+ { label: "Chat", href: "/chat", icon: MessageSquare },
{ label: "Docs", href: "/docs", icon: BookOpen },
{ label: "API Keys", href: "/dashboard/api-keys", icon: Key },
{ label: "Usage", href: "/dashboard/usage", icon: BarChart3 },
@@ -51,66 +55,102 @@ export function Sidebar({ variant }: { variant: "dashboard" | "admin" }) {
const { data: session } = useSession();
const items = variant === "admin" ? adminNav : dashboardNav;
const showAdminLink = variant === "dashboard" && session?.user.role === "ADMIN";
+ const [open, setOpen] = useState(false);
+
+ // Close on route change
+ useEffect(() => {
+ setOpen(false);
+ }, [pathname]);
return (
-
-
-
- LLM Proxy
-
-
-
- {variant === "admin" && (
- <>
-
-
- Back to Dashboard
-
-
- >
+ <>
+ {/* Mobile hamburger */}
+ setOpen(true)}
+ className="fixed left-3 top-3 z-40 flex h-10 w-10 items-center justify-center rounded-lg border border-white/[0.06] bg-[hsl(220,16%,5%)] text-muted-foreground md:hidden"
+ aria-label="Open menu"
+ >
+
+
+
+ {/* Overlay */}
+ {open && (
+ setOpen(false)} />
+ )}
+
+ {/* Sidebar */}
+
{
- const isActive =
- item.href === `/${variant === "admin" ? "admin" : "dashboard"}`
- ? pathname === item.href
- : pathname.startsWith(item.href);
- return (
-
-
- {item.label}
-
- );
- })}
- {showAdminLink && (
- <>
-
-
-
- Admin Portal
-
- >
- )}
-
-
+ >
+
+
+
+ LLM Proxy
+
+ setOpen(false)}
+ className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:text-foreground md:hidden"
+ aria-label="Close menu"
+ >
+
+
+
+
+ {variant === "admin" && (
+ <>
+
+
+ Back to Dashboard
+
+
+ >
+ )}
+ {items.map((item) => {
+ const isActive =
+ item.href === `/${variant === "admin" ? "admin" : "dashboard"}`
+ ? pathname === item.href
+ : pathname.startsWith(item.href);
+ return (
+
+
+ {item.label}
+
+ );
+ })}
+ {showAdminLink && (
+ <>
+
+
+
+ Admin Portal
+
+ >
+ )}
+
+
+ >
);
}
diff --git a/src/lib/db.ts b/src/lib/db.ts
index ccb9355..29863c2 100644
--- a/src/lib/db.ts
+++ b/src/lib/db.ts
@@ -417,4 +417,7 @@ export const db = {
requestLog: makeModel("requestLog", "request_logs"),
usageAggregateDaily: makeModel("usageAggregateDaily", "usage_aggregates_daily"),
ingestionBatch: makeModel("ingestionBatch", "ingestion_batches"),
+ chatConversation: makeModel("chatConversation", "chat_conversations"),
+ chatMessage: makeModel("chatMessage", "chat_messages"),
+ userPreference: makeModel("userPreference", "user_preferences"),
};
diff --git a/src/lib/validations/chat-completion.ts b/src/lib/validations/chat-completion.ts
index c4fb87a..2829582 100644
--- a/src/lib/validations/chat-completion.ts
+++ b/src/lib/validations/chat-completion.ts
@@ -1,8 +1,19 @@
import { z } from "zod";
+const contentPartSchema = z.discriminatedUnion("type", [
+ z.object({ type: z.literal("text"), text: z.string() }),
+ z.object({
+ type: z.literal("image_url"),
+ image_url: z.object({
+ url: z.string(),
+ detail: z.enum(["auto", "low", "high"]).optional(),
+ }),
+ }),
+]);
+
const chatMessageSchema = z.object({
role: z.enum(["system", "user", "assistant", "tool"]),
- content: z.union([z.string(), z.null()]),
+ content: z.union([z.string(), z.array(contentPartSchema), z.null()]),
name: z.string().optional(),
tool_calls: z
.array(
diff --git a/src/server/adapters/base.ts b/src/server/adapters/base.ts
index 1e18db1..a9f82b7 100644
--- a/src/server/adapters/base.ts
+++ b/src/server/adapters/base.ts
@@ -1,4 +1,7 @@
import type {
+ AudioSpeechRequest,
+ ImageGenerationRequest,
+ ImageGenerationResponse,
ProviderAdapter,
ProviderKeyContext,
ProviderKeyMetadata,
@@ -46,7 +49,6 @@ export abstract class OpenAICompatibleAdapter implements ProviderAdapter {
};
if (req.temperature !== undefined) body.temperature = req.temperature;
if (req.top_p !== undefined) body.top_p = req.top_p;
- if (req.max_tokens !== undefined) body.max_tokens = req.max_tokens;
if (req.stop !== undefined) body.stop = req.stop;
if (req.presence_penalty !== undefined) body.presence_penalty = req.presence_penalty;
if (req.frequency_penalty !== undefined) body.frequency_penalty = req.frequency_penalty;
@@ -171,6 +173,68 @@ export abstract class OpenAICompatibleAdapter implements ProviderAdapter {
return (await response.json()) as UnifiedEmbeddingResponse;
}
+ async imageGeneration(req: ImageGenerationRequest, ctx: ProviderKeyContext): Promise
{
+ const body: Record = {
+ model: ctx.providerModelId,
+ prompt: req.prompt,
+ response_format: "b64_json",
+ };
+ if (req.n !== undefined) body.n = req.n;
+ if (req.size !== undefined) body.size = req.size;
+ if (req.quality !== undefined) body.quality = req.quality;
+ if (req.style !== undefined) body.style = req.style;
+
+ const response = await fetch(`${ctx.providerBaseUrl}/v1/images/generations`, {
+ method: "POST",
+ headers: this.buildHeaders(ctx),
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(ctx.timeout),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => "Unknown error");
+ logger.error({ status: response.status, body: errorText, provider: this.id }, "Provider image generation error");
+ throw new ApiError(
+ response.status,
+ `Provider ${this.id} returned ${response.status}: ${errorText.slice(0, 200)}`,
+ "server_error",
+ "provider_error",
+ );
+ }
+
+ return (await response.json()) as ImageGenerationResponse;
+ }
+
+ async audioSpeech(req: AudioSpeechRequest, ctx: ProviderKeyContext): Promise {
+ const body: Record = {
+ model: ctx.providerModelId,
+ input: req.input,
+ voice: req.voice,
+ };
+ if (req.response_format) body.response_format = req.response_format;
+ if (req.speed !== undefined) body.speed = req.speed;
+
+ const response = await fetch(`${ctx.providerBaseUrl}/v1/audio/speech`, {
+ method: "POST",
+ headers: this.buildHeaders(ctx),
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(ctx.timeout),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => "Unknown error");
+ logger.error({ status: response.status, body: errorText, provider: this.id }, "Provider audio speech error");
+ throw new ApiError(
+ response.status,
+ `Provider ${this.id} returned ${response.status}: ${errorText.slice(0, 200)}`,
+ "server_error",
+ "provider_error",
+ );
+ }
+
+ return response.arrayBuffer();
+ }
+
async validateApiKey(key: string): Promise {
try {
const response = await fetch(`${this.defaultBaseUrl}/v1/models`, {
diff --git a/src/server/services/model-router.ts b/src/server/services/model-router.ts
index 708f411..ccc0e1b 100644
--- a/src/server/services/model-router.ts
+++ b/src/server/services/model-router.ts
@@ -2,7 +2,7 @@ import { getMongoDb } from "@/lib/mongo";
import { decrypt } from "./encryption";
import { getAdapter } from "@/server/adapters";
import { DEFAULT_PROVIDER_TIMEOUT_MS } from "@/lib/constants";
-import type { ProviderAdapter, ProviderKeyContext } from "@/types/provider";
+import type { ModelType, ProviderAdapter, ProviderKeyContext } from "@/types/provider";
type ProviderDocument = {
_id: string;
@@ -27,6 +27,7 @@ type ModelMappingDocument = {
logicalModelId: string;
priority: number;
enabled: boolean;
+ modelType?: ModelType;
createdAt: Date;
};
@@ -37,6 +38,7 @@ export interface ResolvedRoute {
providerApiKeyId: string;
logicalModelId: string;
providerModelId: string;
+ modelType: ModelType;
}
const localRoundRobinByProvider = new Map();
@@ -46,6 +48,7 @@ async function resolveRouteForMapping(
providerId: string;
providerModelId: string;
logicalModelId: string;
+ modelType?: ModelType;
provider: { baseUrl: string; config?: Record; enabled: boolean };
},
): Promise {
@@ -89,6 +92,7 @@ async function resolveRouteForMapping(
providerApiKeyId: selectedKey._id,
logicalModelId: mapping.logicalModelId,
providerModelId: mapping.providerModelId,
+ modelType: mapping.modelType ?? "chat",
};
}
@@ -115,6 +119,7 @@ export async function resolveModelRouteCandidates(logicalModelId: string): Promi
providerId: mapping.providerId,
providerModelId: mapping.providerModelId,
logicalModelId: mapping.logicalModelId,
+ modelType: mapping.modelType,
provider: { baseUrl: provider.baseUrl, config: provider.config, enabled: provider.enabled },
});
if (route) candidates.push(route);
diff --git a/src/server/services/request-handler.ts b/src/server/services/request-handler.ts
index 340e64b..9981fe0 100644
--- a/src/server/services/request-handler.ts
+++ b/src/server/services/request-handler.ts
@@ -26,7 +26,7 @@ interface RouteLogContext extends BaseRequestContext {
function summarizeChatPrompt(req: UnifiedChatRequest): string {
return req.messages
- .map((message) => `${message.role}: ${message.content ?? ""}`)
+ .map((message) => `${message.role}: ${typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content.filter((p) => p.type === "text").map((p) => (p as { text: string }).text).join("") : ""}`)
.join("\n")
.slice(0, 5000);
}
@@ -190,7 +190,7 @@ export async function handleChatCompletion(request: Request): Promise
latencyMs,
streamed: false,
promptText: summarizeChatPrompt(unifiedReq),
- responseText: result.choices[0]?.message.content ?? undefined,
+ responseText: typeof result.choices[0]?.message.content === "string" ? result.choices[0].message.content : undefined,
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log usage"));
diff --git a/src/types/provider.ts b/src/types/provider.ts
index ea69375..b529c77 100644
--- a/src/types/provider.ts
+++ b/src/types/provider.ts
@@ -1,6 +1,30 @@
import type { UnifiedChatRequest, UnifiedCompletionRequest, UnifiedEmbeddingRequest } from "./unified-request";
import type { UnifiedChatResponse, UnifiedCompletionResponse, UnifiedEmbeddingResponse } from "./unified-response";
+export type ModelType = "chat" | "image" | "audio";
+
+export interface ImageGenerationRequest {
+ prompt: string;
+ model: string;
+ n?: number;
+ size?: string;
+ quality?: string;
+ style?: string;
+}
+
+export interface ImageGenerationResponse {
+ created: number;
+ data: Array<{ url?: string; b64_json?: string; revised_prompt?: string }>;
+}
+
+export interface AudioSpeechRequest {
+ model: string;
+ input: string;
+ voice: string;
+ response_format?: "mp3" | "opus" | "aac" | "flac" | "wav" | "pcm";
+ speed?: number;
+}
+
export interface ProviderKeyContext {
decryptedKey: string;
providerModelId: string;
@@ -35,5 +59,7 @@ export interface ProviderAdapter {
completion?(req: UnifiedCompletionRequest, ctx: ProviderKeyContext): Promise;
embeddings?(req: UnifiedEmbeddingRequest, ctx: ProviderKeyContext): Promise;
+ imageGeneration?(req: ImageGenerationRequest, ctx: ProviderKeyContext): Promise;
+ audioSpeech?(req: AudioSpeechRequest, ctx: ProviderKeyContext): Promise;
listModels?(ctx: ProviderKeyContext): Promise;
}
diff --git a/src/types/unified-request.ts b/src/types/unified-request.ts
index b71504c..8467912 100644
--- a/src/types/unified-request.ts
+++ b/src/types/unified-request.ts
@@ -1,6 +1,21 @@
+export interface ChatMessageContentPartText {
+ type: "text";
+ text: string;
+}
+
+export interface ChatMessageContentPartImage {
+ type: "image_url";
+ image_url: {
+ url: string;
+ detail?: "auto" | "low" | "high";
+ };
+}
+
+export type ChatMessageContentPart = ChatMessageContentPartText | ChatMessageContentPartImage;
+
export interface ChatMessage {
role: "system" | "user" | "assistant" | "tool";
- content: string | null;
+ content: string | ChatMessageContentPart[] | null;
name?: string;
tool_calls?: ToolCall[];
tool_call_id?: string;